0% found this document useful (0 votes)
111 views46 pages

C++ Notes

1. The document discusses the basics of C++ programming language, including data types, variables, operators, loops, and decision making. 2. It explains that all variables in C++ require a data type that determines the type of data stored and amount of memory allocated. 3. There are three main data types in C++ - primitive, derived, and user-defined - with primitive types like int, char, float for integers, characters, and floating point numbers.

Uploaded by

Divyanshu Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
111 views46 pages

C++ Notes

1. The document discusses the basics of C++ programming language, including data types, variables, operators, loops, and decision making. 2. It explains that all variables in C++ require a data type that determines the type of data stored and amount of memory allocated. 3. There are three main data types in C++ - primitive, derived, and user-defined - with primitive types like int, char, float for integers, characters, and floating point numbers.

Uploaded by

Divyanshu Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 46

C++ is a general-purpose programming language and widely used nowadays for

competitive programming. It has imperative, object-oriented and generic programming


features. C++ runs on lots of platform like Windows, Linux, Unix, Mac, etc.
However to become proficient in any programming language, one Firstly needs to
understand the basics of that language.
Therefore, below are the basics of C++ in the format in which it will help you the most to
get the headstart:
1. Basic Syntax and First Program in C++: Learning C++ programming can be
simplified into writing your program in a text editor and saving it with correct
extension(.CPP, .C, .CP) and compiling your program using a compiler or online IDE.
The “Hello World” program is the first step towards learning any programming
language and also one of the simplest programs you will learn.
2. Basic I/O in C++:C++ comes with libraries which provides us with many ways for
performing input and output. In C++ input and output is performed in the form of a
sequence of bytes or more commonly known as streams. The two keywords cout and
cin are used very often for taking inputs and printing outputs. These two are the most
basic methods of taking input and output in C++.
3. Comments in C++: A well-documented program is a good practice as a
programmer. It makes a program more readable and error finding become easier. One
important part of good documentation is Comments. In computer programming, a
comment is a programmer-readable explanation or annotation in the source code of a
computer program. These are statements that are not executed by the compiler and
interpreter.
4. Data Types and Modifiers in C++: All variables use data-type during declaration to
restrict the type of data to be stored. Therefore, we can say that data types are used
to tell the variables the type of data it can store. Whenever a variable is defined in C+
+, the compiler allocates some memory for that variable based on the data-type with
which it is declared. Every data type requires a different amount of memory.
5. Uninitialized variable in C++: “One of the things that has kept C++ viable is the
zero-overhead rule: What you don’t use, you don’t pay for.” -Stroustrup. The overhead
of initializing a stack variable is costly as it hampers the speed of execution, therefore
these variables can contain indeterminate values. It is considered a best practice to
initialize a primitive data type variable before using it in code.
6. Undefined Behaviour in C++: If a user starts learning in C/C++ environment and is
unclear with the concept of undefined behaviour then that can bring plenty of
problems in the future like while debugging someone else code might be actually
difficult in tracing the root to the undefined error.
7. Variables and Types in C++: A variable is a name given to a memory location. It is
the basic unit of storage in a program. The value stored in a variable can be changed
during program execution. A variable is only a name given to a memory location, all
the operations done on the variable effects that memory location. In C++, all the
variables must be declared before use.
8. Variable Scope in C++: In general, scope is defined as the extent up to which
something can be worked with. In programming also the scope of a variable is defined
as the extent of the program code within which the variable can we accessed or
declared or worked with. There are mainly two types of variable scopes, Local and
Global Variables.
9. Constants and liberals in C++: As the name suggests the name constants is given
to such variables or values in C++ programming language which cannot be modified
once they are defined. They are fixed values in a program. There can be any types of
constants like integer, float, octal, hexadecimal, character constants, etc. Every
constant has some range. The integers that are too big to fit into an int will be taken
as long. Now there are various ranges that differ from unsigned to signed bits. Under
the signed bit, the range of an int varies from -128 to +127 and under the unsigned bit,
int varies from 0 to 255. Literals are kind of constants and both the terms are used
interchangeably in C++.
10. Types of literals in C++ : In this article we will analyse the various kind of literals
that C++ provides. The values assigned to each constant variables are referred to as
the literals. Generally, both terms, constants and literals are used interchangeably. For
eg, “const int = 5;“, is a constant expression and the value 5 is referred to as constant
integer literal.
11. Access Modifiers in C++: Access modifiers are used to implement an important
feature of Object-Oriented Programming known as Data Hiding. Access modifiers or
Access Specifiers in a class are used to set the accessibility of the class members.
That is, it sets some restrictions on the class members not to get directly accessed by
the outside functions.
12. Storage classes in C++:  Storage Classes are used to describe the features of a
variable/function. These features basically include the scope, visibility, and life-time
which help us to trace the existence of a particular variable during the runtime of a
program.
13. Operators in C++: Operators are the foundation of any programming language.
Thus the functionality of C/C++ programming language is incomplete without the use
of operators. We can define operators as symbols that help us to perform specific
mathematical and logical computations on operands. In other words, we can say that
an operator operates the operands.
14. Loops in C++: Loops in programming comes into use when we need to repeatedly
execute a block of statements. For example: Suppose we want to print “Hello World”
10 times. This can be done in two ways, Iterative method and by using Loops.
15. Decision making in C++: There comes situations in real life when we need to make
some decisions and based on these decisions, we decide what should we do next.
Similar situations arise in programming also where we need to make some decisions
and based on these decisions we will execute the next block of code. Decision-making
statements in programming languages decide the direction of flow of program
execution.
16. Forward declarations in C++: It refers to the beforehand declaration of the syntax
or signature of an identifier, variable, function, class, etc. prior to its usage (done later
in the program). In C++, Forward declarations are usually used for Classes. In this,
the class is pre-defined before its use so that it can be called and used by other
classes that are defined before this.
17. Errors in C++: Error is an illegal operation performed by the user which results in
abnormal working of the program. Programming errors often remain undetected until
the program is compiled or executed. Some of the errors inhibit the program from
getting compiled or executed. Thus errors should be removed before compiling and
executing.

