0% found this document useful (0 votes)
14 views81 pages

Chap 1 Second Half

K

Uploaded by

raoh0605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views81 pages

Chap 1 Second Half

K

Uploaded by

raoh0605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

2.

1 Creating, Compiling, and Executing C++ PROGRAM


Any C++ program can be written using simple IDE like TurboC++, CodeBlock, DevC++, etc. The
extension to the file name should be
.cpp. We have saved our first program by the name p2.cpp

Step 1: Write a code in Code Block, Save it with p2.cpp

If you are using Turbo C++ then you have to write, these two
header files. Instead of using namespace std and
#include<iostream>

Line 1: The #include is a preprocessor directive used to include header files


in our program.

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 3: A valid C++ program must have the main() function.

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 6:The return 0; statement is the "Exit status" of the program.

Line 7: The curly } braces indicate the end of the main function.
2.2 Cout and Cin objects

cout
• cout is an output statement.

• cout is an object of the output stream.

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.

• cin is an object of the input stream.

Example#
#include<iostream>
using namespace std;

int main()
{
int rollno;
char name[20];

cout<<"\nEnter rollno =>";


cin>>rollno;

cout<<"\nEnter name =>";


cin>>name;

cout<<"\nRollno = "<<rollno;
cout<<"\nName = "<<name;

return 0;
}

Output:

Enter rollno =>12

Enter name =>Devesh

Rollno = 12
Name = Devesh

2.3 << operator and >> operator

• >> is known as insertion operator or getfrom operator. We can use >>


operator with cin object.

• << is known as extraction operator or putto operator. We can use <<


operator with cout object.
2.4 Variables
In C++ programming language, a variable is a value that can change, depending
on conditions or on information passed to the program.

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.

2.4.1 Variable names


A name given to the memory location is known as variable name. There are rules
that must be followed before giving a variable name in C++. They are as follows :
• In C++, it must start with an alphabet or underscore (_) and following
characters can be letters, underscores and digits only.
• Both uppercase and lowercase letters can be used.
• Spaces are not allowed in variable name.
• Certain keywords (these are C++ language
reserved words) cannot be used in the variable
name.
• The variable names should not be very long.
(maximum 32 characters)
• The variable names should be meaningful.

Example#

Valid A, a1, a_ , _a

Invalid If, 1a, a#, a bc

2.4.2 Declaration of the variables


Syntax#
Data-type variableName1, variableName2 … variableNameN;

Example#
Name
int sum, rollno;
Variable
float average;

char gender, name[20];


Data type

2.4.3 Types of Variable

There are three types of variable in C++ :

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.

There are two ways to initialize variable

Static initialization

Storing value at compile time is called static initialization.

Syntax#
Data-type variableName=value;

Example#
int rollno=5, total=300;
float pi=3.14;
char name[]=”Shyam”;

Dynamic initialization

Storing value at runtime is called dynamic initialization.

Syntax#
VariableName3=VariableName1/VariableName2

Example#
int a=20,b=5,c,x;

//Dynamic

c=a/b;

cout<<”\nEnter value of X =>”;


cin>>x;
Identifiers:-
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or other user-
defined data types created by the programmer. They are the basic requirement of any language. Every
language has its own rules for naming the identifiers.

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:

o First character must be on alphabet or underscore.


o It can contain only letters(a..z A…Z),digits(0 to 9) or underscore(_)
o Identifier name cannot be keyword.
o Only first 31 characters are significant.

Example:
#include<iostream>
using namespace std;
int main()
{
char ch;
char name[20];
int num;

cout<<"Enter a character: ";


cin>>ch;
cout<<"You entered: "<<ch<<endl;

cout<<"\nEnter your name: ";


cin>>name;
cout<<"Your name is: "<<name<<endl;
cout<<"\nEnter a number: ";
cin>>num;
cout<<"You entered: "<<num<<endl;

return 0;
}
Output:
Enter a character:T
You entered T

Enter your name:jay


Your name is jay

Enter a number:123456
You entered 123456
Enum:-

• enum or enumeration is a data type consisting of named values like elements,


members, etc., that represent integral constants. It provides a way to define and
group integral constants.
• It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc.
• enum constants are static and final implicitly.
• Enumerations are defined much like structures.
• An enumeration is set of named integer constants.
,

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:

The gender is Male

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

const data_type variable_name;

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:-

For accessing the class of a namespace, we need to use namespacename::classname. We


can use using keyword so that we don't have to use complete name all the time.

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

C++ namespace example: by using keyword


#include <iostream>
using namespace std;
namespace First{
void sayHello(){
cout << "Hello First Namespace" << endl;
}
}
namespace Second{
void sayHello(){
cout << "Hello Second Namespace" << endl;
}
}
using namespace First;
int main () {
sayHello();
return 0;
}
Op
Hello First Namespace
Operators and Expression
Operators are the symbols that instruct to perform some mathematical or logical
operations. Operators operate on certain data types called operands, and they form
a part of the mathematical or logical expressions. More complex expressions use
operators.

