0% found this document useful (0 votes)
28 views48 pages

Chapter 3

This document discusses different types of control statements in programming, including sequence statements, selection statements (if, if-else, switch), and loop statements (for, while, do-while). Sequence statements execute code sequentially line by line. Selection statements like if and switch allow choosing between multiple code blocks based on conditions. Loop statements like for, while, and do-while allow repeating code execution while a condition is true.

Uploaded by

Dagmawe Zewengel
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)
28 views48 pages

Chapter 3

This document discusses different types of control statements in programming, including sequence statements, selection statements (if, if-else, switch), and loop statements (for, while, do-while). Sequence statements execute code sequentially line by line. Selection statements like if and switch allow choosing between multiple code blocks based on conditions. Loop statements like for, while, and do-while allow repeating code execution while a condition is true.

Uploaded by

Dagmawe Zewengel
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/ 48

Chapter 3

Control Statements

1
Outline

 Sequence statements
 Selection statements
 If statements
 If-else statements
 Switch statements
 Loop statements
 For loops
 While loop
 Do-while loop
 Jumping control statements
 Break statements
2
 Continue statements
Introduction

 One of the most important aspects of programming is controlling


which statement will be executed next.
 Control structures / Control statements enable a programmer to
determine the order in which program statements are executed.
 These control structures allow you to do two things:

 Skip some statements while executing others and

 Repeat one or more statements while some condition is true.

 So in programming we have the following four basic control structures


or statements 3
1.Sequential Program Control
In sequential program control, all statements are executed
line by line / one after the other.
Sequential logic is the easiest to construct and follow.
If we have 10 statements, all the 10 statements will be
executed one after the other with out any additional rule.
In sequential statements, the order will be determined
during program development and can not be changed.

4
Sequential Program Control

Statement 1
Start
Area= s*s
Statement 2
Perimeter=4*s
Diagonal= sqrt ((s*s)+(s*s))
Statement 3
End

5
 Write a c++ program to execute the area, perimeter and diagonal of
square?

6
2. Selection Control Statements

 It is used to make a decision about some conditions of your


program's data to determine whether certain statements should be
executed.
 Example: To find the roots of a quadratic equation
 We have three conditions to make a decision:
Condition1: when it has two real roots
Condition2: when it has exactly one real root
Condition3: when it has no real roots
7
Decision Expressions
 A selection-control statement requires an expression that
can be evaluated into a "Yes/No" (or True/False) value.
 A decision expression is a combination of values (either
constants or variables) and operators.
Flow chart to show the Selection of
actions based on conditions: Statement 1

Possibility 1 Possibility 2 Decision


Statement 1 Statement 1
Statement 2a Statement 2b
Statement 3 Statement 3 Statement 2a Statement 2b

Statement 3

8
Selection Statements
 A selection statement provides the means of choosing between two or more
paths of execution.
 There are two general categories:
 Two-way selectors
 Multiple-way selectors
A. Two-Way Selection Statements (IF and IF-ELSE)
I. IF statement:

Start
if (control_expression) --> should be evaluated
statement1
End
 If the control expression is true, statament1 will be executed,
 Otherwise, the program will execute optional statements or exit without
9
doing nothing.
 Example:
if(age>=18)
{
cout<<“You are eligible to vote";
}

II. if-else statement

 In if-else statement, if the given condition is true then it will execute

the statements otherwise it executes the else part statements.


If(condition) --> should be evaluated
{
Statement1 --> executed if the condition is TRUE
}
Else
{
Statement2 --> executed if the condition is FALSE
}
10
Example 1
if(age>=18)
{
cout<<“ you are eligible to vote";
}
Else
{
cout<<“you are Not eligible to vote";
}
Example 2: Write a c++ program that accept numbers from the
user and told the given number is even or odd.

11
 Out put:

12
B. Multiple Selection Constructs

 The multiple selection construct allows the selection of one of any number of
statements or statement groups.
 Using IF-ELSE IF statement
 The “if else if” statement allows us to specify more than two alternative statements
each will be executed based on testing one or more conditions.

 Syntax:
