0% found this document useful (0 votes)
87 views62 pages

Chapter 3 C++++++++++++++++++

The document discusses control flow statements in programming languages. It describes three basic structures: sequence, selection, and looping. Selection statements include conditional/branching statements like if-else statements and switch statements. If-else statements allow different code blocks to execute based on a condition being true or false. Switch statements allow different code blocks to execute based on the value of an expression. The document provides examples and explanations of one-way if statements, multi-way if-else statements, nested if statements, and the switch statement.

Uploaded by

Yesuph Ebabu
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)
87 views62 pages

Chapter 3 C++++++++++++++++++

The document discusses control flow statements in programming languages. It describes three basic structures: sequence, selection, and looping. Selection statements include conditional/branching statements like if-else statements and switch statements. If-else statements allow different code blocks to execute based on a condition being true or false. Switch statements allow different code blocks to execute based on the value of an expression. The document provides examples and explanations of one-way if statements, multi-way if-else statements, nested if statements, and the switch statement.

Uploaded by

Yesuph Ebabu
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/ 62

CHAPTER 3

CONTROL STATEMENTS
CONTROL OF FLOW

Ø A flow control statement can cause a change in the


subsequent controls of flow to differ from the natural
sequential order in which the instructions are listed.
 Flow control roughly categorized into 3. These are:
1. Conditional/Branching/selection statements
2. Iteration/Looping/Repetition statements
3. Jumping statements
THE 3 BASIC STRUCTURES IN PROGRAMMING LANGUAGES

 Sequence o Selection
 Programs executed
• Programs executed
sequentially by default
dependent on a
… ...
condition being
satisfied.

Statement 1
True False
Condition?

Statement 2
Statement A Statement B
… ...
BASIC STRUCTURES IN PROGRAMMING LANGUAGES (2)

 Loop

True
Condition? Statement

False
Statement

True
Condition?

False
1. CONDITIONAL OR SELECTION STATEMENTS

 The program can decide which statements to execute


based on a condition.

 C++ provides several types of selection statements:


1. one-way if statements,
2. two-way if-else statements,
3. nested if and multi-way if-else statements,
4. switch statements, and
5. conditional expressions.
1.1. THE ONE-WAY IF
STATEMENT
§ The syntax for a one-way if statement is shown
here:

if (Boolean_expression)
{
statement(s);
}

§ It executes an action if and only if the condition is true.


CONTINUED

 If the boolean-expression evaluates to true, the statements in


the block are executed.
#include<iostream.h>
int main()
{
int grade;
cout<<“Enter the student grade: ”;
cin>>grade;
if ( grade >= 50 )
cout << “\n Passed“;
return 0;
}
 The braces can be omitted if they enclose a single statement.
 E.g.,
if (i > 0)
cout << "i is positive" << endl;
EXAMPLE

 Write a program that prompts the user to enter


an integer. If the number is a multiple of 5,
display Hello Five. Also, if the number is even,
display Hello Even.
Ans. #include <iostream>
using namespace std;
int main() { int number;
cout << "Enter an integer: ";
cin >> number;
if (number % 5 == 0) cout << "Hello Five!" <<
endl;
if (number % 2 == 0) cout << "Hello Even!" <<
endl;
return 0;
}
1.2. TWO-WAY IF-ELSE
STATEMENT

§ An if-else statement decides which statements to


execute based on if the condition is true or false.
Flowchart
if (Boolean_expression)
{
statement(s);
Syntax

}
else
{
statement(s);
}
EXAMPLE

#include<iostream.h>
int main()
{
int grade;
cout<<“Enter the student grade: ”;
cin>>grade;
if ( grade >= 50 )
cout << “\n Passed“;
else
cout << “\n Failed“;
return 0;
}
// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else
{
cout << "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}
1.2.1. THE MULTI-WAY IF-ELSE
STATEMENT
The syntax of the if...else if...else statement is:
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}

• This style, called multi-way if-else statements,


avoids deep indentation and makes the
program easy to read.
EXAMPLE
#include<iostream.h>
int main()
{
int grade;
cout<<“Enter the student grade: ”;
cin>>grade;
if ( grade >= 90 )
cout << “\n You Get Grade A “;
else if ( grade >= 80 )
cout << “\n You Get Grade B “;
else if ( grade >= 70 )
cout << “\n You Get Grade C “;
else if ( grade >= 60 )
cout << “\n You Get Grade D “;
else
{
cout << “\n You Get Grade F“;

}
return 0;
}
1.3 NESTED IF STATEMENT
 An if statement can be inside another if