C++ Data Types


All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data it can
store. Whenever a variable is defined in C++, the compiler allocates some memory for
that variable based on the data-type with which it is declared. Every data type requires a
different amount of memory.
 

Data types in C++ is mainly divided into three types: 


 
1. Primitive Data Types: These data types are built-in or predefined data types and
can be used directly by the user to declare variables. example: int, char , float, bool
etc. Primitive data types available in C++ are: 
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character
2. Derived data types: The data-types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types. These can be of four types namely: 
 Function
 Array
 Pointer
 Reference
3. Abstract or user defined data types : These data types are defined by user itself.
Like, defining a class in C++ or a structure. C++ provides the following user-defined
datatypes: 
 Class
 Structure
 Union
 Enumeration
 Types of defined DataType
This article discusses primitive data types available in C++. 
 
 Integer: Keyword used for integer data types is int. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647. 
 
 Character: Character data type is used for storing characters. Keyword used for
character data type is char. Characters typically requires 1 byte of memory space and
ranges from -128 to 127 or 0 to 255. 
 
 Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean data type
is bool. 
 
 Floating Point: Floating Point data type is used for storing single precision floating
point values or decimal values. Keyword used for floating point data type is float.
Float variables typically requires 4 byte of memory space. 
 
 Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating
point data type is double. Double variables typically requires 8 byte of memory
space. 
 
 void: Void means without any value. void datatype represents a valueless entity.
Void data type is used for those function which does not returns a value. 

 Wide character: Wide character data type is also a character data type but this
data type has size greater than the normal 8-bit datatype. Represented by wchar_t. It
is generally 2 or 4 bytes long. 
 
 

Datatype Modifiers
As the name implies, datatype modifiers are used with the built-in data types to modify
the length of data that a particular data type can hold. 
 
Data type modifiers available in C++ are: 
 
 Signed
 Unsigned
 Short
 Long

// C++ program to sizes of data types

#include<iostream>

using namespace std;

int main()

cout << "Size of char : " << sizeof(char)

<< " byte" << endl;

cout << "Size of int : " << sizeof(int)

<< " bytes" << endl;

cout << "Size of short int : " << sizeof(short int)

<< " bytes" << endl;

cout << "Size of long int : " << sizeof(long int)

<< " bytes" << endl;

cout << "Size of signed long int : " << sizeof(signed long int)

<< " bytes" << endl;

cout << "Size of unsigned long int : " << sizeof(unsigned long int)

<< " bytes" << endl;


cout << "Size of float : " << sizeof(float)

<< " bytes" <<endl;

cout << "Size of double : " << sizeof(double)

<< " bytes" << endl;

cout << "Size of wchar_t : " << sizeof(wchar_t)

