Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27

Loops and Decisions

Chapter (3)

1
Contents
 switch statement
 conditional operator
 Loops
 The "for” Loop
 Three Expressions in the “for” Loop
 Multiple statements in loop body
 for Loop Variations
Objectives
 To learn syntax of switch, and conditional operator
 To know how the length of code and memory space are
reduced using loops
 To understand about “for” loop
switch Statement
 If all the decisions depend on the same variable, consider switch
statement instead of if…else or else if constructions

Syntax: integer or character variable


switch variable True
equals first First case body
case constant
switch (n) no semicolon here  

{ integer or character constant   False

case 1:
statement1; switch variable
equals second
True
Second case body

break; case constant


 
case 2:   False

statement2; ……
break;
………….. False
Default body

default: Exit
statement;
}
no semicolon here Figure 1: Operation of the switch
statement
switch Statement (Example-1)

// accepts a number from user and displays it is even or odd


Memory:
number
int number; 116
cout<<"Enter a number : ";
cin>>number; Screen:
switch(number%2) Enter a number: 116
It is even.
{
case 0: cout<<"It is even."; break;
default : cout<<"It is odd."; // case 1: cout<<"It is odd."; break;
}
switch Statement (Example-2)
// input a number between 1 and 5 (both are inclusive) and displays that number is
boundary or inside or outside number

int num; Sample interaction: 1


cout<<"Enter a number (between 1 and 5): "; Enter a number(between 1 and 5): 5
cin>>num; Boundary number
switch(num)
Sample interaction: 2
{
case 1: Enter a number(between 1 and 5): 2
Inside number
case 5: cout<<"Boundary number"; break;
case 2: Sample interaction: 3
case 3: Enter a number(between 1 and 5): -1
case 4: cout<<"Inside number "; break; Outside number
default : cout<<"Outside number";
}
Conditional Operator (?:)

A variable is given one value if something is true and another


value if it’s false.
Conditional Expression

Syntax:
variable = (test expression) ? expression1 : expression2;

Conditional Operator

if…else statement Equivalent program fragment using conditional operator


if(alpha<beta)
min = alpha; min = (alpha<beta) ? alpha : beta;
else
min = beta;
Conditional Operator (Example-1)
// reads an exam: mark from user and displays the message "Pass" or "Fail"
#include<iostream.h>
using namespace std; Memory:
int main() mark
{
65
int mark;
cout<<"Enter exam mark: ";
cin>>mark; Screen:
Enter exam mark: 65
(mark>49)? cout<<"Pass" : cout<<"Fail";
Pass
return 0;
}
Conditional Operator (Example-2)
Equivalent else…if construction
#include<iostream> if (num == 1)
using namespace  std; cout <<"One";
else if (num == 2)
int main()
cout<<"Two";
{ else if (num==3)
    int num; cout<<"Three";
    cout<<"Enter a positive integer : "; else
    cin>>num; cout<<"Greater than 3";

    (num==1)? cout<<"One": Equivalent switch statement


    (num==2)? cout<<"Two":
    (num==3)? cout<<"Three": switch(num){
    cout<<"Greater than 3"; case 1: cout<<"One"; break;
case 2: cout<<"Two"; break;
    return 0;
case 3: cout<<"Three"; break;
default: cout<<"Greater than 3";
}
Sample interaction: 1 }
Enter a positive integer : 2
Two
Loops
 a section of the program to be repeated a certain number of
times
 the repetition continues while a condition is true
 when the condition becomes false, the loop ends and control passes
to the statements following the loop
 three kinds of loops in C++ are:
 for loop
 while loop
 do loop (do-while)
The for Loop
 executes a section of code a fixed number of times
no semicolon here
Syntax:
for(Initialization expression; Test expression; Increment/Decrement expression)
Single-statement loop body
statement;
(or)

for(Initialization expression; Test expression; Increment/Decrement expression)


{
statement;
Multiple-statement loop
statement; body, block of code
statement;
} no semicolon here
Three Expressions in the for Loop
 Initialization expression
 gives the loop variable an initial
value, executed only once Initialization
expression

 Test expression
 is evaluated each time through the
