Nothing Special   »   [go: up one dir, main page]

Chapter 3 Part - 3

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

Loops and Decisions

Chapter (3)

1
Contents

 The while Loop


 The do Loop (do-while)
 The Nested Loop
 The continue statement
 The break statement
 The exit() function

2
Learning Objectives
 To learn the syntax of “while” loop and “do” loop
 To study the use of loops to execute a set of statements repeatedly until a
particular condition is satisfied
 To know about nested loops where “while” loop contains “do” loop as
well as “do” loop nests “while” loop
 To study how to write the structured program using various loops
 To learn other control statements in addition to decisions and loops
 To study the use of break and continue statements

3
The while Loop
 is used when you don’t know how many
times
 contains a test expression only
 text expression is evaluated at the beginning
of the loop
Test
Test
Syntax: expression
expression
True
True

while(test expression) no semicolon here   


statement; Single statement
Body of Loop
(or) False

while(test expression)
{ Multiple-statement loop Exit
statement; body, block of code
statement;
statement; Figure 1: Operation of the
} while loop
no semicolon here

4
The while Loop (Example-1)
// repeatedly asks the user to enter numbers until ‘0’ is encountered
#include<iostream>
using namespace std;
int main()
{
int n=99; // make sure n isn’t initialized to 0

while(n!=0) // loop until n is 0


{
cout<<"Enter a number : ";
Enter a number : 12
cin>>n; Enter a number : -100
Enter a number : 45
} Enter a number : 0
cout<<endl;
return 0;
}

5
The while Loop (Example-2)
// prints numbers raised to fourth power Table 1. Trace of while loop
#include<iostream> pow numb pow<100 Screen ++num pow=numb*numb*numb*
#include<iomanip> Output numb
using namespace std; 1 1 true 1 1 num=2 pow=16

int main() 16 2 true 2 16 num=3 pow=81


{
81 3 true 3 81 num=4 pow = 256
int pow=1,numb=1;
256 4 false      
// loop while power <= 2 digits
while(pow<100)
{ Output
cout<<setw(2)<<numb;
1 1
cout<<setw(5)<<pow<<endl; 2 16
++numb; 3 81
pow=numb*numb*numb*numb;
}
cout<<endl;
return 0;
}

6
The do Loop (do-while)
 is used when you don’t know how
many times
 the test expression is placed at the end
of the loop
 the loop body is executed at least once Body of Loop

Syntax:
Test
do no semicolon here expression
True

statement;  

while(test_expression);
False
(or)
do { Exit
statement;
semicolon
statement;
statement;
Figure 2: Operation of the do loop
}while(test_expression);

7
The do Loop (do-while)
(Example 1)
//accepts a dividend and a divisor, calculates quotient and remainder until the user stops (y/n)
#include<iostream>
using namespace std; Sample Interaction
int main() Enter dividend: 11
{ Enter divisor: 3
   long   dividend, divisor; Quotient is 3, remainder is 2
Do another? (y/n): y
   char   ch; Enter dividend: 222
    do{ Enter divisor: 17
    cout<<"Enter dividend: "; cin>>dividend; Quotient is 13, remainder is 1
        cout<<"Enter divisor: "; cin>>divisor; Do another? (y/n): n
        cout<<"Quotient is "<<dividend/divisor;
        cout<<", remainder is "<<dividend % divisor;
        cout<<"\nDo another? (y/n): ";
        cin>>ch;
    }while(ch!='n');
   return 0;
}

8
The Nested Loop (Example 2)
// generates a table of multiples of any     i=1;
given number  formatting it 5 columns and     while(i<=10)     // loops for 10 lines
10 lines
Sample   {
Interaction
#include<iostream>         j=1;
#include<iomanip>         do{
            cout<<setw(8)<<num * count;
using namespace std;             count++;
int  main( )             j++;       // increases columns
        }while(j<=5);   // loops for 5 columns
{       cout<<endl;       // moves next column
    int num, i, j, count=1;         i++;                    // increases lines
  }
    cout<<"Enter a number: ";
     return  0;
    cin>>num; }  

9
The continue Statement
take to the top of the loop when
something unexpected happens
Jump back to the top of loop
all subsequent statements in the body  

Test
of the loop are ignored for that condition True
of  
particular loop iteration Loop

Condition
within continue;
False
loop
 

Normal loop return


Exit  

Figure 3: Operation of the continue statement

10
The continue Statement (Example-1)
// demonstrates continue statement

