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

CHAPTER 7cs

Chapter 7 discusses control statements in C++, focusing on decision-making statements like if, if...else, and switch, as well as iteration statements such as while, for, and do...while. It also covers nesting of control statements, jump statements like break and continue, and provides examples for each type. The chapter emphasizes the syntax and usage of these statements to control the flow of a program.

Uploaded by

aleenamb78
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)
2 views

CHAPTER 7cs

Chapter 7 discusses control statements in C++, focusing on decision-making statements like if, if...else, and switch, as well as iteration statements such as while, for, and do...while. It also covers nesting of control statements, jump statements like break and continue, and provides examples for each type. The chapter emphasizes the syntax and usage of these statements to control the flow of a program.

Uploaded by

aleenamb78
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/ 12

CHAPTER 7

CONTROL STATEMENTS

Decision making statements


The statements provided by C++ for the selected execution are called decision making
statements or selection statements. if and switch are the two types of selection
statements in C++.

if Statement
The if statement is used to select a set of statements for execution based on a condition.
In C++, conditions (otherwise known as test expressions) are provided by relational
or logical expressions. The syntax (general form) of if statement is as follows:
if (test expression)
Body of if statement
{
that consists of the
statement block;
statement(s) to be
} executed when the
condition is true

Here the test expression represents a condition which is either a relational


expression or logical expression. If the test expression evaluates to True (non-zero
value), a statement or a block of statements associated with if is executed. Otherwise,
the control moves to the statement following the if construct.

The test expression is always enclosed in parentheses.


The expression may be a simple expression constituted by relational expression or a

compound expression constituted by logical expression.


The statement block may contain a single statement or multiple statements. If there is a

single statement, then it is not mandatory to enclose it in curly braces { }.


Program: To display 'You have passed' if score is 18 or more
#include<iostream>
using namespace std;
int main()
{
int score ;
Body of if
cout << "Enter your score: ";
cin >> score;
if (score >= 18)
cout << "You have passed";
return 0;
}

The following is a sample output of program 7.1:


Enter your score: 25
You have passed
The test expression compares the value of score with 18. The body of if will be
executed only if the test expression evaluates to True. That means, when the score is greater
than or equal to 18, the output You have Passed will be displayed on the screen.
Otherwise, there will be no output.

if...else statement
The syntax is:

if (test expression)
{
statement block 1;
}
else
{
statement block 2;
}

If the test expression evaluates

to True, only the statement block 1

is executed. If the t e s t

expression evaluates to False

statement block 2 is executed.


Nested if
In some situations there may arise the need to take a decision within if block. When
we write an if statement inside another if block, it is called nesting. Nested means
one inside another.

An if statement, inside another if statement is termed as a nested


if statement. The following is an expanded form of nested if.

if (test expression 1)
It will be executed if both
{
the test expressions are
if (test expression 2)
True
statement 1;
else
statement 2;
} It will be executed if test
else expression 1 is True, but
{ test expression 2 is
body of else ; False
}

It will be executed if test expression 1 is


False. The test expression 2 is not evaluated

The else if ladder


It is also known as if...else if statement. The general form of else if ladder is:
if (test expression 1)
statement block 1;
else if (test expression 2)
statement block 2;
else if (test expression 3)
statement block 3;
...............
else
statement block n;
At first, the test expression 1 is evaluated and if it is True, the statement
block 1 is executed and the control comes out of the ladder. That means, the rest of
the ladder is bypassed. If test expression 1 evaluates to False, then the test
expression 2 is evaluated and so on. If any one of the test expressions evaluates
to True, the corresponding statement block is executed and control comes out of the
ladder. If all the test expressions are evaluated to False, the statement block n after the
final else is executed.
Program: To find the grade of a student for a given score

#include <iostream>
using namespace std;
int main()
{
int score;
cout << "Enter your score: ";
cin >> score;
if (score >= 80)
cout << "A Grade";
else if (score >= 60)
cout << "B Grade ";
else if (score >= 40)
cout << "C grade";
else if (score >= 30)
cout << "D grade";
else
cout << "E Grade";
return 0;
}

