0% found this document useful (0 votes)
17 views54 pages

Chapter 4

This chapter four pdf material use it

Uploaded by

jamsibro140
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)
17 views54 pages

Chapter 4

This chapter four pdf material use it

Uploaded by

jamsibro140
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/ 54

Control Structure

3/18/2022 2
Introduction
Flow control in a program is sequential, from one statement to the next,
but may be diverted to other paths by branch statements.

Declaration statements are used for defining variables.

Assignment-like statements are used for simple, algebraic computations.

Branching statements are used for specifying alternate paths of execution,


depending on the outcome of a logical condition.

Loop statements are used for specifying computations, which need to be


repeated until a certain logical condition is satisfied.

Jumping statements are used to divert the execution path to another part
of the program.
3
Conditional Statements
Selection statements are used for specifying alternate paths of
execution, depending on the outcome of a logical condition

The conditional expressions are mainly used for decision making.

The following statements are used to perform the task of the


conditional operations.

if statement.
Nested if –else statement.
If-else statement.
Switch statement.
else-if statement.

3/18/2022 4
if statement
 The if statement is used to express conditional expressions.

 If the given condition is true then it will execute the statements otherwise skip

the statements.

 The general form is:


If (conditional expression)
statement-1;
(or)
If ( conditional expression){
statement-1;
statement-2;
……… STATEMENT-N }
 The expression is evaluated and if the expression is true the statements will be executed.

 If the expression is false the statements are skipped and execution continues with

the next statements.


5
Cont.…
e.g. Write a C++ program to check percentage of a
student and display pass if it is greater than 50.
if (Condition)
#include <iostream.h>
statement;
int main()
{
float percent;
cout<<"Enter your percentage: ";
cin>>percent;
cout<<"You scored“<< percent << "%“ <<
endl;
if (percent>=50)
{
cout<<"Congratulation: You have
passed";
}
return 0;
}

6
if - else statement
 It is a two way branching statement.
 It is similar to if statement but the only difference is if the condition is
false then a different block of statements are executed which is inside else
statement.
Syntax of if-else statement
if (condition)
{
statements;
... ... ...
}
else
{
statements;
... ... ...
}
7
Cont…
#include<iostream.h>
int main () {
int n;
cout<<"Enter a Number: " ;
cin>>n;
if (n%2==0)
{
cout<<n<<" is Even!"; }
Else
{
cout<<n<<" is Odd!"; }
return 0;
}

8
else-if statements
 It used when there are two or more conditions that needs to be
checked to decide which block of statement is to be executed.
Syntax:
if (exp1)
Statement1;
else if (exp>)
Statement2;
else if (exp3)
Statement3;
else
Statement4;
 When a logical expression is encountered whose value is true the
corresponding statements will be executed and the remainder of the nested
else if statement will be bypassed.

3/18/2022 9
Cont...
 Thus control will be transferred out of the entire nest
once a true condition is encountered.

 The final else clause will be apply if none of the exp is


true.

 The number of else if statements depends upon the


number of conditions to be checked.