statement to form a nested if statement.
 Its syntax is:
// outer if statement
if (condition1)
{
// statements
// inner if statement
if (condition2)
{
// statements
}
}
NESTED IF STATEMENT

if (i > k)
{
if (j > k)
cout << "i and j are greater than k" <<
endl;
}
else
cout << "i is less than or equal to k" <<
endl;

The if (j > k) statement is nested inside the if (i > k).


The nested if statement can be used to implement
multiple alternatives.
// C++ PROGRAM TO FIND IF AN INTEGER IS EVEN OR ODD OR NEITHER (0)
// USING NESTED IF STATEMENTS
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
// outer if condition
if (num != 0) {
// inner if condition
if ((num % 2) == 0) {
cout << "The number is even." << endl; }
// inner else condition
else {
cout << "The number is odd." << endl; } }
// outer else condition
else {
cout << "The number is 0 and it is neither even nor odd." << endl;
}
cout << "This line is always printed." << endl;
}
HOME WORK
 Suppose x = 3 and y = 2; show the output, if any,
of the following code. What is the output if x = 3
and y = 4? What is the output if x = 2 and y = 2?
 Draw a flowchart of the code.
if (x > 2) {
if (y > 2) {
int z = x + y;
cout << "z is " << z << endl;
}
}
else
cout << "x is " << x << endl;
1.4. THE SWITCH STATEMENT
THE SWITCH STATEMENT

The switch
switch (condition)
{
case value1:
Statement statement11;
...
 Multiple selection break;
case value2:
structure statement21;
...
 Performs different actions break;
for different test
expression values ...
 Less general than nested case valueN:
if-else statement statementN1;
...
 integer test expression only break;
 test for equality only
default:
statementD;
...
}
THE SWITCH STATEMENT FLOWCHART
(CONT’D)

The switch Statement


switch (expression)
{
(cont’d)
case value1:
statement11;
...
break;  Uses 4 keywords
case value2:
statement21;  switch
...
break;  identifies start of switch
statement
...
 expression in parentheses
case valueN: (switch expression) evaluated
statementN1;
... & its value compared to
break; various alternative (case)
default:
statementD; values within compound
... statement that follows
}
(CONT’D)
switch (expression)
{ The switch Statement (cont’d)
 Uses 4 keywords (cont’d)
case value1:
statement11;
...  Case
break;
case value2:  identifies possible entry points
statement21;
... of switch statement
 comparison done in order in
break;
... which case values are listed
case valueN:  execution begins with
statementN1; statement immediately
...
break; following case value that
default: matched value of switch
statementD;
... expression
}
(CONT’D)
switch (expression)
{ The switch Statement (cont’d)
 Uses 4 keywords (cont’d)
case value1:
statement11;
...  break
break;
case value2:  identifies end of each case & forces
statement21; immediate exit from switch statement
...  once entry point established, no further
break; case evaluations done; all statements
within compound statement executed
... unless break statement is encountered
case valueN:  if omitted, all statements in compound
statementN1; statement following entry point
... (including default case) are executed
break;
default:
statementD;
...
}
(CONT’D)
switch (expression)
{ The switch Statement (cont’d)
 Uses 4 keywords (cont’d)
case value1:
statement11;
...  default
break;
case value2:  identifies default action when
statement21; no match between case value
...
break; & switch expression value
exists
 optional (if switch expression
...
case valueN: value does not match any
statementN1; case value, no statement is
executed unless default is
...
break;
default: encountered)
 invariably placed at bottom
statementD;
...
} of switch statement (by
virtue of its purpose); break
statement not needed for last
E.G. SIMPLE CALC. USING SWITCH
• A switch statement executes statements based on
the value of a variable or an expression.
CONTINUED
#include <iostream>
using namespace std; Ø Commenting Grades using
int main () { switch statement.
char grade = ‘B’;
switch(grade) {
case ‘A’ : cout << “Excellent!” << endl;
break;
case ‘B’ :
case ‘C’ : cout << “V. Good!” << endl;
break;
case ‘D’ : cout << “Poor!” << endl;
break;
case ‘F’ : cout << “Fail!” << endl;
break;
default : cout << “Invalid grade” << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
V. Good!
}
Your grade is B
CONTINUED

• Here is an example which has fall-throughs. Suppose we


want to print the number of days in the nth month of the
year, taking n as the input. Here is the program.
CONTINUED
// A program which identifies the input character is vowel, consonant or space
#include<iostream.h> 
int main()
{
char ch;
cout<<“Enter a character ";
cin>>ch;
switch(ch)
{
case 'a‘: case 'e‘: case 'i': case 'o': case 'u‘: //means if(ch==‘a’ || ch==‘e’ || ch==‘i’ || ch==‘o’ ||
ch==‘u’ )
cout<<"vowel";
break;
case ' ':
cout<<"space";
break;
default:
cout<<"consonant";
break;
}
return 0;
}
NESTED SWITCH STATEMENT
#include <iostream>
using namespace std;
This is outer switch
int main ( )
This is inner switch
{ The value of a is : 100
int a = 100; The value of b is : 200
int b = 200;
switch (a) {
case 100:
cout << "This is outer switch" << endl;
switch (b) {
case 200:
cout << "This is inner switch" << endl;
}
}
cout << "The value of a is : " << a << endl;
cout << "The value of b is : " << b << endl;
return 0;
}
1.5. THE CONDITIONAL EXPRESSIONS