<< " bytes" <<endl;

return 0;

Variables in C++
A variable is a name given to a memory location. It is the basic unit of storage in a
program. 
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on
the variable effects that memory location.
 In C++, all the variables must be declared before use.
 
How to declare variables?
A typical variable declaration is of the form: 

 // Declaring a single variable


Type variable_name;

// Declaring multiple bvariables:


Type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‘_’ character. However, the name must not start with a number.
 
In the above diagram,
data type : Type of data that can be stored in this variable.
Variable_name: Name given to the variable.
Value: It is the initial value stored  in the variable

Examples: 
// Declaring float variable
float simple_interest;

// Declaring integer variable


int time, speed;

// Declaring character variable


Char var;
 
 
Difference between variable declaration and definition
The variable declaration refers to the part where a variable is first declared or
introduced before its first use. A variable definition is a part where the variable is
assigned a memory location and a value. Most of the times, variable declaration and
definition are done together.
See the following C++ program for better clarification: 
 
 CPP

#include <iostream>
using namespace std;

  

int main()

    // declaration and definition

    // of variable 'a123'

    char a123 = 'a';

  

    // This is also both declaration and definition

    // as 'b' is allocated memory and

    // assigned some garbage value.

    float b;

  

    // multiple declarations and definitions

    int _c, _d45, e;

  

    // Let us print a variable

    cout << a123 << endl;

  

    return 0;

Output: 
a
 
Types of variables
There are three types of variables based on the scope of variables in C++: 
 
 Local Variables
 Instance Variables
 Static Variables
 

Let us now learn about each one of these variables in detail. 


 
1. Local Variables: A variable defined within a block or method or constructor is
called local variable. 
 These variable are created when the block in entered or the function is called
and destroyed after exiting from the block or when the call returns from the
function.
 The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access these variable only within that block.
 Initialisation of Local Variable is Mandatory.
2. Instance Variables: Instance variables are non-static variables and are declared
in a class outside any method, constructor or block. 
 As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier then the default access specifier will be
used.
 Initialisation of Instance Variable is not Mandatory.
 Instance Variable can be accessed only by creating objects.
3. Static Variables: Static variables are also known as Class variables. 
 These variables are declared similarly as instance variables, the difference is
that static variables are declared using the static keyboard within a class outside
any method constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per
class irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initialization of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The
compiler will replace the object name to class name automatically.
 If we access the static variable without the class name, Compiler will
automatically append the class name.
 
Instance variable Vs Static variable
 
 Each object will have its own copy of instance variable whereas We can only
have one copy of a static variable per class irrespective of how many objects we
create.
 Changes made in an instance variable using one object will not be reflected in
other objects as each object has its own copy of instance variable. In case of static,
changes will be reflected in other objects as static variables are common to all object
of a class.
 We can access instance variables through object references and Static Variables
can be accessed directly using class name.
 Syntax for static and instance variables:
 class Example
 {
 static int a; // static variable
 int b; // instance variable
}

Loops in C and C++


Loops in programming come into use when we need to repeatedly execute a block
of statements. For example: Suppose we want to print “Hello World” 10 times. This
can be done in two ways as shown below:

// C++ program to illustrate need of loops


#include <iostream>
Using namespace std;
Int main () {
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Cout<<”hello world\n”;
Return 0;
}

OUTPUT
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world

In Loop, the statement needs to be written only once and the loop will be executed
10 times as shown below.
In computer programming, a loop is a sequence of instructions that is repeated
until a certain condition is reached.
 An operation is done, such as getting an item of data and changing it, and
then some condition is checked such as whether a counter has reached a
prescribed number.
 Counter not Reached: If the counter has not reached the desired number,
the next instruction in the sequence returns to the first instruction in the
sequence and repeat it.
 Counter reached: If the condition has been reached, the next instruction
“falls through” to the next sequential instruction or branches outside the loop.
There are mainly two types of loops:
1. Entry Controlled loops: In this type of loops the test condition is tested
before entering the loop body. For Loop and While Loop are entry controlled
loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or
evaluated at the end of loop body. Therefore, the loop body will execute atleast
once, irrespective of whether the test condition is true or false. do – while
loop is exit controlled loop.

for Loop
A for loop is a repetition control structure which allows us to write a loop that is
executed a specific number of times. The loop enables us to perform n number of
steps together in one line.
Syntax:

For (initialization expr; test expr; update expr)


