0% found this document useful (0 votes)
3 views

C++ Unit 2 Chap1

The document provides an overview of control statements in C++, including selection and iteration statements. It details various types of selection statements such as if, if-else, nested if, and switch statements, along with examples of their usage. Additionally, it covers iterative constructs like while, do-while, and for loops, explaining their structure and providing sample code.

Uploaded by

SushmaRaj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C++ Unit 2 Chap1

The document provides an overview of control statements in C++, including selection and iteration statements. It details various types of selection statements such as if, if-else, nested if, and switch statements, along with examples of their usage. Additionally, it covers iterative constructs like while, do-while, and for loops, explaining their structure and providing sample code.

Uploaded by

SushmaRaj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

C++ Programing Language 1

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:

if(TestCondition) //This Conditionis true


Statement1;
Statement2;

Sushma B | JSSCACS| 2024-25


C++ Programing Language 2

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;

seclargest = (a + b + c) – (largest + smallest);


cout<<”Smallest Number is = “<<smallest<<endl;
cout<<”Second LargestNumberis=“<<seclargest<<endl;
cout<<”Largest Number is = “<< largest<<endl;
getch();
}
EX 2 : WriteaC++program to input the total amount in abill, iftheamount is greater than 1000, a

Sushma B | JSSCACS| 2024-25


C++ Programing Language 3

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

Sushma B | JSSCACS| 2024-25


C++ Programing Language 4

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

Sushma B | JSSCACS| 2024-25


C++ Programing Language 5

 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

Sushma B | JSSCACS| 2024-25


C++ Programing Language 6

structure. Otherwise, Condition 2 is tested. If it is TRUE, Statement 2 is executed control is


transferred out of the structure and so on.
o If none of the condition is satisfied, a statement called default statement is executed.

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.

Units consumed Cost


<30 Rs.3.50 / Unit
>=30 and<50 Rs.4.25 / Unit
>=50 and<100 Rs.5.25 / Unit
>=100 Rs.5.85 / Unit

#include<iostream.h>
#include<conio.h>voi
d main( )
{
int units;

Sushma B | JSSCACS| 2024-25


C++ Programing Language 7

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

Sushma B | JSSCACS| 2024-25


C++ Programing Language 8

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

Sushma B | JSSCACS| 2024-25


C++ Programing Language 9

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

Sushma B | JSSCACS| 2024-25


C++ Programing Language 13

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

Sushma B | JSSCACS| 2024-25


C++ Programing Language 15

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.

Sushma B | JSSCACS| 2024-25


C++ Programing Language 16

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

 This looping structure works as follows:


o Initialization is executed. Generally it is an initial value setting for a counter variable and is
executed only one time.
o Condition is checked.if it is TRUE the loop continues,other wise the loop ends and control
exists from structure.
o Statement is executed as usual, is can either a single statement or a block enclosed in curled
braces { and }.
o Atlast, what ever is specified in the increase field is executed and the loop gets back to
executed step 2.
o The initialization and increase fields are optional. They can remain empty, but in all cases the
semicolon sign between them must be written compulsorily

Sushma B | JSSCACS| 2024-25


o Optionally, using the comma operator we can specify more than one expression in any of the
fields included in a for loop.
Ex 1 Write a C++ program to find the factorial of a number using for statement.
(Hint:5!= 5 * 4 *3 * 2 * 1 = 120)
#include<iostream.h>
#include<conio.h>
void main( )
{
Int num,fact,i;
clrscr( );
cout<<”Enterthe number”<<endl;
cin>>num;
fact=1;
for(i =1; i<=num; i++)
fact=fact*i;
cout<<”Thefactorialof a”<<num<<”!is: “<<fact<<endl;
getch();
}
EX 2 : Write a C++ program to generate the Fibonacci sequence up to a limit usingfor statement.
(Hint: 5 = 0 1 1 2 3)
#include<iostream.h>
#include<conio.h>vo
id main( )
{
Int num,first,second,count,third;
clrscr( );
cout<<”Enter the number limit for Fibonacci Series”<<endl;
cin>>num;
first = 0;
second = 1;
cout<<first<<”\t”<<second;
third = first + second;
for(count=2;third<=num; count++)
{
cout<<”\t”<<third

Sushma B | JSSCACS | 2024-25


first = second;
second = third;
third=first+second;
}
cout<<”\nTotal terms= “<<count<<endl;
getch();
}
 Jump statements or Transfer of control from within loop
Transfer of control within looping are used to
o Terminate the execution of loop.
o Exiting a loop.
o Half way through to skip the loop.
All these can be done by using break, exit and continue statements.

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

Sushma B | JSSCACS | 2024-25


for(i=2;i<=n/2;i++)
{
if(n%i ==0)
{
cout<<”It is not a prime”<<endl;
exit(0);
}
}
cout<<”Itis aprime number”<<endl;
getch();
}
 Continue statement:
o The continue statement causes the program to skip the rest of the loop in the current
iteration as if end of the statement block has been reached, causing it to jump to start of the
following iteration.
o The continue statement works some what like break statement.
o Instead of forcingtermination, however continue forces the next iteration of the loop to take
place, skipping any code in between.
o Thegeneralformofthecontinuestatement is:
continue;
 Example:
for(n=10;n<0;n--)
{
if(n==10)continue;
cout<<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( );
}

Sushma B | JSSCACS | 2024-25

You might also like