loop before executing the loop
Test True
 determine whether the loop will expression
be executed again Body of loop

 Increment/Decrement expression False


Increment/Decrement
 change the value of the loop expression

variable, often by incrementing or Exit

decrementing it
 always executed at the end of the Figure 2: Operation of the for loop
loop
For Loop (Example-1)
Table 1: Trace of for loop
// displays the message 5 times Step 1 Step 2 Step 3 Step 4
#include<iostream.h> (Initialization) i (Test)
i<5
(Body of Loop)
 
(Increment)
i++;
using namespace std;
i=0 0 0<5 (true) Introduction to for loop 1
int main()
{ 1 1<5 (true) Introduction to for loop 2
Initialization expression
2 2<5 (true) Introduction to for loop
int i; Test expression
3

3 3<5 (true) Introduction to for loop 4


Increment expression
cout<<“Introduction to for loop\n”; 4 4<5 (true) Introduction to for loop 5
for(i=0; i<5; i++)
cout<<“Introduction to for loop\n”; 5 5<5 (false)    
cout<<“Introduction
cout<<“Introduction to for loop\n”; to for
cout<<“Introduction to for loop\n”;
Output
loop\n”;
Introduction to for loop
return 0; Introduction to for loop
Introduction to for loop
Introduction to for loop
} Introduction to for loop
For Loop (Example-2)
// displays square values of zero to five
Table 2: Trace of the for loop
#include<iostream.h>
int main() Step 3
Step 1 Step 2 Step 4
(Body of
{ (Initialization) j (Test)
Loop)
(Increment)
j<6 j++
int j;  
j=0 0 0<6 (true) 0 1
1 1<6 (true) 1 2
for(j=0; j<6; j++)
2 2<6 (true) 4 3
cout<<j * j<<" "; 3 3<6 (true) 9 4
4 4<6 (true) 16 5
5 5<6 (true) 25 6
cout<<endl;
6 6<6 (false)    
return 0;
Output
} 0 1 4 9 16 25
Multiple statement in loop body (Example 3)

// lists cubes from 1 to 10


#include<iostream>
#include<iomanip>   // setw( ) Output
1 1
using namespace std; 2 8
int main() 3 27
{ 4 64
   int numb; 5 125
6 216
   for(numb=1; numb<=10; numb++) 7 343
   { 8 512
        cout<<setw(4)<<numb; 9 729
        int cube = numb * numb * numb; 10 1000
        cout<<setw(6)<<cube<<endl;
   }
   return 0;
}
For Loop Variations
// calculates factorial value of a given number

factorial value of n = n * (n-1) * (n-2) * … * 3 * 2 * 1


int fact = 1, j;
Example:
for(j = num; j>=1; j--)
factorial value of 5 = 5 * 4* 3 * 2 * 1
fact = fact*j;
20

60

120 fact *= j;

120 factorial value of 5


For Loop Variations (Example 4)
// calculates factorial value of a given number
#include<iostream> Table 3: Trace of the for loop
using namespace std; Step 1 Step 2 Step 3 Step 4

int main() (Initialization) j fact (Test) (Body of Loop) (Decrement)


j=numb; j>0  fact*=j; j--;
{ j=5 5 1 5>0 (true) fact = 1*5 4
  unsigned int numb; 4 5 4>0 (true) fact = 5*4 3

  unsigned long fact=1; 3 20 3>0 (true) fact = 20*3 2


60
  cout<<"Enter a number : "; 2 2>0 (true) fact = 60*2 1
1 120 1>0 (true) fact = 120*1 0
  cin>>numb; 120
0 0>0 (false)

  for(int j=numb; j>0; j--) Output


    fact *= j; Output
Enter a number : 10
  Enter a number : 5
  cout<<"Factorial is "<<fact<<endl; Factorial is 3628800 Factorial is 120
  return 0;
}
Nested for Loop

 A loop can be nested inside of another loop.

Syntax:
for ( Initialization; Test; Increment/Decrement )
{

outer loop
for (Initialization; Test; Increment/Decrement )

Inner loop
{
statement(s);
}
statement(s); // you can put more statements.
}
Nested for Loop (Example-1)