{
// body of the loop
// statements we want to execute
}

In for loop, a loop variable is used to control the loop. First initialize this loop
variable to some value, then check whether this variable is less than or greater
than counter value. If statement is true, then loop body is executed and loop
variable gets updated. Steps are repeated till exit condition comes.
 Initialization Expression: In this expression we have to initialize the loop
counter to some value. for example: int i=1;
 Test Expression: In this expression we have to test the condition. If the
condition evaluates to true then we will execute the body of loop and go to
update expression otherwise we will exit from the for loop. For example: i <= 10;
 Update Expression: After executing loop body this expression
increments/decrements the loop variable by some value. for example: i++;
Equivalent flow diagram for loop :

Example:

// C++ program to illustrate for loop


#include <iostream>
Using namespace std;
Int main () {
For ( int i=1; I <=10; i++)
{ cout << “hello world\n”;
}
Return 0;
}

OUTPUT
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
While Loop
While studying for loop we have seen that the number of iterations is known
beforehand, i.e. the number of times the loop body is needed to be executed is
known to us. while loops are used in situations where we do not know the exact
number of iterations of loop beforehand. The loop execution is terminated on the
basis of test condition.
Syntax:
We have already stated that a loop is mainly consisted of three statements –
initialization expression, test expression, update expression. The syntax of the
three loops – For, while and do while mainly differs on the placement of these
three statements.

Initialization expression;
While (test_expression)
{ // statements
Update_expressions;
}
Flow Diagram:

Example:

// c++ program to illustrate while loop


#include namespace std;

Int main()
{
//initialization expression
Int I = 1;

// test expression
While (i<6)
{
Cout<< “hello world\n”;

// update expression
I++;
}
Return 0;
}

OUTPUT

Hello world
Hello world
Hello world
Hello world
Hello world

do while loop
In do while loops also the loop execution is terminated on the basis of test
condition. The main difference between do while loop and while loop is in do while
loop the condition is tested at the end of loop body, i.e do while loop is exit
controlled whereas the other two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test
condition.

Syntax:

Initialization expression;
Do
{
// statements

Update_expression;
}while (test_expression);

Note: Notice the semi – colon(“;”) in the end of loop.


Flow Diagram:

Example:

// C++ program to illustrate do while loop


#Include <iostream>
Using namespace std;

Int main()
{
Int I = 2; // initialization expression

Do
{
// loop body
Cout <<”hello world\n”;

// update expression
I++;

} while (i<1); // test expression

Return 0;
}
OUTPUT
HELLO WORLD

In the above program the test condition (i<1) evaluates to false. But still as the loop
is exit – controlled the loop body will execute once.
What about an Infinite Loop?
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks
a functional exit so that it repeats indefinitely. An infinite loop occurs when a
condition always evaluates to true. Usually, this is an error.

// C++ program to demonstrate infinite loops

// using for and while

// Uncomment the sections to see the output

#include <iostream>

using namespace std;

int main ()

int i;

// This is an infinite for loop as the condition

// expression is blank

for ( ; ; )

cout << "This loop will run forever.\n";

// This is an infinite for loop as the condition


// given in while loop will keep repeating infinitely

/*

while (i != 0)

i-- ;

cout << "This loop will run forever.\n";

*/

// This is an infinite for loop as the condition

// given in while loop is "true"

/*

while (true)

cout << "This loop will run forever.\n";

*/
}

OUTPUT
This loop will run forever.
This loop will run forever.
…..

Important Points:
 Use for loop when number of iterations is known beforehand, i.e. the number
of times the loop body is needed to be executed is known.
 Use while loops where exact number of iterations is not known but the loop
termination condition is known.
 Use do while loop if the code needs to be executed at least once like in Menu
driven programs

Decision Making in C / C++ (if , if..else,


Nested if, if-else-if )
There come situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next. Similar situations
arise in programming also where we need to make some decisions and based on
these decisions we will execute the next block of code. For example, in C if x
occurs then execute y else execute z. There can also be multiple conditions like in
C if x occurs then execute p, else if condition y occurs execute q, else execute r.
This condition of C else-if is one of the many ways of importing multiple
conditions. 

Decision-making statements in programming languages decide the direction of the


flow of program execution. Decision-making statements available in C or C++ are: 
1. if statement
2. If else statement
3. nested if statement
4. If-else-if ladder
5. Switch statements
6. Jump statements:
1. Break
2. continue
3. Goto
4. Return
 
