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

Chapter 4 - Control Statements

The document discusses different types of control statements in C++ including selection statements like if and switch statements as well as iteration statements like for, while and do-while loops. It provides syntax and examples for if, if-else, nested if, switch statements and explains the concepts of sequence, selection and iteration in program flow control.

Uploaded by

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

Chapter 4 - Control Statements

The document discusses different types of control statements in C++ including selection statements like if and switch statements as well as iteration statements like for, while and do-while loops. It provides syntax and examples for if, if-else, nested if, switch statements and explains the concepts of sequence, selection and iteration in program flow control.

Uploaded by

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

CHAPTER FOUR

C++
Control Statements

05/27/2024 C++ Control Statements 1


Contents
1. Selection(conditional) Statements
 if, if…else, if…else if, switch
2. Loops
 for, while, do…while
3. Flow control statements(other
statements
 [break, continue, go to, return]
05/27/2024 C++ Control Statements 2
INTRODUCTION
Generally a program executes its statements from
beginning to the end, but all programs don't
follow this.
STATEMENTS
 Statements are the instructions given to the
computer to perform any kind of data movements,
be it making decisions or repeating actions.
 They form the smallest executable unit of the
program. They are terminated by a semicolon(;). The
different types of statements are:-
05/27/2024 C++ Control Statements 3
Compound Statements(Block)
A block is a group of statements that are
enclosed in a pair of curly brackets:-
{
statement:-1
statement:-2
}
 It may appear anywhere in a program as a
single statement of the program.
 A block is many times known as compound
statements.
05/27/2024 C++ Control Statements 4
STATEMENT FLOW CONTROL
In a program, statements may be executed sequentially,
selectively or iteratively:-
 This is the default flow of the statements
Sequence:
and also known as sequence construct.
 Statements are being executed sequentially.

Selection:  Execution of the statements depends on a


condition-test.
 If the condition is true then the statements
would be executed else they would be
skipped.
 If-else statement is a good example of
05/27/2024
selectionC++statement.
Control Statements 5
Iteration:  It’s repetition of a certain set of statements
based on a certain condition-test.
 Looping statements can be used to perform
the repetition of a certain set of statements.
 Three types:- for, do-while & while loop.
SELECTION STATEMENTS
 They allow to choose a certain set of statements for
execution only if a condition is true.
 There are two types of selection statements provided by c+
+ namely if statement and switch statement.
THE IF STATEMENT IN C++
An if statement tests for a particular condition, if the
statement is true then the particular set of statements is
executed
05/27/2024
else they are skipped.
C++ Control Statements 6
FLOW CONTROL
• In a program statement may be executed
sequentially, selectively or iteratively.
• Every program language provides constructs
to support sequence, selection or iteration.

05/27/2024 C++ Control Statements 7


Sequence
• Sequence construct mean statement are
executed sequentially.
• Every program begins with the first statement of
main(). Each statement in turn executed
sequentially when the final statement of main() is
executed the program is done.
THE SEQUENCE CONSTRUCT

Statement 1

Statement 2

Statement 3
05/27/2024 C++ Control Statements 8
SELECTION
Selection
• The Selection construct means the execution
of statement(s) depending upon a condition-
test.
• If a condition evaluates to true, a course-of-
action (a set of statements) is followed
otherwise another course -of-action (a
different set of statements).
• This construct(selection construct) is also
called decision construct because it helps in
making decision about which set-of-
statements is to be executed.
05/27/2024 C++ Control Statements 9
THE SELECTION CONSTRUCT

Condition ? Statement 1 Statement 2

Statement 1

Statement 2

05/27/2024 C++ Control Statements 10


ITERATION
• Iteration construct means repetition of set
of statements depending upon a condition
test.
• Till the time of condition is true. (or false
depending upon the loop).
• A set of statements are repeated again and
again.
• As soon as the condition become false (or
true), the repetition stops. The iteration
condition is also called ”Looping Construct”.
05/27/2024 C++ Control Statements 11
THE ITERATION CONSTRUCT

Condition ? False

True

Statement 1
The Loop Body

Statement 2

05/27/2024 C++ Control Statements 12


THE SELECTION STATEMENT – if Statement
• An if statement test a particular condition, if
the condition evaluated to true, a course of
action is followed, i.e. a statement or a set of
statement is executed.
• Otherwise if the condition evaluated to false
then the course of action is ignored.

05/27/2024 C++ Control Statements 13


SYNTAX OF if STATEMENT
if (condition)
statement 1;
 The statement may consist of single or compound.
 If the condition evaluates non zero value that is true
then the statement 1 is executed otherwise if the
condition evaluates zero i.e., false then the
statement 1 is ignored.
Example 1:
if (age>18)
cout<<“The person is eligible for vote”
Example 2:
if(ch==‘ ‘)
spaces++;
05/27/2024 C++ Control Statements 14
if - else FORMAT
if (condition)
{
Statement 1
Statement 2
}
else
{
Statement 1
Statement 2
}

Example of if-else
if (basic>8000)
{
total_da=(40*basic)/100
gross=total_da + basic
}
else
{
total_da=(40*basic)/100
05/27/2024 gross=total_da + basic
C++ Control Statements 15
}
NESTED IFs
A nested if is an if that has another if in its body
or in its else body. The nested if can have one of
the following three forms.
Form 1 :
if (expression 1)
{
if (expression 2)
statement 1
else
statement 2
}
else
body of else
05/27/2024 C++ Control Statements 16
Form 2:
if (expression 1)
{
if (expression 2)
statement 1
else
statement 2
……….
}
else
{
if (expression 2)
statement 1
else
statement 2
……….
05/27/2024 } C++ Control Statements 17
Form 3:
if (expression 1)
{
body of if
}
else
{
if (expression 2)
statement 1
else
statement 2
……….
}

05/27/2024 C++ Control Statements 18


Program to create the equivalent of a
four function calculator

#include<iostream.h>
int main()
{
char ch;
float a,b, result;
cout<<"Enter the two values" ;
cin>>a>>b;
cout<<"Enter the Operator [ + - * / ] : ";
cin>>ch;

05/27/2024 C++ Control Statements 19


…continued
if(ch=='+')
result=a+b;
else if(ch=='-')
result=a-b;
else if(ch=='*')
result=a*b;
else if(ch=='/')
result=a/b;
else
cout<<"Unknown Operation ";
cout<<"\nThe Resultis : "<<result;
return 0;
}
05/27/2024 C++ Control Statements 20
THE if-else-if LADDER
• A common programming construct in C++ is the
if-else-if ladder, which is often also called as the
if-else-if ladder because of its appearance.
• It takes the following general form.
if (expression 1)
statement 1;
else if (expression 2)
statement 2
else if (expression 3)
statement 3
……….
else
05/27/2024 statement
C++ Control4;
Statements 21
THE switch STATEMENT

• C++ provides multiple- branch selection statement


known as switch.
• This selection statement successively tests the value
of an expression against the list of integer or
character constants.
• When a match is found, the statements associated
with that construct are executed.

05/27/2024 C++ Control Statements 22


THE switch STATEMENT
 The syntax is:
switch(expression)
{
case constant 1 :
statement sequence 1;
break;
case constant 2 :
statement sequence 2;
break;

default:
statement sequence 3;
break;
}
05/27/2024 C++ Control Statements 23
Example of switch

#include<iostream.h>
void main()
{ case 6 : cout<<“\n Friday”;
int dow; break;
cout<<“Enter the number of day”; case 7 : cout<<“\nSaturday”;
cin>>dow; break;
switch(dow) default :cout<<“Wrong
number of day”
{ break;
case 1 : cout<<“\n Sunday”; }
break; }
case 2 : cout<<“\n Monday”;
break; Out put
case 3 : cout<<“\n Tuesday”; Enter the number of day 5
break; Thursday
case 4 : cout<<“\n Wednesday”;
break;
case 5 : cout<<“\n Thursday”;
05/27/2024 C++ Control Statements 24
break;
THE switch Vs if-else-if
• Both let you select an alternative out of many
alternatives by testing an expression.
• However there are some differences in their
operation and they are,
1. Switch can only test for equality where as if can
evaluate a relational or logical expressions
i.e multiple conditions.
2. The switch statement selects its branches by
testing the value of same variable (against the
set of constants) where as the if else
construction lets you to use a series of
expressions that may involve unrelated
variables and complex expressions.
05/27/2024 C++ Control Statements 25
…continued
3. The if-else-if is more versatile/multipurpose of
two statements where as switch cannot. Each
switch case label must be a single value.

4. The if-else-if statement can handle floating


point tests also apart from integer and
character tests where as switch cannot
handle floating point tests. The case labels
of switch must be an integer or character.

05/27/2024 C++ Control Statements 26


The Nested Switch
• Like if statement, switch can also be nested.
• For example following code fragment is perfectly
all right in C++.
switch (a)
{
case 1: switch(b)
{
case 0 : cout<<“Divide by zero error”;
break;
case 1 : res=a/b;
break;
} // inner switch end
break; // outer switch case 1’s break
case 2 : //outer switch case 2
……
05/27/2024 C++ Control Statements 27
} // outer switch end.
More about Switch
1. A switch statement can only work for equality
comparisons.
2. Now two case labels in the same switch can
have the identical values but in case of nested
witch the case constants of inner and outer
switch can contain common values.
3. If a characters constants are used in switch
statements, they are automatically converted
into integers (equivalent ASCII codes).
4. The switch statement is more efficient than if in
a situation that supports the nature of switch
operation.
05/27/2024 C++ Control Statements 28
More about Switch
• For example a statement that tests values against a
set of constants like this,
if (wish==‘a’)
{ …..
.….
}
else if (wish ==‘b’)
{ …..
…..
}
else if (wish ==‘c’)
{ …..
…..
}
else
{ …..
…..
05/27/2024 C++ Control Statements 29
}
…continued
It is better written as a switch statement as,
switch(wish)
{ case ‘a’: ……
..….
break;
case ‘b’ : ……
..….
break;
case ‘c’: ……
..….
break;
default : ……
..….
break;
} //end of switch body
05/27/2024 C++ Control Statements 30
ITERATION STATEMENT
• The iteration statement allows instructions to
be executed until a certain condition is to be
fulfilled.
• The iteration statements are also called as
loops or Looping statements.
• C++ provides three kinds of loops
1. while
2. do-while
3. for

05/27/2024 C++ Control Statements 31


THE while LOOP – AN ENTRY CONTROLLED LOOP

• The second loop available in C++ is the while


loop.
• The while loop is an entry controlled loop the
syntax of while is:
while(expression)
Loop body
 Where, loop body contain the single statement
or set of statements (compound statement) or
an empty statement.
 The loop iterates while the expression
evaluates to true, when expression becomes
false the loop terminates.
05/27/2024 C++ Control Statements 32
VARIATIONS IN while LOOP
A while loop can also have variations.it can be
1. Empty loop : it does not contain any statement in
its body.
2. An infinite loop : while can be infinite if you forget
to update expression inside the body of the loop.
EXAMPLE : EMPTY LOOP
….
….
long wait=0;
while (++wait<10000)
 The above given is the TIME DELAY LOOP. It is
useful for pausing the program for some time.
05/27/2024 C++ Control Statements 33
EXAMPLE : INFINITE LOOP
int j=0;
while(j<=n)
cout<<“\n”<< j * j ;
j++;
….
 The above loop is an infinite loop as a only one statement
taken into a loop’s body
EXAMPLE : FINITE LOOP
j=0
while(j<=n)
{
cout<<“\n”<< j * j ;
j++;
}
….
 The above loop is an finite loop. It will terminate as soon
as the value of j exceeds
05/27/2024
the n.
C++ Control Statements 34
THE do-while LOOP – AN EXIT
CONTROLLED LOOP
• Unlike the for and while the do-while loop is an
exit controlled loop.
• it evaluates its test expression at the bottom of
the loop after executing its loop –body
statements.
• The syntax is:
do
{
Statements
}
while(test expression); // here semicolon must
05/27/2024 C++ Control Statements 35
THE do-while LOOP – AN EXIT
CONTROLLED LOOP
char ch=‘A’;
do {
cout<<“\n”<<ch;
ch++;
}
while (ch<=‘Z’);
 The above code prints the character from ‘A’ onwards until
the condition ch<=‘Z’ becomes false.
 The most common use of the do-while loop is in menu
selection routine, where the menu is flashed at once and
depending upon the users response either it is repeated
or terminated.
05/27/2024 C++ Control Statements 36
Elements that control a Loop
• Every loop has its elements that control and govern
its execution.
• Generally a loop has four elements that have
different purposes, they are,
1. INITILIZATION EXPRESSIONS
 Before entering in a loop, its control variable must
be initialized.
 The initialization expression executed at only once.
2. TEST EXPRESSION
 The test expression is an expression whose truth
values decides weather the loop- body will be
executed or not.
 If the test expression evaluates to true I.e., the loop
05/27/2024 gets executed, otherwise the loop terminated.
C++ Control Statements 37
…continued
3. UPDATED EXPRESSION
 The update expression change the value(s) of
loop variable(s).
 The update expression(s) is executed; at the
end of the loop after the loop-body is
executed.
4. THE BODY OF THE LOOP
 The statements that are executed repeatedly as
long as the value of expression is non zero.
 If it evaluates to zero then the loop is
terminated.

05/27/2024 C++ Control Statements 38


THE for LOOP
 The for loop is the easiest to understand of the
C++ loops. The general form of for loop is,
Syntax:
for(initialization expression(s); test expression; update expression)
body of for loop
Example:- for LOOP
#include<iostream.h>
int main()
{
int i;
for (i=1; i<=10; ++I ) // do not give semicolon here.
cout<<“\n”<<i;
return 0;
}
NOTE: NO SEMICOLON IN FOR STATEMENT
05/27/2024 C++ Control Statements 39
Example: for LOOP
Initilization exp; Test Exp; Update Exp
for ( i=1; i <=10; ++i )
cout<<“\n”<<i; // Body of the loop

THE for LOOP VARIATIONS


• C++ offers several variations that
increase the flexibility and applicability of
for loop.

05/27/2024 C++ Control Statements 40


DECLARATION OF VARIABLES IN THE LOOP

• C++ allows to declare variables anywhere in a


program.
• So they are generally declared immediately
before there first reference.
• For example
for(int i=0;i<10;++i)
NOTE : Variables can be accessed only in the
block where it has been declared.
VARIABLE’S SCOPE
• The program area inside which a variable can
be accessed, is called variable’s scope.

05/27/2024 C++ Control Statements 41


THE SCOPE OF LOCAL LOOP VARIABLE
• Until now, a variable declared in the for or while loop could
be accessed after the statement because the variable
declaration had not taken place within the braces of the
loop block, the item would still be in scope when the loop
terminates.
• That means the same variable could not be declared in
another loop in the same scope.
• For example,
for(char ch=‘a’; ch<=‘z’; ++ch)
{
……
……
}
cout<<ch; // ch was still valid. It was still in the scope
for(char ch=‘a’; ch<=‘z’; ++ch) // Wrong!!!
{
……
05/27/2024
} C++ Control Statements 42
NESTED LOOPS
A loop can contain another loop in its body. This
form of a loop is called nested loop.
In nested loop the inner loop must terminate
before the outer loop.
for(i=1;i<=5;i++) {
for(j=1;j<=i;j++) {
cout<<“* “; }
cout<<“\n”;
}
The above prints following out put
*
**
***
****
*****
05/27/2024 C++ Control Statements 43
JUMP STATEMENTS(other statements
 Jump statements unconditionally transfer
program control within a function.
 C++ has four jump statements that perform
an unconditional branch: return, goto,
break, and continue.
 Of these return and goto maybe used
anywhere in the program but break and
continue can be used only inside brackets { }

05/27/2024 C++ Control Statements 44


THE goto STATEMENT
 The destination of a goto statement is marked by a label.
 The label and goto must appear in the same function.

THE break STATEMENT


 It enables the user to skip over a part of the program.
 It is used inside brackets { }.
 It brings the program control directly outside the
brackets { }.

THE continue STATEMENT


 It skips a certain part of the code but does not
terminate the loop but skips a certain part of the code.
05/27/2024 C++ Control Statements 45
JUMP STATEMENT - goto
The goto statement is rarely used in the
programming.
A goto statement can transfer the program
control anywhere in the program. The target
destination of a goto statement is marked by the
label.
Syntax is,
goto label; //here you put semicolon
…….
…….
…….
label : //here you put colon
05/27/2024 C++ Control Statements 46
JUMP STATEMENT – goto Example

int a=0;
start :
cout<<++a<<“, ”;
if(a<5)
{
goto start;
}
else
{
cout<<“STOP”;
}
05/27/2024 C++ Control Statements 47
break STATEMENT
 The break statement enables the program to
skip over the part of the code.
 A break statement terminates the smallest
enclosing while, do-while, for or switch
statement.

05/27/2024 C++ Control Statements 48


break STATEMENT - EXAMPLE
while (test expression)
{
statement
if(val>2000)
break;
…..
statement;
}
statement 3;

05/27/2024 C++ Control Statements 49


break STATEMENT-EXAMPLE
for( initialize; test expression; update expression)
{
statement
if(val>2000)
break;
…..
statement;
}
statement 3;

05/27/2024 C++ Control Statements 50


break STATEMENT-EXAMPLE

do {
statement
if(val>2000)
break;
…..
statement;
} while (test expression);
statement 3;

05/27/2024 C++ Control Statements 51


THE continue STATEMENT
• The continue statement is the another
jump statement like the break as the
both the statements skips over the part
of code.
• But the continue statement is some what
different than the break.
• Instead of forcing for termination it forces
for the next iteration of the loop to take
place.

05/27/2024 C++ Control Statements 52


THE continue STATEMENT EXAMPLE

while (test expression)


{
statement
if(condition)
continue;
…..
statement;
}
statement 3;

05/27/2024 C++ Control Statements 53


THE continue STATEMENT EXAMPLE
for (initialize; test expression; update expression )
{
statement
if(condition)
continue;
…..
statement;
}
statement 3;

05/27/2024 C++ Control Statements 54


THE exit() FUNTION
• The exit() function causes the program to
terminate as soon as it is encountered.
• The exit() function is a C++ standard
library function defined in process.h file.
• Which must be included in the program
that uses exit() function.

05/27/2024 C++ Control Statements 55


EXAMPLE exit() FUNCTION
// Program to check entered number is prime number or not
#include<iostream.h>
#include<process.h>
void main()
{
int num,i;
cout<<"Enter the Number: ";
cin>>num;
for(i=; i<=num/2;++i)
{
cout<<"\n Not a Prime Number";
exit(0);
}
cout<<"\n It is Prime Number";
}
Enter the Number: 4
Not a Prime Number
05/27/2024 C++ Control Statements 56

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy