0% found this document useful (0 votes)
3 views10 pages

ProgrammingFundamentals Lab 08

Uploaded by

Learn Easy
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)
3 views10 pages

ProgrammingFundamentals Lab 08

Uploaded by

Learn Easy
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/ 10

IT & Computer Science Department

Pak-Austria Fachhochschule: Institute of Applied Sciences and


Technology, Haripur, Pakistan

Lab # 8: Iteration Structure (While, do and for Loop)

The aims of this lab are to cover some other basics of C programming Loop Structure in detail.

Learning Objectives:
 While Loop
 Do While loop
 For loop

Outcomes:
 Students should be able to use while, do while and for loops.
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Loop
Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of
code is one of the most basic but useful tasks in programming -- many programs or websites that produce
extremely complex output are really only executing a single task many times. Now, think about what this
means: a loop lets you write a very simple statement to produce a significantly greater result simply by
repetition.

1. The while loop


The most basic loop in C is the while loop. A while statement is like a repeating if statement. Like an If
statement, if the test condition is true: the statements get executed. The difference is that after the
statements have been executed, the test condition is checked again. If it is still true the statements get
executed again. This cycle repeats until the test condition evaluates to false.
A while loop is a control flow statement that allows code to be executed repeatedly based on a given
condition. The while consists of a block of code and a condition. The condition is first evaluated and if the
condition is true the code within the block is then executed. This repeats until the condition becomes false

Syntax
Basic syntax of while loop is as follows:
while ( expression )
{
Single statement
or
Block of statements;
}

The expression can be any combination of Boolean statements that are legal. Even, (while x ==5 || v ==
7) which says execute the code while x equals five or while v equals 7.

Flow Chart of While Loop


IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 8.1:
Write a program using while loop who print the values from 10 to 1

#include <iostream>
using namespace std;

int main()
{
int i = 10;

while ( i > 0 )
{
cout<<i;
cout<<”\n”;
i = i -1;
}
system(“pause”);
return 0;
}
}

This will produce following output:


10
9
8
7
6
5
4
3
2
1
Our next example is very simple. It uses a while loop to count from 1 to 10. It does so by incrementing a
variable named counter by 1 in each iteration or cycle. Incrementing a variable means to add something
to it, so that its value is increased.
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example8 .2: Print Numbers from 1 to 10 using a while loop

#include <iostream>
using namespace std;
int main()
{
int counter = 1;
while (counter <= 10)
{
cout<<counter;
cout<<”\n”;
counter++;
}
system(“pause”);
return 0;
}

Our 3rd example is based on a while-loop that keeps on running until a certain condition is reached (a
certain value is entered by the user). That certain value is called the 'sentinel value', 'signal value' or 'flag
value'.
Our program asks the user for an integer value, if that value is not -1, it keeps on running through the
next cycle/iteration.
Example 8.3: Printing the numbers you entered using a while loop
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

#include <iostream>
using namespace std;
int main()
{
int flag; //flag is just an integer variable
cout<<“Enter any number: ( -1 to quit) ”;
cin>>flag;
cout<<“Entering the while loop now...\n”;
while (flag != -1) {
cout<<“Enter any number: ( -1 to quit) ”;
cin>>flag;
cout<<“You entered \n”<<flag;
}
cout<<“Out of loop now”;
system(“pause”);
return 0;
}

The do-while loop


Its format is:
do statement while (condition);
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never fulfilled. For example, the following example program echoes any
number you enter until you enter 0.
Example 8.4

#include <iostream>
using namespace std;