if statement in C/C++
if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not. 
Syntax: 

if( condition)
{
// statements to execute if
// condition is true
}
 
Here, the condition after evaluation will be either true or false. C if statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not. If we do not provide the curly braces ‘{‘ and ‘}’
after if(condition) then by default if statement will consider the first immediately
below statement to be inside its block. 
Example: 

If (condition)
Statement1;
Statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block
 
Flowchart 
 
// C++ program to illustrate If statement

#include<iostream>

using namespace std;

int main()

int i = 10;

if (i > 15)

cout<<"10 is less than 15";

cout<<"I am Not in if";


}

OUTPUT
I am Not in if

As the condition present in the if statement is false. So, the block below the if
statement is not executed.
 
if-else in C/C++

The if  statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false. Here comes the C else  statement. We can
use the else  statement with if  statement to execute a block of code when the
condition is false. 
Syntax: 
If (condition)
{
// executes this block if
// condition is true
}
Else
{
// executes this block if
// condition is false
}

Flowchart: 
 

Example:

// C++ program to illustrate if-else statement


#include<iostream>
using namespace std;

int main()
{
int i = 20;

if (i < 15)
cout<<"i is smaller than 15";
else
cout<<"i is greater than 15";

return 0;
}
OUTPUT
I is greater than 15
The block of code following the else  statement is executed as the condition
present in the if  statement is false.
 
nested-if in C/C++
A nested if in C is an if statement that is the target of another if statement. Nested
if statements mean an if statement inside another if statement. Yes, both C and C+
+ allow us to nested if statements within if statements, i.e, we can place an if
statement inside another if statement. 
Syntax: 

If (condition1)
{
// executes when condition1 is true
If (condition2)
{
// executes when condition2 is true
}
}

Flowchart 
 
Example: 

// C++ program to illustrate nested-if statement


#include <iostream>
using namespace std;

int main()
{
int i = 10;

if (i == 10)
{
// First if statement
if (i < 15)
cout<<"i is smaller than 15\n";

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
cout<<"i is smaller than 12 too\n";
else
cout<<"i is greater than 15";
}
return 0;
}

OUTPUT

I is smaller than 15
I is smaller than 12 too

if-else-if ladder in C/C++


Here, a user can decide among multiple options. The C if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions are true, then the final else statement will be
executed. 
Syntax: 

If (condition)
Statement;
Else if (condition)
Statement;
.
.
Else
Statement;
Example: 

// C++ program to illustrate if-else-if ladder

#include<iostream>

using namespace std;

int main()

int i = 20;

if (i == 10)

cout<<"i is 10";

else if (i == 15)

cout<<"i is 15";

else if (i == 20)

cout<<"i is 20";

else

cout<<"i is not present";


}

OUTPUT
I is 20

Jump Statements in C/C++


These statements are used in C orC++ for the unconditional flow of control
throughout the functions in a program. They support four types of jump statements:
 
1. C loop: This loop control statement is used to terminate the loop. As soon as
the break statement is encountered from within a loop, the loop iterations stop
there, and control returns from the loop immediately to the first statement after
the loop. 

Syntax: 
 break;

1. Basically, break statements are used in situations when we are not sure
about the actual number of iterations for the loop or we want to terminate the
loop based on some condition. 
 

1. Example: 

// CPP program to illustrate


// Linear Search
#include <iostream>
using namespace std;

void findElement(int arr[], int size, int key)


{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
cout << "Element found at position: " << (i + 1);
break;
}
}
}
// Driver program to test above function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = 6; // no of elements
int key = 3; // key to be searched

// Calling function to find the key


findElement(arr, n, key);

return 0;
}

OUTPUT
Element found at position : 3

1.  C
2. C continues: This loop control statement is just like the break statement.
The continue statement is opposite to that of the break statement, instead of
terminating the loop, it forces to execute the next iteration of the loop. 
As the name suggests the continue statement forces the loop to continue or
execute the next iteration. When the continue statement is executed in the loop,
the code inside the loop following the continue statement will be skipped and the
next iteration of the loop will begin. 

Syntax: 

Continue;

1. Example: 
// C++ program to explain the use

// of continue statement

#include <iostream>

using namespace std;

int main()

// loop from 1 to 10

for (int i = 1; i <= 10; i++) {

// If i is equals to 6,

// continue to next iteration

// without printing

if (i == 6)

continue;

else

// otherwise print the value of i

cout << i << " ";

return 0;
}
OUTPUT
1 2 3 4 5 7 8 9 10