Example# + - X / &&

There are three categories of operators.

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.

Operator Meaning Example

+ To perform addition operation. a+b

- To perform subtraction operation. a-b

* To perform multiplication operation. a*b

/ To perform division operation. a/b

% Modulus: To gives remainder of the a%b


division operation.
++ To increment value by one in the operand. a++ , ++a

-- To decrement value by one in the operand. a-- , --a

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.

It has the lowest precedence.


Operator Meaning Example Equivalent to

= Assign value to operand a=5; a=5;

+= Add given value to operand a+=5; a=a+5;


value

-= Subtract the given value from a-=5; a=a-5;


operand value

*= Multiply operands value from a*=5; a=a*5;


the given value

/= Divides the operands value by a/=5; a=a/5;


the given value

%= Assign remainder of operators a%=5; a=a%5;


value by given value

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.

Operator Meaning Example

< Less than a<b

> Greater than a>b

>= Greater than or equal to. a>=b

<= Less than or equal to. a<=b

!= Not equal to a!=b

== Equal to. a==b

Example#

#include<iostream>
using namespace std;
int main()
{
int a=20;
int b=10;
int c;

cout<<"\na = "<<a<<" b = "<<b;

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.

Operator Meaning Example

|| To perform logical OR operation. a==5 || a==7

&& To perform logical AND operation a>20 && a<40

! To perform logical NOT operation a!=5

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<<"\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

Bit-wise special operators


We have performed various operations using various operators on entire numbers
so far. But suppose we want to perform operation on bits rather than entire byte,
C supports bitwise operator to perform operation on bits of integral operands.

Bitwise operators works on binary levels.

Syntax#
Operand1 symbol(bitwise) operand2
Here operand1, operand2 are the variable or constant.

Operator Meaning Example

& 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 Complement. Set 1 to 0 and 0 to 1 bit. ~a

^ Bitwise Exclusive OR. If both bits of the both operand a ^ b


are 1 then resulted bit is 1 otherwise resulted bit is 0.

>> 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;

cout<<"\na = "<<a<<" b = "<<b;

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.

3. . (dot) and -> (arrow)


Member operators are used to accessing objects of classes, structures, and
unions.

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).

It is known as the ternary operator because it has three operands.

Syntax#
If expression 1 is true then expression 2 is executed else expression 3 is executed.

Example# Maximum between two with the conditional operator

#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

Example# Program to check whether a number is odd or even using


conditional operator

#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

Dot and Arrow operator


We can access the data member and data function of the class in the main()
function using dot operator.

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#

Dot operator Arrow operator

Objectname.functionName() objectName=>functionName()

Emp1.setEmployeeData() Emp1 ->setEmployeeData()

#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()
{

student *s1=new student();


s1->setdata();
s1->printdata();

student s2=new student();


s2.setdata();
s2.printdata();
return 0;
}

Output

Enter no =>12

Enter name =>Jeet

No = 12 Name = Jeet

Enter no =>13

Enter name =>Shourya

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.

In the sequential flow of control, statements are


executed line by line but in the case of the conditional
program, the order of execution is based on data values
and conditional logic.

Conditional statements cause variable flow of execution


of the same program based on certain condition to be
true or false, whenever a program is executed

The control statements can be classified into three


groups: Decision-making statements, Looping
statements, and Jumping statements.

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.

The condition’s result comes from the comparison of two values.

Condition is an expression that is made up by using relational operators


(>,<,>=,<=,==,etc.) and operand and logical operators (&& , || ,etc) if
required, and it returns true or false.

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.

The condition usually results from the comparison of two values.

If the condition is TRUE then the control is between the if brackets.

Syntax#

if(condition)
{
Logic..
}

Example# To check whether the number is 5

#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

In some situations, we would like to execute some logic when a condition is


TRUE, and some other logic when the condition is FALSE.

An if statement consists of a Boolean expression.

The condition usually results from a comparison of two values.

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.

We can have any number of else if statements or none.

We can also write nested if-else blocks.


Syntax#

if(condition)
{
Logic..
}
else
{
Logic..
}

Example# To check whether a number is positive or negative

#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

An If inside an If is known as a Nested If…else.

In some cases, we would like to execute some more conditions when a


condition is TRUE, and some other condition logic when the condition is
FALSE.

The most general way of doing this is by using the else if variant on the if
statement.

This works by cascading several comparisons.

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
{

}
}

Example# To find the maximum number out of three numbers

#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

Enter no1 =>22

Enter no2 =>33

Enter no3 =>11

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.

