C++ Unit 2 Chap1
C++ Unit 2 Chap1
UNIT 2
CONTROL STATEMENTS
Introduction
o Control statements are statements that alter the sequence of flow of instructions.
o Any single input statement, assignment and output statement is simple statement.
o A group of statement that are separated by semicolon and enclosed within curled braces
{ and } is called a block or compound statement.
o The order in which statements are executed in a program is called flow of control.
Types of control statements:
• C++ supports two basic control statements.
o Selection statements
o Iteration statements
Selection Statements:
o This statement allows us to select a statement or set of statements for execution based on
some condition.
o It is also known as conditional statement.
o This structure helps the programmer to take appropriate decision.
o The different selection statements,viz.
• ifstatement
• if– elsestatement
• Nested–ifstatement
• switch statement
if statement:
o This is the simplest form of if statement.
o This statement is also called as one-way branching.
o This statement is used to decide whether a statement or set of statements should be
executed or not.
o The decision is based on acondition which can be evaluated toTRUE or FALSE.
o The general form of simple–if statement is:
o Here, the test condition is tested which results in either a TRUE or FALSE value. If the
result of the test condition is TRUE then the Statement 1 is executed. Otherwise, Statement
2 is executed.
Ex:if(amount >=5000 )
discount=amount*(10/100); net-amount = amount – discount;
EX 1 : Write a C++ program to find the largest, smallest and second
largest of three numbers using simple if statement.
#include<iostream.h>
#include<conio.h>voi
d main( )
{
Int a, b, c;
int largest,smallest,seclargest;
clrscr( );
cout<<”Enter the three numbers”<<endl;
cin>>a>>b>>c;
largest = a; //Assumefirstnumberaslargest
if(b>largest)
largest=b;
if(c>largest)
largest=c;
smallest = a; //Assumefirstnumberassmallest
if(b<smallest)
smallest=b;
if(c<smallest)
smallest=c;
discount of 8% is given. Otherwise, no discount is given. Output the total amount, discount and the
final amount. Use simple if statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
Float TAmount, discount, FAmount;
clrscr( );
cout<<”EntertheTotal Amount”<<endl;
cin>>TAmount;
discount=0; //CalculateDiscount
if(TAmount>1000)
Discount=(8/100)*TAmount;
FAmount=TAmount –Discount //CalculateFinalAmount
cout<<”ToatalAmount=“<<TAmount<<endl;
cout<<”Discount = “<<discount<<endl;
cout<<”Final Amount = “<< FAmount<<endl;
getch( );
}
if–else statement:
o This structure helps to decide whether a set of statements should be executed or another set
of statements should be executed.
o This statement is also called as two-way branching.
o The general form of if–elsestatementis:
if (Test Condition)
Statement1;
else
Statement2;
o Here, the test condition is tested.If the test- condition is TRUE, statement-1 is executed.
Otherwise Statement 2 is executed.
Ex:if(n %2 ==0 )
cout<<”NumberisEven”;
else
cout<<”NumberisOdd”;
EX 1 : Write a C++ program to check whether a given year is a leap year not,Using if- else statement.
#include<iostream.h>
#include<conio.h>voi
d main( )
{
Int year;
clrscr( );
cout<<”Enter the Year in the form YYYY”<<endl;
cin>>year;
if(year%4==0&&year%100!=0||year%400==0)
cout<<year<<”isaleapyear”<<endl;
else
cout<<year<<”isnotleapyear”<<endl;
getch();
}
EX 2 : Write a C++ program to accept a character. Determine whether the character is a lower-case or
upper-case letter.
#include<iostream.h>
#include<conio.h>
void main( )
{
Char ch;
clrscr();
cout<<”Enterthe Character”<<endl;
cin>>ch;
if(ch>=‘A’ &&ch<=’Z’)
cout<<ch<<”isanUpper-Case Character”<<endl;
else
if(ch>=‘a’&&ch <=’z’)
cout<<ch<<”isanLower-CaseCharacter”<<endl;
else
cout<<ch<<”isnotan alphabet”<<endl;
getch();
}
Nested if statement:
o If the statement of an if statement is another if statement the n such an if statement is
called as Nested-if Statement.
o Nested-ifstatement containsanifstatementwithinanotherif statement.
o There are two forms of nested if statements.
if–else-if statement:
o This structure helps the programmer to decide the execution of a statement from multiple
statements based on a condition.
o There will be more than one condition to test.
o This statement is also called as multiple-way branch.
o The general form of if–else–if statement is:
if(TestCondition1)
Statement1;
else
if(TestCondition2)
Statement2;
elseif(testCondition N)
StatementN;
else
Default Statement;
Example:
if(marks>=85 )
PRINT“Distinction”
else
if(marks>=60 )
PRINT“FirstClass”
else
if(marks>=50 )
PRINT“SecondClass”
else if(marks>=35 )
PRINT“Pass”
else
PRINT“Fail;
o Here, Condition 1 is tested. If it is TRUE, Statement 1 is executed control transferred out of the
EX 1 : Write a C++ program to input the number of units of electricity consumed in a house and calculate
the final amount using nested-if statement. Use the following data for calculation.
#include<iostream.h>
#include<conio.h>voi
d main( )
{
int units;
floatBillamount;
clrscr( );
cout<<”Enterthenumberofunitsconsumed”<<endl;
cin>>units;
if(units<30)
Billamount=units *3.50 ;
else
if(units<50)
Billamount=29* 3.50 + (units– 29)* 4.25 ;
else
if(units<100)
Billamount=29 *3.50 +20 *4.25 +(units–49)* 5.25 ;
else
Billamount=29 * 3.50 + 20 * 4.25 +50* 5.25+(units– 99)* 5.85 ;
cout<<”TotalUnitsConsumed=”<<units<<endl;
cout<<”Toatl Amount = “<<Billamount<<endl;
getch( );
}
The general form of if–else-ifstatement is:
if(TestCondition1) Ex:Tofindthegreatestofthreenumbersa,bandc. if ( a>b
if(TestCondition2) )
Statement1; if(a>c)
OUTPUT a
else
else
Statement2; OUTPUT c
else else
if(b >c)
OUTPUT b
else
OUTPUT c
SwitchStatement:
o C++ has built in multiple-branch selection statement i.e.switch.
o If there are more than two alternatives to be selected, multiple selections construct isused.
o The general formof Switch statement is: Switch ( Expression )
{
Case Label-1: Statement1;
Break;
Case Label-2: Statement1;
Break;
…………..
Case Label-N: StatementN;
Break;
Default : Default-Statement;
}
Ex:To find the name of the day given the day number
switch ( dayno )
{
Case1: cout<<“Sunday”<<endl;
break;
Case2: cout<<“Monday”<<endl;
break;
Case3: cout<<“Tuesday”<<endl;
break;
Case4: cout<<“Wednesday”<<endl;
break;
Case5: cout<<“Thursday”<<endl;
break;
Case6: cout<<“Friday”<<endl;
break;
Case7: cout<<“Saturday”<<endl;
break;
default: cout<<“InvalidDayNumber”<<endl;
}
The switch statement is a bit peculiar with in the C++language because it uses labels instead of
blocks.
This force up to put break statements after the group of statements that we want to execute for
aspecific condition.
Sushma B | JSSCACS| 2024-25
C++ Programing Language 10
Other wise the remainder statements including those corresponding too there labels also are
executed until the end of the switch selective block or a break statement is reached.
Ex : Write a C++ program to input the marks of four subjects. Calculate the total percentage and
output the result as either “First Class” or “Second Class” or “Pass Class” or “Fail” using switch
statement.
Class Range(%)
FirstClass Between60%to100%
SecondClass Between50%to59%
PassClass Between40%to49%
Fail Lessthan 40%
#include<iostream.h>
#include<conio.h>
Void main()
{
Int m1,m2,m3,m4,total,choice; float
per;
clrscr( );
cout<<”Enter the First subject marks”<<endl;
cin>>m1;
cout<<”Enter the Second subject marks”<<endl;
cin>>m2;
cout<<”Enter the Third subject marks”<<endl;
cin>>m3;
cout<<”Enter the Fourth subject marks”<<endl;
cin>>m4;
total=m1+m2+m3+m4; per
= (total / 400) * 100;
cout<<”Percentage= “<<per<<endl;
choice=(int)per/10;
cout<<”The result of the student is: “<<endl;
switch(choice)
Sushma B | JSSCACS| 2024-25
C++ Programing Language 11
{
case 10:
case 9:
case 8:
case 7:
case6:cout<<”FirstClass”<<endl; break;
case5: cout<<”SecondClass”<<endl;
break;
case4:cout<<”Pass Class”<<endl;
break;
default:cout<<”Fail”<<end;
}
getch();
}
Iterative Constructsor Looping
o Iterative statements are the statements that are used to repeatedlyexecute a sequence of
statements until some condition is satisfied or a given number of times.
o The process of repeated execution of a sequence of statements until some condition is
satisfied is called as iteration or repetition or loop.
o Iterative statements are also called as repetitive statement or looping statements.
o There are three types of looping structures in C++.
While loop
Do while loop
For loop
while loop:
o This is a pre-tested loop structure.
o This structure checks the condition at the beginning of the structure.
o The set of statements are executed again and again until the condition is true.
o When the condition becomes false, control is transferred out of the structure.
o The general form of while structure is while ( Test Condition)
{
Statement1
Statement2
Sushma B | JSSCACS| 2024-25
C++ Programing Language 12
……..
StatementN
}
End of While
Example:
n =10;
While(n >0)
{
cout<<n<<”\t”;
--n;
}
cout<<”End of while loop\n”;
Output:10 9 8 76 5 4 3 21 End of while loop
EX 1 : Write a C++ program to find sum of all the digits of a number using while statement.
#include<iostream.h>
#include<conio.h>voi
d main( )
{
intnum,sum,rem; clrscr( );
cout<<”EntertheNumber”<<endl; cin>>num;
sum =0;
while(num!=0)
{
rem = num % 10;
sum=sum+rem;
num = num/10;
}
cout<<”Sumofthedigitsis“<<sum<<endl;
getch();
}
EX 2 : Write a C++ program to input principal amount, rate of interest and time period. Calculate
compound interest using while statement.
(Hint:Amount=P*(1+R/100)T,CompoundInterest=Amount–P)
#include<iostream.h>
#include<conio.h>voi
d main( )
{
Float pri,amt,priamt,rate,ci; int
time, year;
clrscr( );
cout<<”EnterthePrincipalamount,rateofinterestandtime”<<endl;
cin>>pri>>rate>>time;
year = 1;
priamt=pri;
while(year<=time)
{
amt=pri*(1+rate/100); year
++;
}
ci=amt – priamt;
cout<<”CompoundInterestis“<<ci<<endl; getch(
);
}
EX 3: Write a C++ program to check whether the given number is power of 2.
#include<iostream.h>
#include<conio.h>
void main( )
{
intnum,m,flag;
clrscr( );
cout<<”Enterthe Number”<<endl;
cin>>num;
m = num;
Sushma B | JSSCACS| 2024-25
C++ Programing Language 14
flag = 1;
while(num>2)
if(num%2 ==1)
{if(flag)
}
else
flag=0; break;
num =num/2;
else
cout<<m<<”ispowerof 2 “<<endl;
cout<<m<<”is notpowerof2 “<<endl;
getch();
}
Do while statements:
o This is a post-tested loop structure.
o This structure checks the condition attheend ofthestructure.
o The set of statements are executed again and again until the condition is true.
o When the condition becomes false, control is transferred out ofthestructure.
o The general form of while structure is do
{
Statement1
Statement2
……..
StatementN
}while(Test Condition);
Example:
i =2;
do
{
cout<<i<<”\t”;
i =i +2;
} while ( i<=25);
EX 1 Write a C++ program to check whether the given number is an Armstrong Number using do-while
statement. (Hint: 153 = 13 + 53 + 33)
#include<iostream.h>
#include<conio.h>
void main( )
{ Int num,rem,sum,temp;
cout<<”Enterthethreedigitnumber”<<endl;
cin>>num;
temp=num;
sum = 0;
do
{rem=temp%10;
sum=sum+rem*rem*rem; temp = temp / 10;
}while(temp!=0);
if(sum == num)
cout<<num<<”isan ArmstrongNumber “<<endl;
else
cout<<num<<”isnotan ArmstrongNumber “<<endl;
}
Difference between while and do while loop:
while do while
This is pre-tested looping structure This is post tested looping structure
It tests the given condition at in itial point It tests the given condition at the last of
Of looping structure Looping structure.
Minimum execution of loop is zero Minimum execution of loop is once.
Syntax: Syntax:
while(Testcondition) do
{ {
statement1; statement1;
statement2; statement2;
…………….; statementn;
statementn; }
} while(Testcondition);
Semi colon is not used. Semi colon is used.
for statement:
o This structure is the fixed execution structure.
o This structure is usually used when we know in advance exactly how many times as set of
statements is to be repeatedly executed again and again.
o This structure can be used as increment looping or decrement looping structure.
o The general form of for structure is as follows:
for(Expression 1; Expression 2; Expression 3)
{
Statement1;
Statement 2;
StatementN;
}
Where, Expression 1 represents Initialization
Expression 2 represents Condition
Expression 3 represents Increment/Decrement
Example:
sum =0;
for(i=1;i<=10;i++)
sum =sum +i;
break statement
The break statement has two uses
o You can use It to terminate a case in the switch statement.
o You can also use it to force immediate termination of a loop like while, do-while and for, by
passing the normal loop conditional test.
When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement.
The general form of break statement is:
break;
Example:
for(n=0;n<100; n++)
{
cout<<n;
if(n==10)break;
}
Program: To test whether a given number is prime or not using break statement.
#include<iostream.h>
#include,conio.h>voi
d main( )
{
Int n,i,status;
Sushma B | JSSCACS | 2024-25
clrscr( );
cout<<”Enter the number”;
cin>>n;
status=1;
for(i=2;i<=n/2;i++)
{
if(n%i ==0)
{
status=0
cout<<”It is not a prime”<<endl;
break;
}
}
if(status)
cout<<”It is a prime number”<<endl;
getch();
}
exit() function:
o This function causes immediate termination of the entire program, forcing a return to the
operating system.
o In effect, exit( ) function acts as if it were breaking out of the entire program.
o The general form of the exit() functionis:
exit( ); or void exit(intreturn_code);
o The return code is used by the operating system and may be used by calling programs.
o An exit code of 0 means that the program finished normally and any other value means
that some error or unexpected results happened.
Program:To test whethera givennumber is prime or not using exit() statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
int n, i;
clrscr();
cout<<”Enter the number”;
cin>>n;
Goto statement:
o The goto allows to makes an absolute jump to another point in the program.
o This statement execution causes an unconditional jump or transfer of control from one
statement to the other statement with in a program ignoring any type of nesting limitations.
o The destination is identified by a label, which is then used as an argument for the goto
statement.
o A label is made of a valid identifier followed by a colon (:).
o The general form of goto statement is: statement1;
statement2;
Sushma B | JSSCACS | 2024-25
goto
label_name;
statement3;
statement4;
label_name:statement5;
statement6;
Program:To print from 10 to 1 using go to statements.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int n=10;
loop: cout<<”\t”<<n;
n--;
if(n>0) goto loop;
cout<<”Endofloop”;
getch( );
}