switch statement
The syntax of switch statement is as follows:
switch(expression)
{

case constant_1 : statement block 1;


break;

: statement block 2;
case constant_2
break;
: statement block 3;
case constant_3
break;
:

:
case constant_n-1 : statement block n-1;
break;
default : statement block n;
}
In the syntax switch, case, break and default are keywords.
Program: To display the day of a week using switch statement

#include <iostream>
using namespace std;
int main()
{ int day ;
cout << "Enter a number between 1 and 7: ";
cin >> day ;
switch (day)
{
case 1: cout << "Sunday";
break;
case 2: cout << "Monday";
break;
case 3: cout << "Tuesday";
break;
case 4: cout << "Wednesday";
break;
case 5: cout << "Thursday";
break;
case 6: cout << "Friday";
break;
case 7: cout << "Saturday";
break;
default: cout << "Wrong input";
}
return 0;
}
switch statement else if ladder
• Permits multiple branching • Permits multiple branching
• Evaluates conditions with equality operator • Evaluates any relational or logical
only expression

• Case constant must be an integer or a character • Condition may include range of


type value values and floating point constants

 When no match is found, default • When no expression evaluates


statement is executed to True, else block is executed

• break statement is required to exit from • Program control automatically goes


switch statement out after the completion of a block
• More efficient when the same variable or
• More flexible and versatile compared
expression is compared against a set of values
to switch
for equality

Table Comparison between switch and else if ladder

The conditional operator (?:)

C++ has a ternary operator. It is the conditional operator (?:) consisting of the symbols
? and : (a question mark and a colon). It requires three operands to operate upon. It can be
used as an alternative to if...else statement. Its general form is:

Test expression ? True_case code : False_case code;

The operation performed by this operator is shown below with the help of an if statement.
if (Test expression)
{
True_case code;
}
else
{
False_case code;
}
he conditional operator works in the same way as if...else works. It evaluates
the test expression and if it is true, the True_case code is executed. Otherwise,
False_case code is executed.

Program: To find the larger number using the conditional operator

#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout << "Enter two numbers: ";
cin>> num1 >> num2 ;
(num1>num2)? cout<<num1<<" is larger" : cout<<num2<<" is larger";
return 0;
}

Iteration statements
While writing programs, we use some specific constructs of the language to perform the
repeated execution of a set of one or more statements. Such constructs are called iteration
statements or looping statements.

while statement
while loop is an entry-controlled loop. The syntax of while loop is:

initialisation of loop control variable;


while(test expression)
{
body of the loop;
updation of loop control variable;
}

for statement
for loop is also an entry-controlled loop in C++. All the three loop elements
(initialisation, test expression and update statement) are placed together in for
statement. The syntax is:
for (initialisation; test expression; update statement)
{
body-of-the-loop;
}
do...while statement
In the case of for loop and while loop, the test expression is evaluated before executing
the body of the loop. If the test expression evaluates to False for the first time itself, the
body is never executed. But in some situations, it is necessary to execute the loop body at
least once, without considering the result of the test expression. In that case the do...while
loop is the best choice. Its syntax is :
initialisation of loop control variable;
do
{
body of the loop;
updation of loop control variable;
} while(test expression);

for loop while loop do...while loop

Entry controlled loop Entry controlled loop Exit controlled loop

Initialization along with loop Initialization before loop Initialization before loop
definition definition definition
Will execute the loop body at
No guarantee to execute the No guarantee to execute the least once even though the
loop body at least once loop body at least once condition is False

Table: Comparison between the looping statements of C++

Nesting of loops

Placing a loop inside the body of another loop is called nesting of a loop. When we nest
two loops, the outer loop counts the number of completed repetitions of the inner loop.
Here the loop control variables for the two loops should be different.

Let us write a program to display the following triangle using nested loop:
*
**
***
****
*****
Program: To display a triangle of stars