If you create a variable in if-else in C/C++, it will be local to that if/else block only. You
can use global variables inside the if/else block. If the name of the variable you created in
if/else is as same as any global variable then priority will be given to `local variable`. 

#include<iostream>

using namespace std;

int main(){

int gfg=0; // local variable for main

cout<<"Before if-else block "<<gfg<<endl;

if(1){

int gfg = 100; // new local variable of if block

cout<<"if block "<<gfg<<endl;

cout<<"After if block "<<gfg<<endl;

return 0;

/*

Before if-else block 0

if block 100

After if block 0
*/
C Goto: The goto statement in C/C++ also referred to as unconditional jump statement
can be used to jump from one point to another within a function. 
Syntax: 

Syntax1 | Syntax2
------------------------------------------------
Goto label; | label:
. | .
. | .
. | .
Label: | goto label;

1. In the above syntax, the first line tells the compiler to go to or jump to the
statement marked as a label. Here label is a user-defined identifier that
indicates the target statement. The statement immediately followed after ‘label:’
is the destination statement. The ‘label:’ can also appear before the ‘goto label;’
statement in the above syntax. 
 

1. Below are some examples of how to use goto statement:


Examples: 

// C++ program to print numbers

// from 1 to 10 using goto statement


#include <iostream>

using namespace std;

// function to print numbers from 1 to 10

void printNumbers()

int n = 1;

label:

cout << n << " ";

n++;

if (n <= 10)

goto label;

// Driver program to test above function

int main()

printNumbers();

return 0;
}

OUTPUT
1 2 3 4 5 6 7 8 9 10
1. C Return: The return in C or C++ returns the flow of the execution to the function
from where it is called. This statement does not mandatorily need any conditional
statements. As soon as the statement is executed, the flow of the program stops
immediately and return the control from where it was called. The return statement may
or may not return anything for a void function, but for a non-void function, a return
value is must be returned. 
Syntax: 
 
Return[ expression ];
1. Example: 
 

// C++ code to illustrate return

// statement

#include <iostream>

using namespace std;

// non-void return type

// function to calculate sum

int SUM(int a, int b)

int s1 = a + b;

return s1;

// returns void

// function to print

void Print(int s2)

cout << "The sum is "<< s2;

return;

int main()
{

int num1 = 10;

int num2 = 10;

int sum_of = SUM(num1, num2);

Print(sum_of);

return 0;
}

OUTPUT
The sum is 20

Arrays in C/C++
An array in C/C++ or be it in any programming language is a collection of similar
data items stored at contiguous memory locations and elements can be accessed
randomly using indices of an array.  They can be used to store collection of
primitive data types such as int, float, double, char, etc of any particular type. To
add to it, an array in C/C++ can store derived data types such as the structures,
pointers etc. Given below is the picture representation of an array.
 

Why do we need arrays? 


We can use normal variables (v1, v2, v3, ..) when we have a small number of
objects, but if we want to store a large number of instances, it becomes difficult to
manage them with normal variables. The idea of an array is to represent many
instances in one variable.
Array declaration in C/C++: 
 
 

Note: In above image int a[3]={[0…1]=3}; this kind of declaration has been
obsolete since GCC 2.5
There are various ways in which we can declare an array. It can be done by
specifying its type and size, by initializing it or both.
Array declaration by specifying size 

// Array declaration by specifying size

int arr1[10];

// With recent C/C++ versions, we can also

// declare an array of user specified size

int n = 10;
int arr2[n];

Array declaration by initializing elements

// Array declaration by initializing elements

int arr[] = { 10, 20, 30, 40 }


// Compiler creates an array of size 4.
// above is same as "int arr[4] = {10, 20, 30, 40}"

Array declaration by specifying size and initializing elements

// Array declaration by specifying size and initializing


// elements
int arr[6] = { 10, 20, 30, 40 }

// Compiler creates an array of size 6, initializes first


// 4 elements as specified by user and rest two elements as
// 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"

Advantages of an Array in C/C++: 


1. Random access of elements using array index.
2. Use of less line of code as it creates a single array of multiple elements.
3. Easy access to all the elements.
4. Traversal through the array becomes easy using a single loop.
5. Sorting becomes easy as it can be accomplished by writing less line of code.
Disadvantages of an Array in C/C++: 
1. Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
2. Insertion and deletion of elements can be costly since the elements are needed to
be managed in accordance with the new memory allocation.
Facts about Array in C/C++: 

 Accessing Array Elements: 


Array elements are accessed by using an integer index. Array index starts with 0 and
goes till size of array minus 1.
 Name of the array is also a pointer to the first element of array.
 

Example: 
#include <iostream>
using namespace std;

int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;

// this is same as arr[1] = 2


arr[3 / 2] = 2;
arr[3] = arr[0];

cout << arr[0] << " " << arr[1] << " " << arr[2] << " "
<< arr[3];

return 0;
}

