Professional Documents
Culture Documents
htm
C++ programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail. LoopType Description Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
while loop
for loop
do...while loop
Like a while statement, except that it tests the condition at the end of the loop body You can use one or more loop inside any another while, for or do..while loop.
nested loops
break statement
continue statement
goto statement
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the for(;;) construct to signify an infinite loop. NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.
A while loop statement repeatedly executes a target statement as long as a given condition is true.
Syntax:
The syntax of a while loop in C++ is: while(condition) { statement(s); Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.
Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
#include <iostream> using namespace std; int main () { "" #ocal varia$le declaration% int a & '!; "" while loop e(ecution while( a < )! ) { cout << "value of a% " << a << endl; a**; return !;
When the above code is compiled and executed, it produces the following result: value value value value value value value value value value of of of of of of of of of of a% a% a% a% a% a% a% a% a% a% '! '' ') '+ ', ''. '/ '0 '1
Syntax:
The syntax of a for loop in C++ is: for ( init; condition; increment ) { statement(s);
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
Flow Diagram:
Example:
#include <iostream> using namespace std; int main () { "" for loop e(ecution for( int a & '!; a < )!; a & a * ' ) { cout << "value of a% " << a << endl;
return !;
When the above code is compiled and executed, it produces the following result: value value value value value value value value value value of of of of of of of of of of a% a% a% a% a% a% a% a% a% a% '! '' ') '+ ', ''. '/ '0 '1
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Syntax:
The syntax of a do...while loop in C++ is: do { statement(s); while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.
Flow Diagram:
Example:
#include <iostream> using namespace std; int main () { "" #ocal varia$le declaration% int a & '!; "" do loop e(ecution do { cout << "value of a% " << a << endl; a & a * '; while( a < )! ); return !;
When the above code is compiled and executed, it produces the following result: value value value value value value value value value value of of of of of of of of of of a% a% a% a% a% a% a% a% a% a% '! '' ') '+ ', ''. '/ '0 '1
END ----------------------------------------------------------------------------------------------------------
Types of Loops:There are three types of loops in C++. These are while loop, Do while loop and For loop.
While loop in C++:It allows the program to repeat the collection of the statements enclosed in a body of a loop until the given condition becomes false.
i)imedia Commons
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream.h> #include<conio.h> main() { int a2$; cout<<" 3nput the first printing value %" ; cin>>a; cout<<endl; cout<<"3nput the last printing value %" ; cin>>$; cout<<endl; while(a<&$) { cout<<" The 4rint out value is %"<<a; cout<<endl; a**;
getch();
21 22 23
Explanation:The above program will ta)e the two values from the user. first value will be assigned to /a/ and second value will be assigned to /b/. Then the while loop will come into the action and will chec) the condition if the condition is true then it will print 0a1, after printing 0a1 it will increment the value of 0a1 and the control returned to it. Then it will terminate only if the given condition becomes false otherwise it will continue. The loop which has no terminating condition is called infinite loop.
Do While Loop in C++:It is used when user already does not )now about the number of iterations. In this loop condition is written after the body of a loop. In this the body of a loop is e2ecuted at least once, even if the condition becomes false at the beginning.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include<iostream.h> #include<conio.h> main() { int 52w; char 62 ; do { cout<<"4lease enter the first num$er %" ; cin>>5; cout<<"4lease enter the second num$er %" ; cin>>w; cout<<"7nswer is & " ; cout<<5*w<<endl; cout<<endl; cout<<"89 :ou want to add more num$ers%" ; cin>>6; cout<<endl;
while(6&&;:;); getch();
Explanation:The above program will ta)e input two numbers, First number will be stored in a variable 041 and the second number will be stored in a variable 0w1. Then program will add the both numbers and show the result on the screen. 5fter the result the program will as) user if he wanted to perform the operation again then press 0y1. If the user entered 0y1 then the control move above to the loop and all the statements will again e2ecuted but if the user entered any other character then it will terminate and the program will be close.
For Loop in C++:For loop is )nown as the counter controlled loop. 6nli)e while and do while loop, for loop is given the specified number of iterations, This loop will continue until the ma2imum number of iteration given by the programmer completes or in other words condition becomes false.
Syntax of For Loop:For !starting value3 given Condition3 Increment in a starting value" # Collection of statements !The body" %
Input and Output y usin! For Loop:The code written below provides is an easy e2ample of input and output of a For loop. It will give a good idea of how to use it.
The below written program will ta)e 7 inputs in array named ne" with the help of For loop. 5fter ta)ing the input, another For loop will came into action and print the numbers into the screen which was assigned to array ne"# .
1 2 #include<iostream.h> 3 #include<conio.h> 4 5 main() 6 { int 52w; 7 int new'<-=; 8 9 for(5&!;5<-;5**) 10 { 11 cout<<">nter a random num$er %"; cin>>new'<5=; 12 13 cout<<endl; 14 15 for(w&!;w<-;w**) 16 { 17 cout<< "?our entered num$ers are % "; cout<<new'<w=; 18 cout<<endl; 19 20 21 getch(); 22 23 24 Example of a For Loop:8ere we will modify the code of an above program of a while loop to wor) for a For Loop. Explanation:The below program will ta)e the two values from the user. first value will be assigned to /9/ and second value will be assigned to /)/. Then, In a For loop the value of /9/ is assigned to the variable 0m1 and the value of 0m1 is lesser than the value of 0)1 which shows that condition is true. Therefore the control will transfer within the body of a Loop, program will output the value of 0m1 then it will increment it and the control will again transfer and the condition will chec) again this process will continue until the condition will be true else it will be terminate and the control moves out from the loop. .
#include<iostream.h>
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<conio.h> main() { long @2A; cout<<"3nput the first printing value %" ; cin>>@; cout<<"3nput the last printing value %" ; cin>>A; cout<<endl; for(int m&a ; m<&$ ; m**) { cout<<" The 4rint out value is %"<<m; cout<<endl;
getch();
END -----------------------------------------------------------------------------------------------
e"ecute the same cout statement ten times. There are three basic types of loops which are# for loop while loop
do while loop
#include<iostream> using namespace std; int main() { int i; for (i & !; i < '!; i**) { cout << "Cello" << "\n"; cout << "There" << "\n"; return !;
Note: % single instruction can be placed behind the for loop without the curly brackets.
$ets look at the for loop from the e"ample# &e first start by setting the !ariable i to '. This is where we start to count. Then we say that the for loop must run if the counter i is smaller then ten. $ast we say that e!ery cycle i must be increased by one (i++). In the e"ample we used i++ which is the same as using i * i + +. This is called incrementing. The instruction i++ adds + to i. If you want to subtract + from i you can use i,. It is also possible to use ++i or -i. The difference is is that with ++i the one is added before the for loop tests if i . +'. &ith i++ the one is added after the test i . +'.
#include<iostream> using namespace std; int main() { int counter2 howmuch; cin >> howmuch; counter & !; while ( counter < howmuch) { counter**; cout << counter << ;\n;; return !;
$ets take a look at the e"ample# First you must always initiali1e the counter before the while loop starts ( counter * +). Then the while loop will run if the !ariable counter is smaller then the !ariable howmuch . If the input is ten, then + through +' will be printed on the screen. % last thing you ha!e to remember is to increment the counter inside the loop (counter++). If you forget this the loop becomes infiniti!e.
do { do something;
while (e(pression);
2o something first and then test if we ha!e to continue. The result is that the loop always runs once. (3ecause the e"pression test comes afterward). Take a look at an e"ample#
#include <iostream> using namespace std; int main() { int counter2 howmuch; cin >> howmuch; counter & !; do { counter**; cout << counter << ;\n;; while ( counter < howmuch); return !;
#include <iostream> using namespace std; int main() { int i; i & !; while ( i < )! ) { i**; cout << "Cello\n"; if ( i && '!) $reaA; return !;
In the e"ample abo!e, the while loop will run, as long i is smaller then twenty. In the while loop there is an if statement that states that if i e4uals ten the while loop must stop (break). The result is that only ten 0ello will be printed. &ith continue5 it is possible to skip the rest of the commands in the current loop and start from the top again. (the loop !ariable must still be incremented). Take a look at the e"ample below#
#include <iostream> using namespace std; int main() { int i; i & !; while ( i < )! ) { i**; continue; cout << "Cello\n"; if ( i && '!) $reaA; return !;
In the e"ample abo!e, the cout function is ne!er called because of the continue5 .
END -----------------------------------------------------------------------------------------------
Definition:
*n C++ a for loop is a pro'rammin' lan'ua'e statement which allows co+e to ,e repeate+ly e$ecu loop is classifie+ as an iteration statement.
Syntax:
for ( varia$le initiali6ation; condition; varia$le increment"assignment ) { Dode to e(ecute while the condition is true
Example Program
"E >(ample 4rogram For for #oop 3n D** little drops G thi:agaraa@.com
Doded H:%TC3?7I7J77K L4
E"
#include<iostream> #include<conio.h>
int main() {
""for #oop HlocA for (int counter & '; counter <& a; counter**) { cout<<">(ecute "<<counter<<" time"<<endl;
Sample O tp t:
Enter the Num,er :.
E$ecute ! time E$ecute " time E$ecute % time E$ecute ( time E$ecute . time
Definition
*n C++ a while loop is a control flow statement that allows co+e to ,e e$ecute+ repeate+ly ,ase+ ,oolean con+ition. 0he while loop can ,e thou'ht of as a repeatin' if statement.
Syntax
while ( condition ) { Dode to e(ecute while the condition is true
Example Program
"E >(ample 4rogram For Ohile #oop 3n D** little drops G thi:agaraa@.com
Doded H:%TC3?7I7J77K L4
E"
#include<iostream>
#include<conio.h>
int counter & '; ""while #oop HlocA while (counter <& a) { cout<<">(ecute Ohile "<<counter<<" time"<<endl; counter**;
Sample O tp t:
Enter the Num,er :( E$ecute 1hile ! time E$ecute 1hile " time E$ecute 1hile % time E$ecute 1hile ( time
Definition
*n C++ a +o while loop sometimes 2ust calle+ a +o loop is a control flow statement that allows co e$ecute+ repeate+ly ,ase+ on a 'i/en 3oolean con+ition.
Syntax
do { Dode to e(ecute while the condition is true while ( condition );
Example Program
"E >(ample 4rogram For 8o..Ohile 3n D** little drops G thi:agaraa@.com
Doded H:%TC3?7I7J77K L4
E"
#include<iostream> #include<conio.h>
int counter & '; ""8o while #oop HlocA do { cout<<">(ecute 8o Ohile "<<counter<<" time"<<endl;
Sample O tp t
Enter the Num,er :4 E$ecute Do 1hile ! time E$ecute Do 1hile " time E$ecute Do 1hile % time E$ecute Do 1hile ( time E$ecute Do 1hile . time E$ecute Do 1hile 4 time
END -----------------------------------------------------------------------------------------------