#include<iostream>
using namespace std;
int main()
{ int i, j;
char ch = '*';
for(i=1; i<=5; ++i) //outer loop
{
cout<< "\n" ;
for(j=1; j<=i; ++j) // inner loop
cout<<ch;
}
return 0;
}

Nesting of control statements

Any control statement can be nested with another control statement.

Program: To input two numbers and perform an arithmetic operation based on user’s
choice

#include<iostream>
using namespace std;
int main()
{
char ch;
float n1, n2;
cout<<"Enter two numbers: ";
cin>>n1>>n2;
do
{
cout<<"\nNumber 1: “<<n1<<“\tNumber 2: "<<n2;
cout<<"\n\t\tOperator Menu";
cout<<"\n\t1. Addition (+)";
cout<<"\n\t2. Subtraction (–)";
cout<<"\n\t3. Multiplication (*)";
cout<<"\n\t4. Division (/)";
cout<<"\n\t5. Exit (E)";
cout<<"\nEnter Option number or operator: ";
cin>>ch;
switch(ch)
{
case '1' :
case '+' : cout<<n1<<" + "<<n2<<" = "<<n1+n2;
break;
case '2' :
case '-' : cout<<n1<<" - "<<n2<<" = "<<n1-n2;
break;
case '3' :
case '*' : cout<<n1<<" * "<<n2<<" = "<<n1*n2;
break;
case '4' :
case '/' : cout<<n1<<" / "<<n2<<" = "<<n1/n2;
break;
case '5' :
case 'E' :
case 'e' : cout<<"Thank You for using the program";
break;
default : cout<<"Invalid Choice!!";
}
} while (ch!='5' && ch!='E' && ch!='e');
return 0;
}

Jump statements

The statements that facilitate the transfer of program control from one place to another
are called jump statements. C++ provides four types of jump statements that perform
unconditional branching in a program. They are return, goto, break and continue statements.

goto statement

The goto statement can transfer the program control to anywhere in the function. The target
destination of a goto statement is marked by a label, which is an identifier. The syntax of
goto statement is:

goto label;
............;
............;
label: ..........;
............;
break statement

When a break statement is encountered in a program, it takes the program control outside
the immediate enclosing loop (for, while, do...while) or switch statement. Execution
continues from the statement immediately after the control structure.

Code segment 1:
i=1;
while(i<=10)
{
cin>>num;
if (num==0)
break;
cout<<"Entered number is: "<<num;
cout<<"\nInside the loop";
++i;
}
cout<<"\nComes out of the loop";
The above code fragment allows to input 10 different numbers. During the input if any
number happens to be 0, the program control comes out of the loop by skipping the rest of
the statements within the loop-body and displays the message “Comes out of the loop”
on the screen.

continue statement

continue statement is another jump statement used for skipping over a part of the code
within the loop-body and forcing the next iteration. The break statement forces
termination of the loop, but continue statement forces next iteration of the loop. The
following program segment explains the working of continue statement:

for (i=1; i<=10; ++i)


{
if (i==6)
continue;
cout<<i<<"\t";
}
This code gives the following output:
1 2 3 4 5 7 8 9 10
Note that 6 is not in the list. When the value of i becomes 6 the continue statement
is executed. As a result, the output statement is skipped and program control goes to
the update expression for next iteration.
comparison between break and continue statements.

Break statement Continue statement


• Used only with loops.

• Used with switch and loops.

• Brings the program control to the


• Brings the program control outside the switch
beginning of the loop by skipping
or loop by skipping the rest of the statements
the rest of the statements within
within the block.
the block.

• Program control goes out of the loop even though


• Program control goes out of the
the test expression is True.
loop only when the test expression
becomes False.

Program: To check whether the given number is prime or not

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i, num;
cout<<"Enter the number: ";
cin>>num;
for(i=2; i<=num/2; ++i)
{
if(num%i == 0)
{
cout<<"Not a Prime Number";
exit(0);
}
}
cout<<"Prime Number";
return 0;
}

C++ provides a built-in function exit() which terminates the program itself. The exit( )
function can be used in a program only if we include the header file cstdlib.

You might also like