• A conditional expression evaluates an expression based on


a condition.
Syntax: boolean-expression ? expression1 : expression2;

• For example, the following statement assigns 1 to y if x is


greater than 0, and -1 to y if x is less than or equal to 0.

if (x > 0) y = x>
0 ? 1 : -1;
y = 1; Ø You might want to assign a variable
else a value that is restricted by certain
y = -1; conditions.
E.g. int max = (a>b) ? a : b;
QUIZ

 Write a program to accept any character from keyboard


and display whether it is vowel or not.

 Write a program that gives grade based on the following


scale using if else statement:

> 95 –> A+ 70 - 74 –> B


65 - 69 –> B-
85 - 94 –> A
60 - 64 –> C+
80 - 84 –> A-
50 - 59 –> C
75 - 79 –> B+ <50 – F

• Write a program that display greatest of three numbers using


if statement accept input from user.
CONT..

• Write a program that accepts three numbers from


the user and prints "increasing" if the numbers are
in increasing order, "decreasing" if the numbers are
in decreasing order and " Neither increasing nor
decreasing order" otherwise.

• Write a program to calculate sum, average and


check your grade status, if pass or fail.

Hint: accept at least three course marks then


calculate the total, and average of your mark, the
status will be based on average value. Display the
total mark, average and status.
2. ITERATION OR LOOPING STATEMENTS

 it is required to repeatedly evaluate a statement or


a whole block of statements with
increment/decrement of some data in order to
arrive at a result.
 Repeated evaluation of statements is called
iteration and recursion. However, iteration is about
looping. 1. for statements, and
 C++ provides several 2. while statements,
types of iteration 3. do … while statements,
statements:
2.1. THE FOR LOOP
• The for loop iterates a section of C++ code for a fixed number
of times
• The for loop runs as long as the test condition is true.
for ( init; cond; inc /dec ) {
statement;
}
CONT’D

The for Statement


 Problem: print numbers 1 through 10 on
standard output
 Solution using for statement

#include <iostream.h>
int main()
{
int counter;
for (counter = 1; counter <= 10; counter++)
cout << counter << endl;
return(0);
}
(CONT’D)

The for Statement (cont’d)


control limiting value of
variable control variable

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

for initial value of updating


keyword control variable control variable
Example: This code displays even numbers from 0 to 100:

#include<iostream>
using namespace std;
int main(){
for (int i=1;i<=100;i++){
if(i %2==0){
cout<<i <<endl;
}
}
}
2.2. THE WHILE LOOP
Syntax: while (conditional expression)
statements;
Ø This implies the statement following it will be carried out as
long as the conditional expression evaluates true, i.e. it is
more than zero.
E.g. let variables n, i and Sum are declared as integers.
The number n is initialized as 10, Sum as 0 and i as 0.
while (i <= n)
Sum += i++;
cout << “Sum 0 to 10 = ” << Sum <<endl;
Ø The process is repeated again and again till i =10. So Sum
will become 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
Ø After the loop is over, Sum 0 to 10 = 55 will be printed.
(CONT)

 Problem: print numbers 1 upto 10 on standard


output
 Solution using while statement
#include <iostream.h>
int main()
{
int counter;
counter = 1;
while (counter <= 10)
{
cout << counter << endl;
counter++;
}
return 0;
}
(CONT’D)
/*Calculate the average of 5 numbers. */