OUTPUT
5 2 -10 5

No Index Out of bound Checking: 


There is no index out of bounds checking in C/C++, for example, the following program
compiles fine but may produce unexpected output when run.  
 
// This C++ program compiles fine
// as index out of bound
// is not checked in C.

#include <iostream>
using namespace std;

int main()
{
int arr[2];

cout << arr[3] << " ";


cout << arr[-2] << " ";

return 0;
}

OUTPUT
-449684907 4195777

In C, it is not a compiler error to initialize an array with more elements than the specified
size. For example, the below program compiles fine and shows just Warning.

#include <stdio.h>
int main()
{

// Array declaration by initializing it


// with more elements than specified size.
int arr[2] = { 10, 20, 30, 40, 50 };

return 0;
}

Warnings: 

(There will some warnings. I am not writing the warnings. Write the program and run to
check the warnings.)

The elements are stored at contiguous memory locations 


Example: 

// C++ program to demonstrate that array elements


// are stored contiguous locations

#include <iostream>
using namespace std;

int main()
{
// an array of 10 integers.
// If arr[0] is stored at
// address x, then arr[1] is
// stored at x + sizeof(int)
// arr[2] is stored at x +
// sizeof(int) + sizeof(int)
// and so on.
int arr[5], i;

cout << "Size of integer in this compiler is "


<< sizeof(int) << "\n";

for (i = 0; i < 5; i++)


// The use of '&' before a variable name, yields
// address of variable.
cout << "Address arr[" << i << "] is " << &arr[i]
<< "\n";

return 0;
}

Output

Size of integer in this compiler is 4


Address arr[0] is 0x7ffe75c32210
Address arr[0] is 0x7ffe75c32214
Address arr[0] is 0x7ffe75c32218
Address arr[0] is 0x7ffe75c3221c
Address arr[0] is 0x7ffe75c32220

Another way to traverse the array

#include<bits/stdc++.h>
using namespace std;

int main()
{
int arr[6]={11,12,13,14,15,16};
// Way -1
for(int i=0;i<6;i++)
cout<<arr[i]<<" ";

cout<<endl;
// Way 2
cout<<"By Other Method:"<<endl;
for(int i=0;i<6;i++)
cout<<i[arr]<<" ";

cout<<endl;

return 0;
}

// Contributed by Akshay Pawar ( Username - akshaypawar4)

OUTPUT
11 12 13 14 15 16
By other method:
11 12 13 14 15 16

Array vs Pointers 
Arrays and pointer are two different things (we can check by applying sizeof). The
confusion happens because array name indicates the address of first element and arrays
are always passed as pointers (even if we use square bracket).

What is vector in C++? 


A vector in C++ is a class in STL that represents an array. The advantages of vector over
normal arrays are, 
 
 We do not need pass size as an extra parameter when we declare a vector i.e,
Vectors support dynamic sizes (we do not have to initially specify size of a vector). We
can also resize a vector.
 Vectors have many in-built function like, removing an element, etc.
Pointers in C and C++ | Set 1 (Introduction,
Arithmetic and Array)
Pointers store address of variables or a memory location. 

Using a Pointer:
 

To use pointers in C, we must understand below two operators. 


 
 To access address of a variable to a pointer, we use the unary
operator & (ampersand) that returns the address of that variable. For example &x
gives us address of variable x. 

 One more operator is unary * (Asterisk) which is used for two things : 
To declare a pointer variable: When a pointer variable is declared in C/C++, there
must be a * before its name.

 To access the value stored in the address we use the unary operator (*) that
returns the value of the variable located at the address specified by its operand. This
is also called Dereferencing.
 
// C++ program to demonstrate use of * for pointers in C++
#include <iostream>
using namespace std;