3/18/2022 10
Cont. …
Syntax of else-if statement
if (condition 1) {
statements;
... ... ...
}
else if (condition 2) {
statements;
}
... ... ... ... ... ...
else if (condition n) {
statements;
... ... ...
}
else {
statements;
}
11
cont…
//else -if equivalent cout<<"x is 2";
#include<iostream.h> }
int main() else if(x ==3)
{ {
int x; cout<<"x is 3";
cout<<"Enter x:"; }
cin>>x; else
if (x == 1) {
{ cout << "value of x
cout << "x is 1"; unknown";
} }
else if(x ==2) return 0;
{ }
3/18/2022 12
Nested if-else statement
 It is possible to nest if-else statements, one within another.
 There are several different form that nested if-else statements can take.
 The most general form of two-layer nesting is

 One complete if-else statement will be executed if expression1 is


true and another complete if-else statement will be executed if
expression1 is false.
3/18/2022 13
Contd...

 An if statement inside another if statement is known as


nested if statements.

 Nested if statements are used if there is a


sub condition to be tested after one condition has been
checked.

 The depth/number of nested if statements depends


upon the number of conditions to be checked.

3/18/2022 14
Con’d...
Syntax of nested if statement statements;
}
if (condition 1) statements;
{ }
statements; ... ... ...
if (sub condition 1) ... ... ...
{ else
statements; {
} statements;
statements; if (sub condition n)
} {
else if (condition 2) statements;
{ }
statements; statements;
if (sub condition 2) }
{
15
Cont...

3/18/2022 16
Cont...
//Demo to check even no. and divisible by 5
#include <iostream.h> else
int main() { {
int n; if (n%5 == 0)
cout<<"Enter a number: "; {
cin>>n; cout<<"Number is not even but
if (n%2 == 0) divisible by 5";
{ }
if (n%5 == 0)
else
{
{
cout<<"Number is even and divisible by 5";
cout<<"Number is not even and
}
not divisible by 5";
else {
cout<<"Number is even but not divisible by 5";
}
} }
}​ return 0;
} 17
Switch statement
The switch statement provides a way of choosing between a set of
alternatives, based on the value of an expression.
The general form of the switch statement is:

switch (expression) {
case Constant1:
statements;
break;
case Constant2:
statements;
break;
default:
statements;
break; }
18
Cont..
First expression (called the switch tag) is evaluated, and the
outcome is compared to each of the numeric constants (called case
labels), in the order they appear, until a match is found.

The statements following the matching case are then executed.

Execution continues until either a break statement is encountered


or all intervening statements until the end of the switch statement
are executed.

The final default case is optional and is exercised if none of the


earlier cases provide a match.

3/18/2022 19
Cond...
Switch(expression) {

case Constant1:

Statement 1;
Break;
Case Constant2:
Statement 2;
Break;
...

Case value n:

Statement n:

Break;

Default:

Statement n

}
3/18/2022 20
Cont...
Rules for Switch Statements
 Values for 'case' must be integer, Boolean or character
constants.

 The order of the 'case' statements is not more obligatory

 The default clause may occur first (convention places it last)

 Cannot use expressions or ranges for the variable.

3/18/2022 21
Cont...
//Switch Case example
#include<iostream.h> case 2:
int main() cout<<"x is 2";
{ break;
int x; default:
cout<<"Enter x:"; cout<<"value of x
cin>>x; unknown";
switch (x) { }
case 1: return 0;
cout<<"x is 1"; }
break;
3/18/2022 22
Cont...
//Switch Case example case 4:
#include<iostream.h> cout<<"the day is Wednesday ";
int main() { break;
int day; case 5:
cout<<"Enter the day number:"; cout<<"the day is Thursday";
cout<<endl; break;
cin>>day; case 6:
switch (day) cout<<"the day is Friday";
{ break;
case 1: case 7:
cout<<"the day is Sunday"; cout<<"the day is Saturday";
break; break;
case 2: default:
cout<<"the day is Monday"; cout<<"unknown value";
break; }
case 3: return 0;
cout<<"the day is Tuesday "; }
break;
3/18/2022 23
Looping Statements
Looping is a way of repeating a series of instructions several
times to execute a block of statements.

 A loop allows to execute a statement or block of statements


repeatedly.

 The statements in the block may be executed any number of


times, from zero to infinite number.

 If a loop continues forever, it is called an infinite loop.


 In looping, a sequence of statements are executed until some
conditions from the termination of the loop are satisfied.
24
Cont…
 A program loop consists of two statements:
1.Body of the loop.
2.Control statements.
 The control statement tests certain conditions and then directs
the repeated execution of the statements contained in the body
of the loop.
 A looping process, in general, would include the following four steps:
1. Setting and initialization of a counter .

2. Test for a specified condition for execution of the loop.

3. Execution of the statements in the loop.

4. Increment/Decrement the counter.


3/18/2022 25
Cont…
 Depending on the position of the control statement in the loop, a
control structure can be either as the entry-controlled loop or as
exit-controlled loop.
 In entry-controlled loop, the control conditions are tested before
the start of the loop execution.
 In exit-controlled loop, the test is performed at the end of the body
of the loop and therefore the body is executed unconditionally for
the first time.
 Three types of loops in C++:
A. for loops:
B. while loops:
C. do …while loops:
3/18/2022 26
A. for Statement
The for statement (also called for loop) is similar to the while
statement, but has two additional components: an expression
which is evaluated only once before everything else, and an
expression which is evaluated once at the end of each iteration.

The general form of the for statement is:

for (expression1; expression2; expression3)

statement;

First expression1 is evaluated. Each time round the loop,


expression2 is evaluated.
3/18/2022 27
Cont…
If the outcome is nonzero then statement is executed and
expression3 is evaluated. Otherwise, the loop is terminated.

The general for loop is equivalent to the following while loop:

expression1;

while (expression2)
{

statement;

expression3;

}
3/18/2022 28
Cont…
The general form of the for statement is:
for(expression1;expression2; expression3)
statement;

3/18/2022 29
Cont…
The most common use of for loops is for situations where a variable is

incremented or decremented with every iteration of the loop.


The following for loop, for example, calculates the sum of all integers
from 1 to n.
sum = 0;
for (i = 1; i <= n; ++i)
sum += i;

This is preferred to the while-loop version.

C++ allows the first expression in a for loop to be a variable definition.

for (int i = 1; i <= n; ++i)

sum += i;
3/18/2022 30
Cont …
 Contrary to what may appear, the scope for i is not the body of the loop, but
the loop itself. Scope-wise, the above is equivalent to:

 int i;

 for (i = 1; i <= n; ++i)

 sum += i;

 Any of the three expressions in a for loop may be empty. For example,
removing the first and the third expression gives us something identical to
a while loop:

 for (; i != 0;) // is equivalent to: while (i != 0)

 statement1;
statment2;
3/18/2022 31
Cont …
Removing all the expressions gives us an infinite loop. This
loop's condition is assumed to be always true.

A loop becomes infinite loop if a condition never becomes false.


for (;;)// infinite loop
statements;
#include <iostream.h>
int main ()
{
for( ; ; )
{
Cout<<"This loop will run forever.\n";
}
return 0;
}
3/18/2022 32
Cont…

//Demo add the first 10 natural numbers


#include<iostream.h>
int main()
{
int sum = 0;
for (int i=0;i<=10;i++) {
sum += i;
}
cout<<"the sum is "<<sum<<endl;
return 0;
}

3/18/2022 33
..
Cont
For loops with multiple loop variables are not unusual.
In such cases, the comma operator is used to separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;

Because loops are statements, they can appear inside other loops.

In other words, loops can be nested. Output:


(1,1)
For example, (1,2)
(1,3)
for (int i = 1; i <= 3; ++i)
(2,1)
for (int j = 1; j <= 3; ++j) (2,2)
(2,3)
cout << '(' << i << ',' << j << ")\n"; (3,1)
(3,2)
(3,3)
3/18/2022 34
Cont …
//C++ Program that Prints 0-n for(int i=1; i<=10; i++)
#include<iostream.h> {
int main() cout<<"\t\t"<<i<<endl;
{ sum+=i;
cout<<"\ \t_____________\n"; }
cout<<"\n\t Numbers 0-10 \n "; cout<<"\n\t The Sum"<<sum;
cout<<"\n\t_____________\n"; cout<<"\n\t_____________\n”;
int sum=0; return 0;
cout<<"\n\t Counting Up \n\n"; }

3/18/2022 35
B. While Statement
The while statement (also called while loop) provides a way of

repeating a statement while a condition holds.

The general form of the while statement is:

while (expression)

statement;

First expression (called the loop condition) is evaluated. If the

outcome is nonzero then statement (called the loop body) is

executed and the whole process is repeated.

Otherwise, the loop is terminated.


36
Cont…
For example, suppose we wish to calculate the sum of all numbers from 1
to some integer denoted by n.
This can be expressed as:
i = 1;
sum = 0;
while (i <= n)
{
sum += i;
i++;
}
The while loop is top tested i.e., it evaluates the condition before executing
statements in the body. Then it is called entry control loop.

3/18/2022 37
Contd..
//While loop demo
#include<iostream.h>
int main()
{
int i=0;
int sum=0;
while(i<=10)
{
sum+=i;
i++;
}
cout<<"\n\t The Sum is "<<sum;
return 0;
}
3/18/2022 38
C. do…while Statement

 The do statement is similar to the while statement, except that its body is
executed first and then the loop condition is examined.
 The general form of the do statement is:
do
statement;
while (expression);
 First statement is executed and then expression is evaluated. If the outcome
of the latter is nonzero then the whole process is repeated. Otherwise, the
loop is terminated.
 It is useful for situations where we need the loop body to be executed at
least once, regardless of the loop condition.
3/18/2022 39
Cont…

 For example, suppose we wish to repeatedly read a value and print


its square, and stop when the value is zero.
 This can be expressed as the following loop:
do {
cin >> n;
cout << n * n << '\n';
}
while (n != 0);
 Unlike the while loop, the do loop is never used in situations
where it would have a null body.
 Although a do loop with a null body would be equivalent to a
similar while loop, the latter is always preferred for its superior
readability.
3/18/2022 40
Cont…