#include <iostream.h>

int main()
{
float average;
int Number,counter=0,sum=0;
while(counter<5)
{
cout <<“\n Enter the number”;
cin>>Number;
sum=sum+Number;
counter++;
}
average=sum/5;
cout<<“\n The average is:”<<average;
return 0;
}
WHAT WILL BE THE OUTPUT?
counter = 0;
while (counter < 5)
{
cout << "\nI love ice cream!";
counter++;
}

WHAT ABOUT THIS ONE?


counter = 0;
while (counter < 5)
{
cout << "\nI love ice cream!";
}
2.3 THE DO-WHILE STATEMENT

In short: executes body once then


repeatedly executes body while condition remains
true
do keyword do
{
(single statement or body
statement(s);
compound statement)
}
while (condition);

while
keyword condition
(enclosed in must
parenthesis) Have ;
(CONT’D)

 Problem: print numbers 1 through 10 on standard output


 Solution using do-while statement
#include <iostream.h>
int main()
{
int counter;
counter = 1;
do
{
cout << counter << endl; loop body
counter++;
}
while (counter <= 10);
return 0;
}
condition true

false
EX. THE SUM OF ANY NUMBER OF INTEGERS
ENTERED BY THE USER.

int number,sum=0;
char loop_response;
do
{
cout << "\n Enter the number? ";
cin >> number;
sum+=number;
cout << "\nDo you want to do it again? y or
n ";
cin >> loop_response;
} while (loop_response == 'y');
cout<<“\n The sum is :”<<sum;
 // print lowercase alphabet.
char ch = `a';
do
{
cout << ch << ` `;
ch++;
} while ( ch <= `z' );
FLOW OF CONTROL

while versus do-while


#include <iostream.h> #include <iostream.h>

int main() int main()


{ {
int counter; int counter;

counter = 1; counter = 1;
while (counter <= 10) do
{ {
cout << counter << endl; cout << counter << endl;
counter++; counter++;
} } while (counter <= 10);
return(0); return(0);
} }
3. JUMPING STATEMENTS

 Loop control statements or jumping statements


change execution from its normal sequence.
 When execution leaves a scope, all automatic objects
that were created in that scope are destroyed.
 C++ supports the following jumping statements:
1. goto statements,
2. break statements,
3. continue statements, and
3.1. THE GOTO STATEMENT
CONTINUED

• The code goto is used for moving back and forth in


the program. Therefore, for using goto statement
one needs to put in a label.
• Syntax:
EXAMPLE : GOTO STATEMENT AS A
LOOPING
int main(){
int n , m;
cout<<“Write and enter two integers: ” ;
cin>> n >> m;
cout<< “You have written the numbers as n= ”<<n
<<“ and m = ”<<m <<endl;
Again: //The label Again, see colon at end.
if(n < m) n++; else m++;
if(n == m)
cout<<“Now m = ” << m<<“ and n = ” << n<<“\n”;
else
goto Again; //Jump back to Again making a loop
return 0;
}
3.2. THE BREAK STATEMENT

• A break statement may appear inside a loop (while,


do, or for) or a switch statement.
• It causes a jump out of these constructs, and hence
terminates them.
• A break statement only applies to the loop or
switch immediately enclosing it.
• It is an error to use the break statement outside a
loop or a switch.
CONTINUED
#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
return 0;
}
3.3. THE CONTINUE STATEMENT
• continue statement causes the loop to skip the
rest of its body and immediately retest its
condition prior to reiterating.
• For the for loop, continue causes the conditional
test and increment portions of the loop to
execute.
• For the while and do...while loops, program
control passes to the conditional tests.
• It is an error to use the continue statement
outside a loop.
E.G. C++ PROGRAM TO DISPLAY INTEGER FROM 1 TO 10 EXCEPT 6
AND 9.
BREAK VS. CONTINUE
The continue statement works somewhat like the break
statement. Instead of forcing termination, however,
continue forces the next iteration of the loop to take place,
skipping any code in between.
QUIZ

 Write a program that calculates sum of numbers


from 1 to 100.
 Write a program that displays numbers between 0
-100 that are divisible by 2, 3, and 5. The
numbers displayed should be those that can be
divided by 2, 3, and 5 without remainder.
 Write a program that calculates factorial using for
loop, while loop and do while loops. The program
should accept the number and then perform the
calculation of the factorial.
 Write a while loop that prints the average of
numbers from 1 to 10

You might also like