if (condition1) {
statement1;
}
else if(condition2) {
Statement2;
}
else if(condition3) {
Statement3;
{
else {
Statement4;
}
13
Example

if(score >=90)
cout<<“Grade is A”;
else if(score >=80)
cout<<“Grade is B”;
else if(score >=50)
cout<<“Grade is C”;
else
cout<<“Grade is F”;

14
B. Multiple Selection Constructs
 The multiple selection construct allows the selection of one of any
number of statements or statement groups.

 Switch control statements


 The switch statement provides a way of choosing between a set of
alternatives, based on the value of an expression.
 The switch statement has four components:
 Switch

 Case

 Default

 Break
15
Syntax

switch (expression)  constant (int/char/string)


{
case constant_expression_1 :
statement_1;
case constant_expression_2 :
statement_2;
---
---
---
case constant_expression_n :
statement_n;
default:
statement_n+1;
16
}
Example:
switch(colour)
{
case 'R':
cout<<"Red";
case 'W':
cout<<"White";
Case ‘B’:
cout<<“Black”;
default:
cout<<"Wrong choice:";
}
Example1:
17
18
The use of break statement in the switch case statement:

Scenario two

 The break terminates the switch statement by jumping to the very end of it.

19
Effect of break statement

20
Changing switch case statements in to if statements

switch example if-else equivalent


if (x == 1)
switch (x)
{
{
cout << "x is 1";
case 1:
}
cout << "x is 1";
else if (x == 2)
break;
{
case 2:
cout << "x is 2";
cout << "x is 2";
}
break;
else
default:
{
cout << "value of x unknown";
cout << "value of x unknown";
}
}
21
 Nested if/ cascading selection statements
Syntax:
if (condition 1)
{
if(condition a)
{
statement1;
}
else (condition b)
{
Statement2;
}
else
{
Statement4;
22
}
Nesting Selectors

if (age<=18)
if (Gender==female)
{
cout<<“Award chocolate”;
}
else
{
cout<<“Award Ball”;
}
else
{
cout<<“Award Book”;
} 23
3. Repetition Statements/Loops
Repetition statements control a block of code to be
executed repeatedly for a fixed number of times or until a
certain condition fails.
A computer can repeatedly execute the same instructions
over-and-over again without getting bored with the
repetition.
This type of control statement is what makes computers
so valuable.
 There are three C++ repetition statements:
1) The For Statement or loop
2) The While statement or loop
3) The do…while statement or loop 24
A. The for loop/ For statement
 The “for” loop is used to repeatedly execute a
block of instructions until a specific condition
fails.
General Syntax is:
for (expression1 ; expression2 ; expression3)
for(initialization ; condition ; increase/decrease)
statements;

25
 The for loop has three expressions:
 Expression1/initialization: is one or more statements that
will be executed only once and before the looping starts.
 Expression2/condition: is the part that decides whether to
proceed with executing the instructions in the loop or to
stop. Expression2 will be evaluated each time before the
loop continues.
 Expression3/increase or decrease: is one or more
statements that will be executed after each iteration.

26
Example

Output?
#include <iostream>
value of a:0
using namespace std;
value of a:1
int main ()
value of a:2
{
value of a:3
// for loop execution
value of a:4
for( int a = 0; a < 10; a = a + 1 ) {
value of a:5
cout << "value of a: " << a <<‘\n’;
value of a:6
}
value of a:7
return 0;
value of a:8
}
value of a:9

27
Steps of execution of the for loop:

1. Initialization is executed. (will be executed only once)


2. Condition is checked, if it is true the loop continues,
otherwise the loop finishes and statement is skipped.
3. Statement is executed.
4. Finally, whatever is specified in the increase or
decrease field is executed and the loop gets back to
step 2.

28
Example:
Write a program that can print numbers from 10 to 1 using
for loop/ countdown using a for loop
#include<iostream>
Using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
return 0;
}
29
 Even though it is not recommended, expression1, expression2 and
expression3 can be optional or can be ignored.
 This means that they can take NULL statement.
 But making expression2 null means that the loop will not
terminate.
 In such cases one can include an “if” statement inside the “for”
loop which will test a condition and break out from the loop
using the break statement.
 While making one or more of the three expressions null, the semi
colons CAN NOT be ignored.
30
Example:
for(;n>0;) --> only condition expression
for(;n>0;n--) --> when no initialization is need
for(; ;) --> infinite loop unless terminated
with if statements
 When we have composite expressions:
for(n=0, i =100; n!=i; n++, i --)
{
//what ever here
}
 Here, n=0 and i=100 are part of expression1 and will be
executed only once before the loop starts.
 In addition, n++ and i-- will be part of expression3 and
31
Examples:

Example 1: Write a program that adds the


numbers between 0 and n using for loop.

int n;
int sum=0;
for(int i=0; i<=n; i++)
sum=sum+i;
32
int n;
int sum=0;
for(int i = 0 ; i<=n;)
{
sum=sum + i ;
i + =2;
}
The above program that adds the even
numbers between 0 and n using for
loop. 33
 Example 3: Write a program that adds the odd numbers between 0 and n
using for loop where all the three expressions are null.

int main ()
{
int n; int Sum=0; int i=1;
Cout<<“Enter n:”;
cin>>n;
for( ; ; )
{
if(n<=0)
cout<<“Enter only positive numbers”;
else
{
Sum=Sum+i;
i=i+2;
}
};
cout<<"sum="<<sum; 34
 In the above Example3, the initialization is at the top before the
looping starts.
 The condition part is put in the if statement before the instructions
are executed and the increment is found immediately after the
statements to be executed in the loop.
 NB: even though there is the option of making all the three
expressions null in a “for” loop, it is not recommended to make the
condition to take null statement.

35
B. The ‘while’ Statement

 The while statement (also called while loop) provides a way of repeating a

statement while a condition holds.

 It is one of the three flavours of iteration in C++.

 The general form of the while statement is:

while (expression)

statement;

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

 If the outcome is non zero then statement (called the loop body) is executed

and the whole process is repeated. Otherwise, the loop is terminated.


36
Example 1:

Output?
#include <iostream>
using namespace std; value of a:0
int main () value of a:1
{ value of a:2
// Local variable declaration:
int a = 0; value of a:3
// do loop execution value of a:4
while( a < 10 ) value of a:5
{ value of a:6
cout << "value of a: " << a << “\n”; value of a:7
a = a + 1;
} value of a:8
return 0; value of a:9
}

37
 Suppose that we wish to calculate the sum of all numbers
from 1 to some integer value n. this can be expressed as :

 Example 2:// adds the numbers between 0 and any given


number n

i=1;
sum = 0;
while(i <= n)
sum += i++;

38
Example 3:
/*The following while loop will request the user to enter his/her age which should be between 0 and 130. If the user
enters a value which is not in the range, the while loop test the value and request the age again until the user enters a
valid age.*/
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"\n enter your age [between 0 and 130]:";
cin>>age;
while(age < 0 || age > 130)
{
cout<<"\n Invalid age. Plz try again!";
cin>>age;
}
}

39
C. Do…while loop.
The do statement (also called the do loop) is similar to the while statement,
except that its body is executed first and then the loop condition is examined.

40
 In do…while loop, we are sure that the body of the loop will be
executed at lease once even if the condition is not fulfilled. then
the condition will be tested.
The general form is:

 First statement is executed and then expression is valuated.


 If the outcome of the expression is nonzero, then the whole
process is repeated. Otherwise the loop is terminated

41
Example 1:
Output??

#include <iostream>
using namespace std; value of a:0
int main () value of a:1
{
// Local variable declaration: value of a:2
int a = 0; value of a:3
// do loop execution value of a:4
do value of a:5
{ value of a:6
cout << "value of a: " << a << “\n”;
a = a + 1; value of a:7
} value of a:8
while( a < 10 ); value of a:9
return 0;
}

42
Example 2:
//Our previous example in the while loop might be changed as:

#include<iostream>
using namespace std;
int main(){
int age;
cout<<"\n enter your age [between 0 and 130]:";
cin>>age;
do
{
cout<<"\n Invalid age. Plz try again!";
cin>>age;
}
while(age < 0 || age > 130);
} 43
Other Statements

The continue statement


 The continue statement terminates the current iteration of a loop
and instead jumps to the next iteration.
 It is an error to use the continue statement outside a loop.

44
45
The break statement
 Using break we can leave a loop even if the condition for its end is
not fulfilled.

46
Questions?
Thanks !!
47
Exercise
1. Write for, do-while, and while statements to
compute the following sum
1+1/2+1/3+1/4+…1/15

48

You might also like