Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Chapter4 Control Flow Structure - Cs

The document discusses different types of control flow statements in C++ programming. It covers three types: sequential statements which execute code in written order; selection statements which include if, if-else and if-else if to make decisions based on conditions; and repetition statements which execute a block of code multiple times. Specifically, it provides details on the syntax and usage of if, if-else and if-else if statements, and explains how to write nested if statements and switch statements.

Uploaded by

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

Chapter4 Control Flow Structure - Cs

The document discusses different types of control flow statements in C++ programming. It covers three types: sequential statements which execute code in written order; selection statements which include if, if-else and if-else if to make decisions based on conditions; and repetition statements which execute a block of code multiple times. Specifically, it provides details on the syntax and usage of if, if-else and if-else if statements, and explains how to write nested if statements and switch statements.

Uploaded by

kemal Beriso
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Oromia State University

College of Science and Technology


Department of IT

Fundamentals of Programming

Chapter 4: Control Flow Statements (Selection and Repetition


Statements
Lecture Note
Introduction
• Control structure refers to the way c++ statements are
executed while a program runs.
• In some case statements are executed one after the other
(sequential) or in some cases certain part of a program
skipped or jumped based up on the result of a condition.
• The order in which statements are executed is called flow
control .

• There are three types of control flow structure.


• A) Sequential
• B) Conditional branching (decision making or Selection
Statements )
• C) Repetition statements (Looping ) or iteration
A)Sequence

Sequential statements are statements that are executed one after


the other in the order they are written in the source code.
In these kinds of statements the flow of control is said to be
sequential.
Eg. void main ()
{
float number1, number2, number3;
cin>>number1;
number2=number1*10;
number3=number2*number2;
cout<<number2<<number3;
}
B) Conditional branching (decision making or
Selection Statements )
• Conditional statements are mainly used for making decision.
Depending on the value of an expression decision can be
made.
• In conditional branching a statement or block of statement
are executed if and only if a condition evaluates to be true,
otherwise those statements will be skipped or jumped.
• A program where there are points at which the program will
decide at runtime whether some part of the code should or
should not be executed are called Selection statements.
• There are two types of selection statements in C++, which
are the “if statement” and the “switch statement”
cont..
• There are three c++ key words used for this
purpose.
• The different forms of the “If” statement are:
The simple if statement
The If else statement
The if else if statement
lf statement
• The if statement is the simplest of the decision statement.
• General Syntax:
if (expression)
Body of if;
 Expression is evaluated first if this true then body of if is
executed if the expression is false then the body of if is
skipped, and execution continues with the next
statement.
 Body of if is simple statement or block depending on the
programmer requirement i.e. if body of if is simple then
that looks like:
 If (expression)
 Statement;
“if "statement..
 To make multiple statements dependent on the same condition we
can use a compound statement, which will be implemented by
embracing the group of instructions within the left “{“ and right “}”
French bracket.
 If the body of “if” is compound or block then that look like:
If( expression)
{
statement1;
statement2;
statement n; }
If expression is true then all the statements with the block are executed.
In case if the expression is false all the statements within the block are
skipped.
“if "statement..
• E.g1:
if(age>18)
cout<<”you are an adult”;
 E.g2:
if(balance > 0)
{
interest = balance * creditRate;
balance += interest; }
 Most of the time “expression” will have relational expressions testing
whether something is equal, greater, less, or different from something else.
 It should be noted that the output of a relational expression is either True
(represented by anything different from zero) or False (represented by Zero).
 Thus any expression, whose final result is either zero or none zero can be
used in ”expression”
“if "statement..
• Thus, expression and be:
Relational expression,
A variable,
A literal constant, or
Assignment operation, as the final result is whatever
we have at the right hand side and the one at the left
hand side is a variable.
If looks like the follow:
if this true then body of if is executed if the
expression is false then the body of if is skipped.
following diagram show its execution

true
• if(Expre.) • Conditional Statement

false
//Example,If Statement

#include<iostream>
#include<stdlib>
Using namespace std;
Int main()
{
Int x, y;
cout<<“Enter the first number”<<endl;
cin>>x;
cout <<“Enter the second number”<<endl;
cin>>y;
If (x==y)
{
cout<<“the two numbers are equal”<<endl;
exit(0);
}
cout<<“The two numbers are not equal”<<endl;
return 0;
}
The If else statement