//displays the following pattern:


*****
***** for(int i=0; i<4; i++) *****
***** { *****
***** *****
for(int j=0; j<5; j++)
*****
cout<<"*";
cout<<endl;
}
Nested for Loop (Example-1) (Cont’d)
Table 4: Trace of nested for loop
// demonstrates nested for loop Outer Loop
Variable (i)
Outer Loop Inner Loop Inner Loop Screen
Test (i<4) Variable (j) Test (j<5) Output
#include<iostream> 0 True 0 True *
using namespace std;     1 True **
int main()     2 True ***
    3 True ****
{     4 True *****
int i, j; False
    5 (exit from  
inner loop)
for(i=0;i<4;i++) 1 True 0 True *
{ Outer loop     1 True **
for(j=0;j<5;j++) ***
Inner loop

    2 True
    3 True **** Output
cout<<"*";     4 True *****
: : False *****
 : :  *****
cout<<endl; 5 (exit from
inner loop)
 
*****
} : : : : :
*****
return 0; 4
False
(exit from      
} outer loop)
Nested for Loop (Example-2)

// demonstrates nested for loop *


//displays the following pattern **
***
****

for(int i=0;i<4;i++) i=0, j=0


*
{ i=1, j=0,1

for(int j=0; j<= i; j++) **


i=2, j=0,1,2

cout<<"*"; ***
i=3, j=0,1,2,3

cout<<endl; ****
}
Nested for Loop (Example-3)
  // displays multiplication tables
Output
1*1=1
    int   i,j,k,n; 1*2=2
1*1=1
n 1*3=3
    cout<<"Enter the number of tables : "; 1*2=2
1*3=3
1*4=4
2
    cin>>n; 1*4=4
1*5=5
1*5=5
1*6=6
    for(i=1; i<=n; i++)    //outer loop 1*6=6
1*7=7
1*7=7
1*8=8
  { 1*8=8
1*9=9
1*9=9
1*10=10
        for(j=1; j<=10; j++)    // inner loop 1*10=10

    { 2*1=2
i 2*2=4
          k= i * j ; 2*3=6
i 2*4=8
          cout<< i << "*" << j << "=" << k <<endl; 2*5=10
2*6=12
    } 2*7=14
2*8=16
    cout<<endl; 2*9=18
  } 2*10=20
Multiple Initialization and Test Expressions

 can have more than one expression in the initialization and


increment/decrement expressions separating by commas
 can have only one test expression

#include<iostream>
using namespace std;
int main()
{
Output
int j, a, b=10;
30
Multiple initializations Multiple increments/decrements 29
28
27
26
for( j=0, a=20 ; j<5 ; j++, b-- )
cout<<a+b<<endl;
return 0;
}
Multiple Initialization and Test Expressions)
(Cont’d)
 can leave out some or all of the expressions

 for( ; ; ) same as while loop with a test expression of true

for( ; ; )
cout<<“Hello”;
will print out infinite numbers of “Hello”

int i=0;
for( ; i<5; i++)
cout<<“Hello”; will print out 5 times-
“Hello”

 Should avoid using such multiple or missing expressions which can lead to
decrease its readability
Summary
In this lecture, you will learn:
 switch provides one selection from many alternatives, evaluated and compared to each
case value.
 conditional operator that can be used to replace “if...else” statements.
 Loop is used when you need to execute a block of code several number of times.
 Three types of loops: for, while and do-while loop
 The for loop handles details of the counter-controlled loop that provides a compact way to
iterate over a range of values.
 The general form of the for statement can be expressed by three expressions.
 Nested for loop: a for loop can be nested completely contained within another for loop.
 Multiple initializations and text expressions can be possible.
References

1. Object-Oriented Programming in C++ (Fourth Edition) by Robert Lafore

2. Programming Logic and Design Comprehensive (Sixth Edition) by Joyce

Farrell

3. Data Structures using C++ by Varsah H. Patil

4. C++ Language Tutorial (e-book)

5. C Programming for Engineering & Computer Science by H.H. Tan and T.B.

D’Orazio
Thank You!

27

You might also like