Introloops Forloop
Introloops Forloop
Programming (CS-102)
Maham Shuja
[email protected]
Programming Structures
Sequential Structure
Selection/Conditional Structure
Examples:
User may display his/ her name for 10 times
Display set of natural numbers from 1 to 10
Counter-Controlled & Sentinel- Controlled Loops
Counter-Controlled Loops
We can determine before loop execution exactly how many loop repetitions will
be needed to solve the problem.
Example: Set of first five natural numbers
for loop
while loop
do - while loop
for loop
for loop executes one or more statements for a specified number of times.
This loop also called counter- controlled loop.
Syntax:
Initialization
It specifies the starting value of counter variable. One or many variables
can be initialized in this part. To initialize many variables, each variable is
separated by comma.
Condition
The condition is given as relational expression. The statement is executed
only if condition is true.
Increment/Decrement
This part specifies the change in counter variable after each execution of
the loop.
Statements:
Instructions that are executed when the condition is true.
Example
Flow Chart
Initialization
Increment/decrement
True
Condition Loop body
False
Example
Write a C++ program that display following output using for loop:
6 4 2 0 -2 -4 -6
i i >= -6 Print
#include<iostream> 6 6 >= -6 6
using namespace std; 4 4 >= -6 4
int main() 2 2 >= -6 2
{ 0 0 >= -6 0
for(int i=6; i >= -6; i = i-2) -2 -2 >= -6 -2
cout << i << ' '; -4 -4 >= -6 -4
return 0; -6 -6 >= -6 -6
-8 -8 >= -6 ----
}
Example
#include<iostream>
using namespace std;
int main()
{
123 is sentinel value
int x;
for(x=0; x != 123; )
{
cout << "Enter a number: "; x x != 123 Print
cin >> x; 0 0 != 123 Enter a number: 12
} 12 12 != 123 Enter a number: 8
cout<<"Exit"; 8 8 != 123 Enter a number: 123
return 0; 123 123 != 123 Exit
}
Output
Example
Write a program to print first ten even numbers using for loop.
#include <iostream>
Using namespace std;
int main()
{
int count;
for (count = 2; count <= 20; count = count +2)
cout<<count<< “ “ ;
return 0;
}
Gary J. Bronson , Program Development and Design using C++, 2nd Edition.
(Chapter 5)