C++ Notes
C++ Notes
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
#include<iostream>
int main()
cout << "Size of signed long int : " << sizeof(signed long int)
cout << "Size of unsigned long int : " << sizeof(unsigned long int)
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:
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;
#include <iostream>
using namespace std;
int main()
float b;
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
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:
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:
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:
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);
Example:
Int main()
{
Int I = 2; // initialization expression
Do
{
// loop body
Cout <<”hello world\n”;
// update expression
I++;
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.
#include <iostream>
int main ()
int i;
// expression is blank
for ( ; ; )
/*
while (i != 0)
i-- ;
*/
/*
while (true)
*/
}
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
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;
#include<iostream>
int main()
int i = 10;
if (i > 15)
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:
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:
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 (condition)
Statement;
Else if (condition)
Statement;
.
.
Else
Statement;
Example:
#include<iostream>
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
OUTPUT
I is 20
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:
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>
int main()
// loop from 1 to 10
// If i is equals to 6,
// without printing
if (i == 6)
continue;
else
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>
int main(){
if(1){
return 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.
void printNumbers()
int n = 1;
label:
n++;
if (n <= 10)
goto label;
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:
// statement
#include <iostream>
int s1 = a + b;
return s1;
// returns void
// function to print
return;
int main()
{
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.
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
int arr1[10];
int n = 10;
int arr2[n];
Example:
#include <iostream>
using namespace std;
int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
cout << arr[0] << " " << arr[1] << " " << arr[2] << " "
<< arr[3];
return 0;
}
OUTPUT
5 2 -10 5
#include <iostream>
using namespace std;
int main()
{
int 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()
{
return 0;
}
Warnings:
(There will some warnings. I am not writing the warnings. Write the program and run to
check the warnings.)
#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;
return 0;
}
Output
#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;
}
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).
Using a Pointer:
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;
// This prints 20
cout << "After doing *ptr = 20, *ptr is "<< *ptr << endl;
return 0;
}
OUTPUT
Value of Var = 10
Adress of Var == 0x7fffa057dd4
After doing *ptr = 20, *ptr is 20
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};
OUTPUT
Value of *ptr= 10
Value of ptr = 0x7ffcae30c710
void geeks()
{
// Declare an array
int val[3] = { 5, 10, 15};
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
*(*nums) nums[0][0] 16
*(*nums + 1) nums[0][1] 18
*(*nums + 2) nums[0][2] 20
*(*(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
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.