We can write multiple else if condition with if statement.

Syntax#

if(condition)
{

}
else if(condition)
{

}
else
{

Example# To check whether a number is odd-even or zero

#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

• It’s not compulsory to write else block.


• We cannot write multiple if or else. Usually we have to
write {} braces.
• We cannot write condition with else.
• We can use logical and relational operator in condition
expression. if(a>b), if(a>b && a>c)

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.

It executes one of several groups of statements depending on the value of


an expression.

If-else block executes different conditions or expressions in each statement


on the other hand the switch statement evaluates a single expression and
compares it for every comparison.

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.

A switch statement allows a variable to be tested for equality against a list


of values.

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;
}

Example# Switch case demo

#include<iostream>
using namespace std;

int main()
{
int a;

cout<<"\nEnter week day no =>";


cin>>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

Enter week day no =>2

Tuesday

Example# Add, subtract, multiply or divide based on user choice using


switch statement

#include<iostream>
using namespace std;

int main()
{
int a,b;
char op;

cout<<"\nEnter no1 =>";


cin>>a;
cout<<"\nEnter no2 =>";
cin>>b;
cout<<"\nEnter operator =>";
cin>>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

Enter no1 =>22

Enter no2 =>2

Enter operator =>+

Add = 24

Properties of Switch statements


• We don't use those expressions to evaluate switch cases, which may return
floating-point values or strings.
• The case label values must be unique.
• The case label must end with a colon(:)
• The break is used to break out of the case statements. The
break is a keyword that breaks out of the code block,
usually surrounded by braces, which it is in.
• It isn't necessary to use a break after each block, but if
you do not use it, then all the consecutive blocks of codes
will get executed after the matching block.
• The default case is optional, but it is wise to include it as it handles any
unexpected cases. Usually, the default case is executed when none of the
mentioned cases matches the switch expression.

Difference between if and switch

If Switch

Which statement will be executed Which statement will be executed is


depending upon the output of the decided by the user.
expression inside if statement.

if-else statement test for equality as switch statement test only for equality.
well as for logical expression.

if statements can evaluate float switch statements cannot evaluate float


conditions. conditions.

If the condition inside if statements is If the condition inside switch


false, then by default the else statement statements does not match with any of
is executed if created. the cases, for that instance the default
statements are executed if created.
Loop Control Structure
Iteration statements are also known as Looping statements. Looping statements
are used when a group of statements is to be executed repeatedly, till a condition
is TRUE or until a condition is FALSE.

The following illustration shows a loop structure that runs a set of statements until
a condition becomes true.

Entry controlled loop and Exit controlled loop

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.

Example# do while loop is known as exit controlled loop


For loop
The for loop executes a block of statements a specified number of times.

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#

for(initialization; condition; increment/decrement)


{
Logic….
}

Step 1: Initialization
Evaluates the initialization code evaluates code from where it starts.

The variable initialization allows us to declare a variable and gives it a starting


value.

The initialization statement is executed only once.

This part is optional and may be absent.

Example#

for(i=0 ; condition; increment/decrement)


for(i=20 ; condition; increment/decrement)
for(i=strlen(name) ; condition; increment/decrement)
for( ; condition; increment/decrement) // initialization is absent

Keep in mind that a semicolon separates each of these sections.

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.

The condition is checked after the execution of increment/decrement statement.

This process repeats until the test expression is false.

Usually, the condition is the combination of Relational operators.


Example#

for(initialization ; i <= X; increment/decrement)


for(initialization ; i > X; increment/decrement)

for(initialization ; i < strlen(name); increment/decrement)

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#

for(initialization ; condition ; i=i+1)


for(initialization ; condition ; i++)
for(initialization ; condition ; i--)
for(initialization ; condition ; i=i+10)

Example# for loop demo

#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

Example# To print table

#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

Some good examples of for loop


for(i=2;i<=n/2;i++) for(i=1;i<=20;i=i+2)
{ {
logic... logic...
} }

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…
}

}
}

Infinite for loop

There may be a condition in a for loop which is always true. In such case, the loop
will run infinite times.

for (i=0; i>0; i++) for (i=0; ; i++) for (;;)


{ { {

} } }

We can use break to come out of an Infinite loop.

for (i=0; i>0; i++)


{
if(Some Condition)
{
break;
}
}
While loop
While 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 while loop may not be executed at all.

While loop keeps executing till the condition remains true.

The While statement always checks the condition before it begins the loop.

In the While loop, the programmer has to maintain or keep track of


increment or decrement value.

An entry control loop checks the condition first and


then enters the loop body. So for…and while..both are
known as an entry controls 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.

Some Good Examples

i=20; i=1; no=123;


while(i>50) n=5; while(no>0)
{ while(i>=n) {
logic... { logic...
i--; logic... }
} i++;
}

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