• Another form of the “if” is the “if …else” statement. The “if else if”
statement allows us to specify two alternative statements:
One which will be executed if a condition is satisfied and
Another which will be executed if the condition is not satisfied.
• The General Syntax is:
If (expression)
statement1;
else
statement2;
First “expression” is evaluated and if the outcome is none zero (true),
then “statements1” will be executed. Otherwise, which means the
“expression” is false “statements2” will be executed
If else statement..

• Body of if and body of else may be simple and may be


block.
• if body of if and body of else is simple then the structure
looks like:

• If (expression)
Statement;
Else
Statement;
If else statement..
If body of if and else is compound then the structure looks like:
If (expression)
E.g.:
{ if(balance > 0)
statement1; {
statement2; interest = balance *
.Statement n; } creditRate;
else balance += interest;
}
{
else
Statement1; {
Statement2; interest = balance *
Statement n; debitRate;
} balance += interest; }
//write the if else program code below and see the effects
#include<iostream>
#include<conio.h>
Using namespace std;
int main(
{
int testScore;
cout<<”\nEnter your test score:”;
cin>>testScore;
if(testScore<70)
cout<<”\n You did not not pass:”; //then block
else
cout<<”\n You did pass”; //else block
getch();
return 0;

}
If else structure execute like follow:
expression is evaluated first if that is true then the
if body is executed otherwise else body is executed.
following diagram show its execution

true
• if(Expre.) • Conditional Statement

false
• else Statement
The “if else if” statement
• The third form of the “if “statement is the “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.
• The General Syntax is:
if (expression1)
statements1;
else if(expression2)
statements2; .. .
else if(expressionN)
statementsN;
else
statements
The “if else if” statement...
• First the “expression1” is evaluated if the outcome is non zero
(true), then “statements1” will be executed. Otherwise, which
means the “expression1” then “expression2” will be
evaluated:
• if the out put of expression2 is True then “statements2” will
be executed otherwise the next “expression” in the else if
statement will be executed and so on.
• If all the expressions in the “if” and “else if “statements are
false then “statements” under else will be executed.
• The “if…else” and “if…else if” statements are said to be
exclusive selection as if one of the condition (expression) is
satisfied only instructions in its block will be executed and the
rest will be ignored.
Nested if else statement
• In if else statement in place of body we can also
use again if or if else. This concept is known as
nested structure.
– If(a>b) {
• If(a>c)
cout<<“a is the larger value”<<endl;
• Else
cout<<“c is the lager value”<<endl; }
– Else
• If(b>c)
Cout<<“b is largest”<<endl;
• Else
Cout<<“c is lagest”;
The Switch Statement
• Another C++ statement that implements a selection
control flow is the switch statement (multiple-choice
statement).
• 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
The Switch Statement..
Syntax:
• Where Default and Break are switch (<selector expression>)
{
Optional case <label1> : <sequence
of statements>;
• The General Syntax might be: break;
switch(expression) case <label2> : <sequence
of statements>;
{ break;
case <labeln> : <sequence
case constant1: of statements>;
break;
statements; default <sequence ofstatements>;
case constant n: }

.. .
statements;
default:
statements;
The Switch Statement..
Meaning:
• Evaluate selector expression.
• The selector expression can only be: a bool, an
integer, an enum constant, or a char.
• Match case label.
• Execute sequence of statements of matching label.
• If break encountered, go to end of the switch
statement.
• Otherwise continue execution
switch Statement: Example 1

• If you have a 95, what grade will you get?

switch(int(score)/10){
case 10:
case 9: cout << "Grade = A" << endl;
case 8: cout << "Grade = B" << endl;
case 7: cout << "Grade = C" << endl;
case 6: cout << "Grade = D" << endl;
default:cout << "Grade = F" << endl;
}
switch Statement: Example 2
#include <iostream>
using namespace std;
int main()
{ char answer;
cout << "Is comp102 an easy course? (y/n): ";
cin >> answer;

switch (answer){
case 'Y':
case 'y': cout << "I think so too!" << endl;
break;
case 'N':
case 'n': cout << "Are you kidding?" << endl;
break;
default:
cout << "Is that a yes or no?" << endl; }
return 0; }
switch Statement with Multiple Labels:
Example 3
switch (watts) {
case 25 : lifespan = 2500;
break;
case 40 :
case 60 : lifespan = 1000;
break;
case 75 : lifespan = 750;
break;
default :
lifespan = 0;
} // end switch
Points to Remember
• The expression followed by each case label
must be a constant expression.
• No two case labels may have the same value.
• Two case labels may be associated with the
same statements.
• The default label is not required.
• There can be only one default label, and it
is usually last.
C) Repetition statements (Looping ) or iteration
Looping or iterative statement are used when a need arise
to execute a single statement a number of time. For loop
cause a section of our program to be repeated a certain
number of time.

REPETITION is the process of executing a block of


statement until a condition become false.

A statement is executed if a condition is TRUE and will not


be executed if a condition is FALSE.
Continued...
There are three types of looping in c++.
These are:
I. for loop
II. While loop
III. do… while
I. For loop
the for loop is executes block of statements
until a condition become false.
Continued …
It has four parts
initialization expression
Test expression
body
increment/decrement
General syntax
for(initialization;Test/condition;increment/decrimet)
{
block of statement;
}
Continued…
A)initialization:-counter
Refers to the starting point for looping.
initialization is a variable with int/char data type.
Example, int=0; int i=10;
B)condition:- refers to a value or character that should
be composed with the initial point either to run true or
false.
Continued…
The variable that you use in initialization will also
be used in condition. It compares from left to
right.
Example, i<0; , i>0;
C)increment/decrement
Refers to increasing or decreasing of the
counter.
By default, it will increase/decrease by 1. eg. X++
increase x by 1
X– decrease x by 1.
Continued…
Example,
#include<iostream>
using namespace std;
int main()
{
for(int i=0;i<10;i++)
cout<<“Hello C++ world”<<endl;
return 0;
}
Continued…
The for loop execution like the following:
.first the initialization expression executed. The test
expression is checked; if it is false, loop terminate. If this is
true body of loop is executed.
After this assignment assign a new value (that increment
or decrement the variable) to variable. Then again test
expression is checked if false loop terminate otherwise
body of loop again execute.

