Chap 1 Second Half
Chap 1 Second Half
If you are using Turbo C++ then you have to write, these two
header files. Instead of using namespace std and
#include<iostream>
Line 2: using namespace std means we use the namespace named std. std
is an abbreviation for standard, it means add all the things of std
namespace.
Line 4: The curly { braces indicate the start of the main function.
Line 5: cout<< is used prints the content inside the quotation marks.
Line 7: The curly } braces indicate the end of the main function.
2.2 Cout and Cin objects
cout
• cout is an output statement.
Example#
#include<iostream>
using namespace std;
int main()
{
int a=10;
cout<<"Hello World"<<endl;
cout<<"No = "<<a<<endl;
cout<<"No = "<<a<<" Square = "<<a*a;
return 0;
}
Output:
Hello World
No = 10
No = 10 Square = 100
cin
• cin is an input statement.
Example#
#include<iostream>
using namespace std;
int main()
{
int rollno;
char name[20];
cout<<"\nRollno = "<<rollno;
cout<<"\nName = "<<name;
return 0;
}
Output:
Rollno = 12
Name = Devesh
Variables are used to store data. A variable is a container (storage area) to hold
data.
We can think of a variable like a bucket and values are like a water in the bucket
which can easily change.
Variable is an entity where user can store digits, characters and strings. It is similar
to a box or a container.
Constant store a value that cannot be change but storing a value in a variable value
can be changed.
Example#
Valid A, a1, a_ , _a
Example#
Name
int sum, rollno;
Variable
float average;
Local Variable :
A variable that is between the opening and closing braces of a method i.e. declared
inside the method is called the local variable.
Local variables are created when the method, constructor, or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
Example#
void printAll()
{
int x=5;
for(int i=1;i<=x;i++)
{
//Here i and x are local variables
}
}
Instance Variable :
→ Instance Variable is a Data member of a class, and not declared as static.
→ Instance variable access outside a method, constructor, or any b lock.
→ Instance variables are created when an object is
created with the new keyword and destroyed
when the object is destroyed.
→ The value of instance variables depends on the
object. Each object has its unique values of
instance variables.
→ Instance variables can be accessed by calling the object name.
ObjectName.VariableName.
Example #
class Stu
{
int rollno;
char name[100]; //Here rollno and name both are instance
variable
}
Stu s1,s2;
Class/Static variable :
→ A variable that is declared as static is called a static variable. It cannot be local.
→ Any object cannot contain static variable.
→ There would only be one copy of each class variable
per class, regardless of how many objects are
created from it. For example, if we create 10
objects, then all of the objects can share same
variable, value remains same for all the object.
→ Static variables are created when the program starts
and are destroyed when the program stops.
→ Static variables can be accessed by calling with the class name.
ClassName.VariableName.
Example#
class Stu
{
static int cnt; //Here cnt is static
variable
}
Stu.cnt=5;
Initialization of Variable
When a variable is declared but not initialized, it contains garbage.
Static initialization
Syntax#
Data-type variableName=value;
Example#
int rollno=5, total=300;
float pi=3.14;
char name[]=”Shyam”;
Dynamic initialization
Syntax#
VariableName3=VariableName1/VariableName2
Example#
int a=20,b=5,c,x;
//Dynamic
c=a/b;
o Constants
o Variables
o Functions
o Labels
o Defined data types
Some naming rules are common in both C and C++. They are as follows:
Example:
#include<iostream>
using namespace std;
int main()
{
char ch;
char name[20];
int num;
return 0;
}
Output:
Enter a character:T
You entered T
Enter a number:123456
You entered 123456
Enum:-
Example:
#include <iostream>
using namespace std;
enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
int main()
{
week day;
day = Friday;
cout << "Day: " << day+1<<endl;
return 0;
}
Output:
Day:5
Example 2:
#include <iostream>
using namespace std;
int main()
{
enum GenderCheck { Male,Female };
GenderCheck gender = Male;
switch (gender) {
case Male:
cout << "The gender is Male";
break;
case Female:
cout << "The gender is Female";
break;
default:
cout << "The value can either be Male or Female";
}
return 0;
}
Output:
Constants:-
• Constants refer to fixed values that the program may not alter and they are
called literals.
• Constants can be of any of the basic data types and can be divided into Integer
Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values
.
It is a const variable used to define the variable values that never be changed during the execution of a
program. And if we try to modify the value, it throws an error.
Syntax
Example:
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
// declare the value of the const
const int num = 25;
num = num + 10;
return 0;
}
Output:
It shows the compile-time error because we update the assigned value of the n
Namespace:-
In C++, global namespace is the root namespace.The global::std will always refer to the
namespace "std" of C++ Framework.
Example:
#include <iostream>
using namespace std;
namespace First {
void sayHello() {
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second {
void sayHello() {
cout<<"Hello Second Namespace"<<endl;
}
}
int main()
{
First::sayHello();
Second::sayHello();
return 0;
}
Op
Hello First Namespace
Hello Second Namespace
Example# + - X / &&
Expression are the ones, whose evaluation yields numeric value. Expression
contains constant, variable, and operators. In C, every expression evaluates to a
value. C language supports rich set of Operators. Like arithmetic, logical, relational
etc.
Example# a+b-c
Operators
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Miscellaneous Operators
Arithmetic operators
These operators are used to perform some basic operations like addition,
substation, division, multiplication, and modulo. These require two operands to
perform their operation hence they are also called binary operators. They are also
knowing as mathematical operators.
Example#
#include<iostream>
using namespace std;
int main()
{
int a=20;
int b=2;
cout<<"Add = "<<a+b<<endl;
cout<<"Sub = "<<a-b<<endl;
cout<<"Mul = "<<a*b<<endl;
cout<<"Div = "<<a/b<<endl;
a++;
cout<<"Inc = "<<a<<endl;
b--;
cout<<"Dec = "<<b<<endl;
}
Output
Add = 22
Sub = 18
Mul = 40
Div = 10
Inc = 21
Dec = 1
Assignment operators
Assignment operators are used to assigning value to any variable. It is denoted by
‘=’ sign. An assignment operator is a binary operator i.e. it operates on two values.
Example#
#include<iostream>
using namespace std;
int main()
{
int a=20;
cout<<"\na = "<<a;
a+=10;
cout<<"\nAfter a+=10 a = "<<a;
a-=10;
cout<<"\nAfter a-=10 a = "<<a;
a*=10;
cout<<"\nAfter a*=10 a = "<<a;
a/=10;
cout<<"\nAfter a/=10 a = "<<a;
a%=10;
cout<<"\nAfter a%=10 a = "<<a;
Output:
a = 20
After a+=10 a = 30
After a-=10 a = 20
After a*=10 a = 200
After a/=10 a = 20
After a%=10 a = 0
Relational operators
It returns Boolean value only.
Relational operators are used to comparing between two operands and evaluate
them as either true or false. For example, # 1 or 0. If the condition is true then
return 1 otherwise return 0. They are used in conjunction with logical operators
and conditional & looping statements.
Example#
#include<iostream>
using namespace std;
int main()
{
int a=20;
int b=10;
int c;
c=a==b;
cout<<"\na==b "<<c;
c=a!=b;
cout<<"\na!=b "<<c;
c=a>b;
cout<<"\na>b "<<c;
c=a<b;
cout<<"\na<b "<<c;
c=a>=b;
cout<<"\na>=b "<<c;
c=a<=b;
cout<<"\na<=b "<<c;
}
Output
a = 20 b = 10
a==b 0
a!=b 1
a>b 1
a<b 0
a>=b 1
a<=b 0
Logical operators
They are also known as binary operators. Logical operators return a Boolean value.
Example#
int main()
{
int a=20;
int b=20;
int c;
c=a>10 || b<30;
cout<<"\na>10 || b<30 = "<<c;
c=!(a>10 || b<30);
cout<<"\nc=!(a>10 || b<30) = "<<c;
return 0;
}
Output
a>10 && b<30 = 1
a>10 || b<30 = 1
c=!(a>10 || b<30) = 0
Syntax#
Operand1 symbol(bitwise) operand2
Here operand1, operand2 are the variable or constant.
& Bitwise AND. If both the bits of the both operand are 1 a & b
then resulted bit is 2.If any one bit is 0 then resulted bit
is 0. (referred AND true table)
| Bitwise OR. If any one bit of the both operand are 1 then a | b
resulted bit is 2.If both bit are 0 then resulted bit is 0.
(referred OR true table)
>> Bitwise shift right. It moves the bit of the first operand a>>2
to the right by the number of bits specified by the second
operand .It discards the far right bit and fill from the
right with 0 bits.
<< Bitwise shift left. It moves the bit of the first operand to a<<2
the left by the number of bits specified by the second
operand. It discards the far left bit and fills from the right
with 0 bits.
Example#
#include<iostream>
using namespace std;
int main()
{
unsigned int a=20;
unsigned int b=10;
int c;
c=a&b;
cout<<"\na&b ="<<c;
c=a|b;
cout<<"\na|b ="<<c;
c=a^b;
cout<<"\na^b ="<<c;
c=~b;
cout<<"\n~b ="<<c;
c=a<<2;
cout<<"\na<<b ="<<c;
c=a>>2;
cout<<"\na>>b ="<<c;
return 0;
}
Output
a = 20 b = 10
a&b =0
a|b =30
a^b =30
~b =-11
a<<b =80
a>>b =5
Miscellaneous Operators
1. sizeof
sizeof operator returns the size of a variable.
2. Conditional operator
Instead of an if-else or switch case, we can use a conditional operator to
check
condition.
sizeof() operator
sizeof() is a unary operator that returns the size of the variable passed as an
argument.
Example#
#include<iostream>
using namespace std;
int main()
{
int a;
float b;
char ch;
double d;
cout<<"\nSizeof(a) ="<<sizeof(a);
cout<<"\nSizeof(b) ="<<sizeof(b);
cout<<"\nSizeof(ch) ="<<sizeof(ch);
cout<<"\nSizeof(d) ="<<sizeof(d);
return 0;
}
Output
Sizeof(a) =4
Sizeof(b) =4
Sizeof(ch) =1
Sizeof(d) =8
Conditional operator
The conditional operator is also known as the ternary operator. It checks the
expression and returns either true (1) or false (0).
Syntax#
If expression 1 is true then expression 2 is executed else expression 3 is executed.
#include<iostream>
using namespace std;
int main()
{
int a,b,max;
a=20;
b=5;
max=a>b?a:b;
cout<<"\nMax = "<<max;
return 0;
}
Output:
Max = 20
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"\nEnter no =>";
cin>>a;
a%2==0?cout<<"\nNo is even":cout<<"\nNo is odd";
return 0;
}
Output
Enter no =>22
No is even
When you create object with a pointer that time we can access the data members
and data functions of the class in the main() function with an arrow operator instead
of a dot.
Syntax#
Objectname.functionName() objectName=>functionName()
#include<iostream>
using namespace std;
class student{
int no;
char name[20];
public:
void setdata()
{
cout<<"\nEnter no =>";
cin>>no;
cout<<"\nEnter name =>";
cin>>name;
}
void printdata()
{
cout<<"\nNo = "<<no<<" Name = "<<name;
}
};
int main()
{
Output
Enter no =>12
No = 12 Name = Jeet
Enter no =>13
No = 13 Name = Shourya
Control Statement and Iteration
Control statement
We can control the order of execution of the program with the help of a control
statement, based on logic and values.
Decision-making statement
The decision-making statement is also known as the Selection statement.
There are two ways to make the decision,
if
In some situations, we would like to execute some logic when a condition is
TRUE, and some other logic when the condition is FALSE and this can be
done by using if statement.
There are 4 ways to write “if statements” as below the given image.
If
In some situations, we would like to execute some logic when a condition is
TRUE.
Syntax#
if(condition)
{
Logic..
}
#include<iostream>
using namespace std;
int main()
{
int a=40;
if(a>20)
{
cout<<"\nNo is greater than 20";
}
return 0;
}
Output
No is greater than 20
If…else
If the condition is TRUE then the control goes to the Logic between if and
else block, that is the program will execute the code between if and else
statements, else program will execute the code after the else statement.
We can write only the “if” block. The else if and else clauses are both
optional.
if(condition)
{
Logic..
}
else
{
Logic..
}
#include<iostream>
using namespace std;
int main()
{
int a=5;
if(a>0)
{
cout<<"\nNo is positive";
}
else{
cout<<"\nNo is negative";
}
return 0;
}
Output
No is positive
Nested If…else
The most general way of doing this is by using the else if variant on the if
statement.
As soon as one of these gives a true result, the following statement or block
is executed, and no further comparisons are performed.
Syntax#
if(condition)
{
if(condition)
{
}
}
else
{
if(condition)
{
}
else
{
}
}
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"\nEnter no1 =>";
cin>>a;
cout<<"\nEnter no2 =>";
cin>>b;
cout<<"\nEnter no3 =>";
cin>>c;
if(a>b)
{
if(a>c)
{
cout<<"\nNo1 is max";
}
else
{
cout<<"\nNo3 is max";
}
}
else
{
if(b>c)
{
cout<<"\nNo2 is max";
}
else
{
cout<<"\nNo3 is max";
}
}
return 0;
}
Output
No2 is max
if…else if…else
There are cases when we would like to execute some more conditions when
a condition is TRUE, and some other condition logic when the condition is
FALSE.
Syntax#
if(condition)
{
}
else if(condition)
{
}
else
{
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"\nEnter no =>";
cin>>a;
if(a==0)
{
cout<<"\nNo is 0";
}
else if(a%2==0){
cout<<"\nNo is even";
}
else{
cout<<"\nNo is odd";
}
return 0;
}
Output
Enter no =>2
No is even
Properties of If..else Statement
Switch-case
When you are comparing the same expression to several different values it
gets complicated with if…else if…else so we can use the switch-case
statements as an alternative to the if-else statements.
If any case statement is satisfied, then the logic of that case will be
executed and then the control will come out of the switch block. This one
will not happen with the if-else block.
Remember that, switch block uses a break statement at the end of each
case. C simply requires that we leave the block before it ends.
If-else block is more time consuming than the switch case block.
Each value is called a case, and the variable being switched on is checked
for each switch case.
Syntax#
switch(testexpression)
{
case expression1:
Logic..
break;
case expression2:
Logic..
break;
case expression N:
Logic..
break;
default:
break;
}
#include<iostream>
using namespace std;
int main()
{
int a;
switch(a)
{
case 1:
cout<<"\nMonday";
break;
case 2:
cout<<"\nTuesday";
break;
case 3:
cout<<"\nWednesday";
break;
case 4:
cout<<"\nThursday";
break;
case 5:
cout<<"\nFriday";
break;
case 6:
cout<<"\nSaturday";
break;
case 7:
cout<<"\nSunday";
break;
default:
cout<<"\nWrong opt";
}
return 0;
}
Output
Tuesday
#include<iostream>
using namespace std;
int main()
{
int a,b;
char op;
switch(op)
{
case '+':
cout<<"\nAdd = "<<a+b;
break;
case '-':
cout<<"\nSub = "<<a-b;
break;
case '*':
cout<<"\nDiv = "<<a/b;
break;
case '/':
cout<<"\nMul = "<<a*b;
break;
default:
cout<<"\nWrong opt";
}
return 0;
}
Output
Add = 24
If Switch
if-else statement test for equality as switch statement test only for equality.
well as for logical expression.
The following illustration shows a loop structure that runs a set of statements until
a condition becomes true.
The concept where the test condition is checked before entering the loop body is
known as Entry Controlled Loop.
Example# for and while loops are known as entry controlled loop
While, in the exit controlled loop the body of loop will be executed first and at the
end, the test condition is checked. If the condition satisfies, then the body of the
loop will be executed again.
It is the most common and most popular loop used in any programming
language.
For loop is an entry controlled loop i.e. the condition is checked before
entering into the loop. So, if the condition is false for the
first time, the statements inside for loop may not be
executed at all.
Syntax#
Step 1: Initialization
Evaluates the initialization code evaluates code from where it starts.
Example#
Step 2: Condition
The condition expression is evaluated. If the test expression is false, for loop is
terminated at that time. But if the test expression is true , logic inside the body of
for loop is executed.
Step 3: Increment/Decrement
Then it evaluates the increment/decrement condition and again follows from step
2. When the condition expression becomes false, it exits the loop.
The variable increment/decrement section is the easiest way for a “for loop” to
handle the changing of the variable. It is possible to do things like x++, x = x +
10, x--
Example#
#include<iostream>
using namespace std;
int main()
{
int a,i;
cout<<"\nEnter no =>";
cin>>a;
for(i=1;i<=a;i++)
{
cout<<"\n"<<i;
}
return 0;
}
Output
Enter no =>5
1
2
3
4
5
#include<iostream>
using namespace std;
int main()
{
int a,i;
cout<<"\nEnter no =>";
cin>>a;
for(i=1;i<=10;i++)
{
cout<<a<<" X "<<i<<" = "<<a*i<<endl;
}
return 0;
}
Output:
Enter no =>5
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
for(i=20;i>=1;i--) for(i=no1;i<=no2;i++)
{ {
logic... logic...
} }
for(i=0;i<strlen(name);i++) for(i=1,j=n;i<=n/2;i++,j--)
{ {
logic...
} }
for(i=1;i<=n;i++) for(i=1;i<=n;i++)
{ {
for(j=1;j<=n;j++) for(j=1;j<=n;j++)
{ {
Logic..
} for(k=1;k<=n;k++)
} {
Logic…
}
}
}
There may be a condition in a for loop which is always true. In such case, the loop
will run infinite times.
} } }
The While statement always checks the condition before it begins the loop.
Syntax#
while(condition)
{
logic….
}
Step 1: condition
The while loop evaluates the conditional expression first. If the test expression is
false, while loop is terminated at a time. But if the test expression is true , logic
inside the body of while loop is executed and the update expression is updated.
When the test expression is false, the while loop is terminated. The loop iterates
while the condition is true.
Example# To print 1 to N
#include<iostream>
using namespace std;
int main()
{
int a,i;
cout<<"\nEnter no =>";
cin>>a;
i=1;
while(i<=a)
{
cout<<"\n"<<i;
i++;
}
return 0;
}
Output:
Enter no =>5
1
2
3
4
5
#include<iostream>
using namespace std;
int main()
{
int a,i,f=1;
cout<<"\nEnter no =>";
cin>>a;
i=a;
while(i>=1)
{
cout<<i<<" X ";
f=f*i;
i--;
}
cout<<"\nFactorial = "<<f;
return 0;
}
Output
Enter no =>5
5X4X3X2X1X
Factorial = 120
#include<iostream>
using namespace std;
int main()
{
int x,ans,no;
cout<<"\nEnter no =>";
cin>>no;
while(no>0)
{
x=no%10;
ans=ans*10+x;
no=no/10;
}
cout<<"\nAns = "<<ans;
return 0;
}
Output
Enter no =>439
Ans = 934
while (1)
{
if(Some Condition)
{
break;
}
}
Do while loop
Do-while loop is an exit controlled loop i.e. the condition is checked at the
end of the loop.
The body of do...while loop is executed once, before checking the test
expression.
To exit a do-while loop either the condition must be false or we should use
break statement.
Syntax#
do
{
logic…;
}while(upto condition);
do do
{ {
Logic.. Logic..
}while(op!=4); }while(no>4);
do
{
Loops…
}while(op!='s');
#include<iostream>
using namespace std;
int main()
{
int a,i;
cout<<"\nEnter no =>";
cin>>a;
i=1;
do
{
cout<<"\n"<<i;
i++;
}while(i<=a);
return 0;
}
Output
Enter no =>5
1
2
3
4
5
#include<iostream>
using namespace std;
int main()
{
int a,b;
char op;
do
{
fflush(stdin);
cout<<"\nEnter a for add\nEnter s for square\nEnter c for cube\nEnter e for
exit\nEnter =>";
cin>>op;
switch(op)
{
case 'a':
cout<<"\nEnter no1 and no2 =>";
cin>>a>>b;
cout<<"\nAddition = "<<a+b;
break;
case 's':
cout<<"\nEnter no =>";
cin>>a;
cout<<"\nSquare = "<<a*a;
break;
case 'o':
cout<<"\nEnter no =>";
cin>>a;
cout<<"\nCube = "<<a*a*a;
break;
case 'e':
cout<<"\nBye";
break;
default:
cout<<"\nWrong opt";
}
}while(op!='e');
return 0;
}
Addition = 24
Enter a for add
Enter s for square
Enter c for cube
Enter e for exit
Enter =>s
Enter no =>5
Square = 25
Bye
While Do..while
In the While loop, the condition is In do-while, the statements are
tested first and then the statements executed for the first time and then the
are executed if the condition turns out conditions are tested, if the condition
to be true. turns out to be true then the statements
are executed again.
while loop does not run in case the A do-while loop runs at least once even
condition given is false. though the condition given is false.
In a while loop, the condition is first In a do-while loop, the condition is tested
tested and if it returns true then it goes at the last.
in the loop.
While loop is the entry control loop do-while is exit control loop.
Syntax: Syntax:
while (condition) do
{ {
Statements; Statements;
} }while(condition);
There may be a condition in a do-while loop that is always true. In such a case, the
loop will run infinite times.
do
{
printf("This is an infinite loop");
}while (1);
do
{
if(Some Condition)
{
break;
}
}while (1);
Nested Loop
A loop within the loop is known as a nested loop. The depth of the nested loop
depends on the complexity of a problem. We can have any number of nested loops
as required.
#include<iostream>
using namespace std;
int main()
{
int a,i,j;
cout<<"\nEnter no =>";
cin>>a;
for(i=1;i<=a;i++)
{
for(j=1;j<=a;j++)
{
cout<<"*";
}
cout<<"\n";
}
return 0;
}
Output
Enter no =>5
*****
*****
*****
*****
*****
Branching Statement
Branching statements are also known as jumping statements. Jumping statements
jump from one statement to another, conditionally or unconditionally.
break
The break statement is used to stop the current execution of the code and
helps to come out of the loop.
In many situations, we need to get out of the loop before the loop execution
is normally complete.
Syntax#
break;
#include<iostream>
using namespace std;
int main()
{
int i,no,x=0;
cout<<"\nEnter no =>";
cin>>no;
for(i=2;i<no;i++)
{
if(no%i==0)
{
x=1;
break;
}
}
if(x==0)
{
cout<<"\nNo is prime";
}
else{
cout<<"\nNo is not prime";
}
return 0;
}
Output
Enter no =>5
No is prime
Continue
Continue is similar to break, but when a break statement is executed, it
breaks the loop whereas continuing skips the rest of the statement and
proceeds for the next iteration.
We can use the Continue statement with For Loop, While Loop, or do-while
loop.
#include<iostream>
using namespace std;
int main()
{
int i,no,x=0;
cout<<"\nEnter no =>";
cin>>no;
for(i=1;i<=no;i++)
{
if(i==3 || i==5)
{
continue;
}
cout<<"\n"<<i;
}
return 0;
}
Output
Enter no =>8
1
2
4
6
7
8
goto
Note that a goto breaks the normal sequential execution of the program.
Syntax#
goto label;
.
.
label: statement;
Backward jump
The label is placed before the goto label; a loop will be formed and some statements
will be executed repeatedly. Such a jump is called a backward jump.
Forward jump
The label: is placed after the goto label; some statements will be skipped and the
jump is known as a forward jump.
Example#
#include<iostream>
using namespace std;
int main()
{
int a;
pos:
cout<<"\nEnter positive value =>";
cin>>a;
if(a<0)
{
cout<<"\nEnter an only positive value";
goto pos;
}
else
{
cout<<"\nValue = "<<a<<" Square = "<<a*a;
}
return 0;
}
Output
Value = 5 Square = 25
return
The return statement is used for returning from a function. Whenever a return
statement is encountered, the control goes out from the function. With the help of
the return statement, we can also return some value.
Example#
#include<iostream>
using namespace std;
int main()
{
int a,b,sum;
cout<<"\nEnter no1 =>";
cin>>a;
cout<<"\nEnter no2 =>";
cin>>b;
sum=add(a,b);
cout<<"\nSum = "<<sum;
return 0;
}
Output
Sum = 25
Exit() function
Syntax#
void exit(int status)
Example#
exit(0)
The difference between the break and exit() function is that the break is a keyword
that causes an immediate exit from the switch or loop (for, while, or do), while
exit() is a standard library function, which terminates program execution when it
is called. the break is a reserved word in C; therefore it can't be used as a variable
name while exit() can be used as a variable name.
Example#
#include<iostream>
using namespace std;
int main()
{
int i,j,no;
cout<<"\nEnter no =>";
cin>>no;
if(no<0)
{
cout<<"\nBye";
exit(0);
}
else
{
cout<<"\nEntered no is positive";
}
}
Output
Enter no =>-2
Type Conversion
Here, the best practice is to convert lower data type to higher data type to avoid
data loss.
Data will be truncated when the higher data type is converted to lower. For
example, if the float is converted to int, data that is present after the decimal point
will be lost.
Implicit Conversion
Implicit conversions do not require any operator for conversion.
Here, the value has been promoted from int to double and we do not have to specify
any type-casting operator. This is known as a standard conversion.
Usually, the smallest data type of the variable converts the largest data type
automatically.
Example#
#include<iostream>
using namespace std;
int main()
{
int i=20;
double p;
p=i; // implicit conversion
cout<<"\nP = "<<p;
}
Output
P=20
Explicit Conversion
There are two types of Explicit Conversion :
1. Converting by assignment
2. Conversion using Cast operator
Converting by Assignment
Syntax#
variableName =(DataType)VariableName;
Example#
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
Output
Sum=2
Cast operator is a unary operator that forces one data type to be converted into
another data type.
• Static Cast
• Dynamic Cast
• Const Cast
• Reinterpret Cast.
static_cast
It is a compile-time cast.
dynamic_cast
It ensures that a result of the type conversion points to the valid, safely converts
from a pointer (or reference) to a base type to a pointer (or reference) to a derived
type.
const_cast
It is used to change the constant value of any object. It ensures that either the
constant needs to be set or to be removed.
reinterpret_cast
Converts any pointer type to any other pointer type, even of unrelated classes.
class classname{
Example:
#include <iostream>
using namespace std;
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
{
private_variable = 10;
protected_variable = 99;
}
// driver code
int main()
{
base object1;
friendFunction(object1);
return 0;
}
Output
Private Variable: 10
Protected Variable: 99
In the above example, we have used a global function as a friend
function. In the next example, we will use a member function of
another class as a friend function.
2.Member Function of Another Class as Friend Function
#include <iostream>
using namespace std;
class base;
class anotherClass {
public:
void memberFunction(base& obj);
};
protected:
int protected_variable;
public:
base()
{
private_variable = 10;
protected_variable = 99;
}
int main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);
return 0;
}
Op
Private Variable: 10
Protected Variable: 99