Example# To print factorial of a number

#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

Example# Enter no and print reverse of it.

#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

Infinite while loop


There may be a condition in a while loop that is always true. In such a case, the
loop will run infinite times.
while (1)
{
printf("This is an infinite loop");
}

We can use a break to come out of an Infinite loop.

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.

In do-while loop, statement/logic is given before the condition, so the


statement or code will be executed at least one time.

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.

Do..while loop is known as an exit controlled loop. An


exit controlled loop checks the condition at the end of the
loop. Hence, even if the condition is false the loop will be
executed at least once.

Syntax#

do
{
logic…;
}while(upto condition);

Some good Examples

do do
{ {
Logic.. Logic..
}while(op!=4); }while(no>4);

do
{
Loops…
}while(op!='s');

Example# To print from 1 to N using do…while loop

#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

Example# Menu driven program for addition, square and cube

#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;
}

Enter a for add


Enter s for square
Enter c for cube
Enter e for exit
Enter =>a

Enter no1 and no2 =>22 2

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

Enter a for add


Enter s for square
Enter c for cube
Enter e for exit
Enter =>e

Bye

Difference between While and Do while

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.

These situations tend to be relatively A do-while is used for a block of code


rare, thus the simple while is more that must be executed at least once.
commonly used.

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);

Infinite do-while loop

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);

We can use a break to come out of an Infinite loop.

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;

Example# To check whether a number is prime or not.

#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.

Example# Print the number which is not divisible by 3 or 5

#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

A goto statement in C programming provides an unconditional jump from the ‘goto’


to a labeled statement in the same function.

C has a goto statement that permits unstructured jumps to be made.

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

Enter positive value =>-2

Enter an only positive value


Enter positive value =>-3

Enter an only positive value


Enter positive value =>5

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 add(int x,int y)


{
return x+y;
}

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

Enter no1 =>22

Enter no2 =>3

Sum = 25

Exit() function

exit() function terminates the calling process immediately.

We need to add "stdlib.h" to use 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

Converting an expression of a given type into another type is known as type-


casting. typecasting is more used in c language programming.

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.

There are two types of typecasting in c language:

Implicit Conversion
Implicit conversions do not require any operator for conversion.

It is also known as automatic type conversion.

They are automatically performed when a value is copied to a compatible type in


the program.

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.

bool -> char -> short int -> int ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double

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

Converting by using Cast Operator

Cast operator is a unary operator that forces one data type to be converted into
another data type.

There are four types of Casting Operator :

• Static Cast
• Dynamic Cast
• Const Cast
• Reinterpret Cast.
static_cast

It is a compile-time cast.

It not only performs upcasts but also downcasts.

Example# <type> <variablename> = static_cast<type>(x);

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.

Example#<type> *objectname = dynamic_cast<<type> *>(objectname);

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.

Example# const_cast<type&>(variablename) = value;

reinterpret_cast
Converts any pointer type to any other pointer type, even of unrelated classes.

Example# <type>* variablename = reinterpret_cast<type*>(variablename);

C++ Functions: Simple functions


Example:-
Friend function
friend class, a friend function can be granted special access to private
and protected members of a class in C++. They are the non-member
functions that can access and manipulate the private and protected
members of the class for they are declared as friends.
A friend function can be:
1. A global function
2. A member function of another class

A friend function can access the private and protected data of a


class. We declare a friend function using the friend keyword inside the
body of the class.
Syntax:-

class classname{

Friend returntype functionname{arguments);


…..

Features of Friend Functions

• A friend function is a special function in C++ that in spite of


not being a member function of a class has the privilege
to access the private and protected data of a class.
• A friend function is a non-member function or ordinary function
of a class, which is declared as a friend using the keyword
“friend” inside the class. By declaring a function as a friend, all
the access permissions are given to the function.
• The keyword “friend” is placed only in the function declaration
of the friend function and not in the function definition or
call.
• A friend function is called like an ordinary function. It cannot be
called using the object name and dot operator. However, it may
accept the object as an argument whose value it wants to
access.
• A friend function can be declared in any section of the class i.e.
public or private or protected.

Example:

#include <iostream>
using namespace std;

class base {
private:
int private_variable;

protected:
int protected_variable;
public:
base()
{
private_variable = 10;
protected_variable = 99;
}

// friend function declaration


friend void friendFunction(base& obj);
};

// friend function definition


void friendFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}

// 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);
};

// base class for which friend is declared


class base {
private:
int private_variable;

protected:
int protected_variable;

public:
base()
{
private_variable = 10;
protected_variable = 99;
}

// friend function declaration


friend void anotherClass::memberFunction(base&);
};

// friend function definition


void anotherClass::memberFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}

int main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);
return 0;
}
Op

Private Variable: 10
Protected Variable: 99

You might also like