This process repeat until the test expression become false.


The Diagram for this is as follows

Initialisation

Increment/decrement

Condition body
test true of loop executed
false
//example1
//Write the following program and see the output
#include<iostream>
using namespase std;
int main()
{
for(int i=0;i<10;i++)
cout<<“Hello world”<<endl;
return 0;
}
//example2
//Write the following program and see the output
#include<iostream>
using namespace std;
int main()
{
for(int i=0;i<10;i++)
cout<<i<<endl;
return 0;
}
Note: We can write the following type for loop
For(;;)infinite loop
example1
#include<iostream>
using namespace std;
int main()
{
for(int i=11;i>10;i++)
cout<<i<<endl;
}
From the above for loop type, the statement executes infinite
time. Because there is no condition checked within the for loop
that means we can say that is for loop all the executions are
optional we can skip any one or more if we need, but semicolon is
necessary.
Nested for loop
In C++ any loop can be placed inside other lop one for
loop can be placed inside other loop that is known as
nested for loop.
In the nested loop the inner loop is executed up to end
for a single interaction of outer loop.
//example1
//Write the following program and see the output
#include<iostream>
using namespace std;
int main()
{
for(int i=1;i<=6;i++) {
for(int j=1;j<=i; j++)
cout<<j<<endl; }
return 0; }
While loop
For loop is best if we know fixed number of repetition. But
if we don’t know how many times you want to do
something before you start the loop then the while loop is
used.

General Syntax:
while (condition)
body of while loop
Execution of while loop:
First the condition is evaluated if that is non-zero the body
of loop executed otherwise loop terminates.
After execution of body again condition is checked if it is
false the loop terminated, otherwise the body of loop is
executes. The body of loop is executed again and again up
to when the condition is true.
//exampl1
//Write the following program and see the output
#include<iostream>
using namespace std;
int main()
{
int i;
while(i<=9)
cout<<“i=“<<i;
return 0;}
//Writ a program which reads integer number from
the key board until you don’t give Zero number.
#include<iostream>
using namespace std;
int main()
{
int n=4; // make sure that n is non 0
cout<<“Enter 0 for termination otherwise any number”<<endl;
cout<<endl;
cin>>n;
while(n!=0)
The do ---while statement (loop)
Its functionality is exactly the same as the while loop
except that condition in the do-while is evaluated after
the execution of statement instead of before, granting at
least one execution of statement even if condition is
never fulfilled.
General Syntax
do
statements;
while (expression);
The do ---while loop is similar with a while loop, except
that its body is executed first and then the loop
condition is checked.
// For example, the following program echoes any number you enter until
you enter 0.

//Program that echoer the number


#include <iostream>
using namespace std;
int main () {
unsigned long n;
do {
cout << "Enter number (0 to end): “<<endl;
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
END!!

You might also like