#include<iostream>
int main() {
int n;
do {
cout<<"Enter the number "<<endl;
cin >> n;
cout << n * n << “\n”;
}
while (n != 0);
cout<<"End of the loop excuted!!!";
return 0;
}
3/18/2022 41
Cont …
#include<iostream.h>
int main() {
int counter=0; while(counter<n);
int sum=0; cout<<"the sum of the
int n;
number is"<<" "<<sum;
cout<<"enter the required number"<<" ";
cin>>n; cout<<"end of the do
do while loop";
{ return 0;
sum=sum + counter;
}
counter=counter+1;
}

3/18/2022 42
D. Nested Looping Statements

 Many applications require nesting of the loop statements, allowing


on loop statement to be surrounded with in another loop statement.

 Nesting can be defined as the method of embedding one control


structure with in another control structure.

 While making control structures to be reside one with in another,


the inner and outer control structures may be of the same type or
may not be of same type.

 But, it is essential for us to ensure that one control structure is


completely embedded within another.

3/18/2022 43

Cont
#include<iostream>
int main()
{
int i;
int j; Output
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
55555
{ 4444
cout<<i; 333
} 22
cout<<endl; 1
}
return 0;
}

3/18/2022 44
Loop Summary

while loop: Repeats a statement or group of statements while a given


condition is true. It tests the condition before executing the loop body.

for loop: Execute a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

do...while loop: Like a while statement, except that it tests the condition
at the end of the loop body

nested loops: a way of using one or more loop inside any another while,
for or do…while loop.

3/18/2022 45
Cont …
#include <iostream.h>

void main ()

int x, answer;

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

{ cout << "Question " << x << endl;

cout << "What is the answer to " << 2*x

<< " + " << (30 - x) << " ? : ";

do

cin >> answer;

if (answer == 2*x + 30 - x)

cout << "Correct!" << endl;

else

cout << "No, try again!" << endl;

while (answer != 2*x + 30 - x);

3/18/2022 46
Jumping Statements
 Jump statements are used to divert the execution path to another part
of the program.
 Jump statements cause an unconditional jump to another statement elsewhere in

the code.

 They are used primarily to interrupt switch statements and loops.

 The jump statements are the goto statement, the continue statement,
the break statement, and the return statement.

3/18/2022 47
A. Break Statement
 Using break we can leave a loop even if the condition for its end is not fulfilled.

 It can be used to end an infinite loop, or to force it to end before its natural end.

// break loop example cout << "countdown aborted!";


#include <iostream> break;
int main () }
{ }
int n; return 0;
for (n=10; n>0; n--) }
{
cout << n << ", ";
if (n==3) 10, 9, 8, 7, 6, 5, 4, 3,countdown aborted!
{
48
Cont…
When used in a for, while, do-while or switch structures

 Causes immediate exit from the structure,

 Program execution continues with the first statement


after the structure.

 Commonly used to escape early from a loop, or skip the


remainder of a switch structure.

3/18/2022 49
B. Continue Statement
 The continue statement terminates the current iteration of a loop and
instead jumps to the next iteration.
 For example, we are going to skip the number 5 in our countdown:

// continue loop example

#include <iostream>
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue; 10, 9, 8, 7, 6, 4, 3, 2, 1,FIRE!
cout << n << ", ";
}
cout << "FIRE!\n";

return 0; }
50
C. goto statement
 goto allows to make an absolute jump to another point in the program.

 You should use this feature with caution since its execution causes an
unconditional jump ignoring any type of nesting limitations.

 The destination point is identified by a label, which is then used as an


argument for the goto statement.

 A label is made of a valid identifier followed by a colon (:).

 Generally speaking, this instruction has no concrete use in structured or


object oriented programming aside from those that low-level
programming fans may find for it.

3/18/2022 51
//goto example

Cont
#include<iostream.h>
void main() {
cout << "\nStatement 1.";
cout << "\nStatement 2."; Output
cout << "\nStatement 3."; Statement 1.
Statement 2.
goto last; Statement 3. End of
cout << "\nStatement 4."; Program.

cout << "\nStatement 5.";


last:
cout << "\nEnd of Program.";
return 0;
}
3/18/2022 52

Cont
// goto loop
example
#include
<iostream.h>
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0)
goto loop;
cout << "FIRE!\n";
return 0;
}
3/18/2022 53
Cont …
#include <iostream.h>
int main () { // Local variable declaration:
int a = 1;
// do loop execution
LOOP: value of a:1
do { value of a:3
if( a == 2) { // skip the iteration. value of a:4
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
}
while( a < 5);
return 0;
}
3/18/2022 54
Chaw
See u next class!!!
3/18/2022 55

You might also like