#include <iostream>
using namespace std;
int main()
{
    int i;
    for(i=0;i<10;i++)
  {
        if(i==5)
            continue; Output
Output
        cout<<i<<" "; 0 11 22 33445667788 99
  } End of
End ofthe
theloop
loop
    cout<<"\nEnd of the loop";
    return 0;
}

11
The continue Statement (Example-
2)
// accepts two numbers, if( divisor == 0 )  // if attempt to divide by 0,
/*calculates and displays quotient and     {                 
//remainder repeats the process until user             cout << "Illegal divisor\n";        
enters ‘n’*/             continue;       // go to top of loop
    }
int main()         cout << "Quotient is " << dividend / divisor;
{         cout << ", remainder is " << dividend % divisor;
   long dividend, divisor;
   char ch;         cout << "\nDo another? (y/n): ";
        cin >> ch;
   do { Sample Result:
Enter dividend: 4
        cout << "Enter dividend: ";     } while( ch != 'n' ); Enter divisor: 2
        cin >> dividend; Quotient is 2, remainder is 0
Do another? (y/n): y
    return 0; Enter dividend: 6
        cout << "Enter divisor: "; } Enter divisor: 3
        cin >> divisor; Quotient is 2, remainder is 0
Do another? (y/n): n

12
The break Statement
terminate the loop immediately and
program control resumes at the next
Test
statement following the loop condition True
of   Normal loop
Loop return
terminate a case in the switch statement  
Condition
within
False
using in the nested loops,  
loop

 stop the execution of the


break;
innermost loop and
Jump to the end of loop
 
 start executing the next line of Exit

code after the block Figure 4: Operation of the break


statement

13
The break Statement (Example-1)
// demonstrates break statement

#include <iostream>
using namespace std;
int main()
{
int i;
for(i=0; i<10; i++)
{
if(i==5)
break; Output
cout<<i<<" ";
01234
}
cout<<"\nEnd of the loop";
End of the loop
return 0;
}

14
The break Statement (Example-2)
// accepts a positive integer, calculates squares of all integers from 1 to this number
//to stop the program, the user must enter 0 Sample interaction
#include <iostream> Enter a positive integer: 4
1 1
#include<iomanip> // setw() 2 4
using namespace std; 3 9
4 16
int main() Enter a positive integer: 3
1 1
{ 2 4
int num; 3 9
Enter a positive integer: 0
do{ Press any key to continue . . .

cout << "Enter a positive integer: "; cin >> num;


if(num==0) break;
for(int i=1; i<=num; i++)
cout<<setw(5)<<i<<setw(7)<<i*i<< "\n";
}while(num>0);
return 0;
}

15
The exit() function

 Causes the C++ program to terminate


 The value supplied as an argument to exit is returned to the operating
system as the program’s exit code
 A return code of zero means that the program completed successfully
 it is different from the return statement in that return will not cause
the program to terminate if it is returning from a function other than
main( )

16
The exit() Function (Example)
// demonstrates exit( ) function
#include <iostream>
using namespace std;
int main()
{
int i;
for(i=0; i<10; i++)
{
if(i==5)
exit(0);
cout<<i<<" "; Output
} 01234
cout<<"\nEnd of the loop";
return 0;
}

17
Summary
In this lecture, you will learn:
 The while loop repeatedly processes a block of code as long as a specified condition is true
and tests the condition before executing the loop body.
 The do-while loop will execute the code block once before checking if the condition is true,
then it will repeat the loop as long as the condition is true.
The loop can be nested in another loops.
Whenever a continue statement is encountered inside a loop,
 control directly jumps to the beginning of the loop for next iteration, skipping the execution of
statements inside loop’s body for the current iteration
The break statement
 can also be used to jump out of a loop and terminates the loop or switch statement
 transfers execution to the statement immediately following the loop or switch
The exit() function
 causes the C++ program to terminate

18
Reading Assignments
1. Chapter(3) - Precedence: Arithmetic and Relational Operators (page. page. 96-97)
Reference book : “Object-Oriented Programming in C++” by Robert Lafore, 4 th Edition
Download link:
https://docs.google.com/file/d/0B21HoBq6u9TsUHhqS3JIUmFuamc/view
2. Continue Statement in C++ with example (beginnersbook.com)
Reference link : https://beginnersbook.com/2017/08/cpp-continue-statement/
3. Break statement in C++ with example (beginnersbook.com)
Reference link : https://beginnersbook.com/2017/08/cpp-break-statement/

19
Thank You!

20

You might also like