int main ()
{
long n;
do
{cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n"; } while (n != 0);
return 0;
}
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Output:
Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0

For Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
The syntax of a for loop in C++ is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
 The init step is executed first, and only once. This step allows you to declare and initialize any
loop
 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 control variables. You are not required to put a statement here, as long as a
semicolon appears.
 Next, the condition 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:
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

output:
Example 8.5 value of a: 10
value of a: 11
#include <iostream> value of a: 12
using namespace std; value of a: 13
value of a: 14
int main () value of a: 15
{ value of a: 16
// for loop execution value of a: 17
for( int a = 10; a < 20; a = a + 1 ) value of a: 18
{ value of a: 19
cout<< "value of a: " << a <<endl;
}

return 0;
system(“pause”);
}

Example 8.6: Output


#include<iostream>
using namespace std; Loop counter value is 5.
int main() Loop counter value is 10.
{ Loop counter value is 15.
int x; Loop counter value is 20.
for ( x=5; x <= 50; x = x+5 ) Loop counter value is 25.
{ // x = x + 5 could also be written x += 5 Loop counter value is 30.
cout<< "Loop counter value is " << x << ".\n"; Loop counter value is 35.
} Loop counter value is 40.
system ("pause"); Loop counter value is 45.
return 0; Loop counter value is 50.
}

Can you modify the above program that counts from 50 to 5 with decrements of 5?

Nested Loop:
We have seen the advantages of using various methods of iteration, or looping. Now let's take a look at
what happens when we combine looping procedures.
The placing of one loop inside the body of another loop is called nesting. When you "nest" twoloops, the
outer loop takes control of the number of complete repetitions of the inner loop. While all types ofloops
may be nested, the most commonly nested loops are for loops.
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 8.7:
// Rectangle comprised of x's
for (rows = 0; rows < 4; rows++)
{
for (col = 0; col < 12; col++)
{
cout<<'x' ;
}
cout<< "\n";
}

Output of the program is displayed as follows:


xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx

Example 8.8:
// The following program checks if the number entered is a prime number or not
//Use of for loop and if-else statement
#include<iostream>
using namespace std;

int main()
{
long n,j;
cout<<"\n\n Enter the Number to test if it is a prime number ";
cin>>n;
for(j=2;j<=n/2;j++)
{
if(n%j==0)
{ cout<<"\n\n\t It is not a prime number as it is divisible
by"<<j<<endl; break;}
else
{ cout<<endl<< n << " is a Prime number "<<endl;
break; }
}
system("pause");
}
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 8.9:
//missing init statement in For loop
#include<iostream>
using namespace std;
int main()
{
int i = 0;
for( ; i < 10; i++)
cout<<"\n"<< i;
system("pause");
return 0;
}

Note: for (;;) works as an infinite loop.

Which Loop should I use?


 while: the loop must repeat until a certain "condition" is met. If the "condition" is FALSE at the
beginning of the loop, the loop is never executed. The "condition" may be determined by the
user at the keyboard. The "condition" may be a numeric or an alphanumeric entry. This is a
good, solid looping process with applications to numerous situations.
 do-while: operates under the same concept as the while loop except that the do-while will
always execute the body of the loop at least one time. (Do-while is an exit-condition loop -- the
condition is checked at the end of the loop.) This looping process is a good choice when you are
asking a question, whose answer will determine if the loop is repeated.
 for: the loop is repeated a "specific" number of times, determined by the program or the user.
The loop "counts" the number of times the body will be executed. This loop is a good choice
when the number of repetitions is known or can be supplied by the user. The following program
fragments print the numbers 1 - 20. Compare the different looping procedures. Remember,
there are always MANY possible ways to prepare code!

Common Error: If you wish the body of a for loop to be executed, DO NOT put a semicolon after the
for's parentheses. Doing so will cause the for statement to execute only the counting portion of the
loop, creating the illusion of a timing loop. The body of the loop will never be executed.
Semicolons are required inside the parentheses of the for loop. The for loop is the only statement that
requires such semicolon placement.
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 8.10:
do-while:
int ctr = 1; do
{
cout<<ctr++ <<"\n";
}while (ctr<= 20);

for:
int ctr;
for(ctr=1;ctr<=20; ctr++)
{
cout<<ctr<<"\n";}

while:
intctr = 1;
while (ctr< = 20)
{
cout<<ctr++ <<"\n";
}

You might also like