Foor Loop Examples
Foor Loop Examples
1. For Statement:
General Form of For statement:
for ( initialization ; continuation condition ; update )
statement1 ;
for ( initialization ; continuation condition ; update )
{
statement1 ;
statement2 ;
:
}
Example:
1
LESSON 9
Example 2
Example:
- Write a C++ program to find the factorial of n (using for statement):
n! = n * n-1 * n-2 * n-3 * … * 2 * 1
#include<iostream.h>
void main( )
{
int n, f = 1;
cout << “enter positive number: “;
cin >> n;
for ( int i = 2; i <= n; i ++ ) for ( int i = n; i > 2; i -- )
f = f * i;
cout << “factorial is: “ << f;
}
Example
Example 3
- Write a C++ program to solve the following equation:
#include<iostream.h>
void main( )
{
int sum = 0;
for ( int i = 1; i <= 20; i ++ )
sum = sum + ( i * i );
cout << “The sum is: “ << sum;
}
Example:
- Write a C++ program to read 10 integer numbers, and find the sum
of positive number only:
#include<iostream.h>
void main( )
{
int num, sum = 0;
for ( int i = 1; i <= 10; i ++ )
{
cout << “enter your number: “;
cin >> num;
if ( num > 0 ) sum = sum + num;
}
cout << “The sum is: “ << sum;
}
2
LESSON 9
Example:
Example:
- Write C++ program to print the following: 1 10
#include<iostream.h> 2 9
void main( ) 3 8
{ 4 7
int x; 5 6
for ( x = 1; x < 7; ++ x ) 6 5
cout << x <<”\t“ << 11 – x << endl;
}
3
LESSON 9
When working with nested loops, the outer loop changes only after the inner loop
is completely finished.
Example:
for(num2 = 0; num2 <= 3; num2++)
{
for(num1 = 0; num1 <= 2; num1++)
{
cout<< num2<< " " << num1<< endl;
}
}
4
LESSON 9
Example 8
5
LESSON 9
Example:
- Write a C++ program to print the following pattern.
00 01 02 03 04 05
10 11 12 13 14 15
20 21 22 23 24 25
30 31 32 33 34 35
40 41 42 43 44 45
50 51 52 53 54 55
#include <iostream>
int main ()
{
int i, j;
cout <<"\n";
}
return 0;
}
6
LESSON 9
Example:
#include <iostream>
int main()
{
int i,j;
for (i =1; i<5; i++)
{
7
LESSON 9
Example:
- Write a C++ program to print the following pattern by using nested for
loop.
12345678
#include <iostream>
int main()
{
int i, j, k,s=1;
for ( i = 1; i <= 2; i ++ )
{
for ( j = 1; j <= 2; j ++ )
{
for ( k = 1; k <= 2; k ++ )
{
cout << s <<" ";
s=s+1;
}
}
}
8
LESSON 9
Example
- Write a C++ program to print the following pattern.
+
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+ + + + + + +
+ + + + + + + +
+ + + + + + + + +
+ + + + + + + + + +
#include<iostream.h>
void main( )
{
int i, j;
for ( i = 1; i <= 10; i ++ )
{
for ( j = 1; j <= i; j ++ )
cout << “ + “;
cout << “\n“;
}
}
Exercise:
#include<iostream.h>
void main( )
{
int i, j, k;
for ( i = 1; i <= 2; i ++ )
{
for ( j = 1; j <= 3; j ++ )
{
for ( k = 1; k <= 4; k ++ )
cout << “ + “;
cout << “\n“;
}
cout << “\n“;
}
}