int main()
{
// A normal integer variable
int Var = 10;

// A pointer variable that holds address of var.


int *ptr = &Var;
// This line prints value at address stored in ptr.
// Value stored is value of variable "var"
cout << "Value of Var = "<< *ptr << endl;

// The output of this line may be different in different


// runs even on same machine.
cout << "Address of Var = " << ptr << endl;

// We can also use ptr as lvalue (Left hand


// side of assignment)
*ptr = 20; // Value at address is now 20

// This prints 20
cout << "After doing *ptr = 20, *ptr is "<< *ptr << endl;

return 0;
}

// This code is contributed by


// shubhamsingh10

OUTPUT
Value of Var = 10
Adress of Var == 0x7fffa057dd4
After doing *ptr = 20, *ptr is 20

 Below is pictorial representation of above program: 


 

 
Pointer Expressions and Pointer Arithmetic 
A limited set of arithmetic operations can be performed on pointers. A pointer may be: 
 
 incremented ( ++ )
 decremented ( — )
 an integer may be added to a pointer ( + or += )
 an integer may be subtracted from a pointer ( – or -= )
Pointer arithmetic is meaningless unless performed on an array. 
Note : Pointers contain addresses. Adding two addresses makes no sense, because
there is no idea what it would point to. Subtracting two addresses lets you compute the
offset between these two addresses.
 
// C++ program to illustrate Pointer Arithmetic
// in C/C++
#include <bits/stdc++.h>

// Driver program
int main()
{
// Declare an array
int v[3] = {10, 100, 200};

// Declare pointer variable


int *ptr;

// Assign the address of v[0] to ptr


ptr = v;

for (int i = 0; i < 3; i++)


{
printf("Value of *ptr = %d\n", *ptr);
printf("Value of ptr = %p\n\n", ptr);

// Increment pointer ptr by 1


ptr++;
}
}

OUTPUT
Value of *ptr= 10
Value of ptr = 0x7ffcae30c710

Value of *ptr = 100


Value of ptr = 0x7ffcae30c714

Value of *ptr = 200


Value of ptr = 0x7ffcae30c718
 
Array Name as Pointers 
An array name acts like a pointer constant. The value of this pointer constant is the
address of the first element. 
For example, if we have an array named val then val and &val[0] can be used
interchangeably. 

// C++ program to illustrate Array Name as Pointers in C++


#include <bits/stdc++.h>
using namespace std;

void geeks()
{
// Declare an array
int val[3] = { 5, 10, 15};

// Declare pointer variable


int *ptr;

// Assign address of val[0] to ptr.


// We can use ptr=&val[0];(both are same)
ptr = val ;
cout << "Elements of the array are: ";
cout << ptr[0] << " " << ptr[1] << " " << ptr[2];

return;
}

// Driver program
int main()
{
geeks();
return 0;
}

OUTPUT
Elements of the array are : 5 10 15
Now if this ptr is sent to a function as an argument then the array val can be accessed in
a similar fashion. 
Pointers and Multidimensional Arrays 
Consider pointer notation for the two-dimensional numeric arrays. consider the following
declaration 

Int nums[2][3] = {{166,18,20}, {25,26,27}}


 
In general, nums[i][j] is equivalent to *(*(nums+i)+j)
 

Pointer Notation Array Notation Value

*(*nums) nums[0][0] 16

*(*nums + 1) nums[0][1] 18

*(*nums + 2) nums[0][2] 20

*(*(nums + 1)) nums[1][0] 25

*(*(nums + 1) +
1) nums[1][1] 26

*(*(nums + 1) +
2) nums[1][2] 27

endl vs \n in C++
Although they both seem to do the same thing, there is a subtle difference between
them. 

Cout << endl : Inserts a new line and flushes the stream

Cout<<”\n” : Only inserts a new line.

Therefore, 
cout << endl; 
can be said equivalent to 
cout << ‘\n’ << flush; 
So cout << “\n” seems performance wise better than cout << endl; unless flushing of
stream is required. 
Some other differences between endl and \n are:  
1. endl is manipulator while \n is character.
2. endl doesn’t occupy any memory whereas \n is character so It occupy 1 byte
memory.
3. \n being a character can be stored in a string (will still convey its specific meaning
of line break) while endl is a keyword and would not specify any meaning when stored
in a string.
4. We cannot write endl in between double quotation while we can write \n in between
double quotation like 
cout<<“\n”; it is right but cout<<“endl”; is wrong.
5. We can use \n both in C and C++ but, endl is only supported by C++ and not the C
language.

You might also like