0% found this document useful (0 votes)
8 views9 pages

Understanding For Loops in C++

Uploaded by

aroojsagir
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)
8 views9 pages

Understanding For Loops in C++

Uploaded by

aroojsagir
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

LESSON 9

1. For Statement:
General Form of For statement:
for ( initialization ; continuation condition ; update )
statement1 ;
for ( initialization ; continuation condition ; update )
{
statement1 ;
statement2 ;
:
}

Example1: for ( i = 0; i < 10; i ++ ) Output:


cout << i; 0 1 2 3 4 5 6 7 8 9

Example2: for ( i = 0; i < 10; i += 2 ) Output: even numbers only


cout << i; 0 2 4 6 8

Example3: for ( i = 1; i < 10; i += 2 ) Output: odd numbers only


cout << i; 1 3 5 7 9

Example:

- Write a C++ program to add the numbers between 1 and 100:


#include<iostream.h> void
main( )
{
int sum = 0;
for ( int i = 1; i <= 100; i ++ )
sum = sum + i;
cout << “sum is: “ << sum;
}

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:

- Write a C++ program to print the following series: 1, 2, 4, 8, 16, 32, 64


#include<iostream.h>
void main( )
{
int x;
for ( x = 1; x < 65; x *= 2 )
cout << x <<” “;
}

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;
}

2. More about For Statement:


1-We can use more than one control with for statement, as follow:
for ( int m = 1, int n = 8 ; m < n ; m ++ , n -- )

2-We can create infinite loop, as follow:


for ( ; ; )

3
LESSON 9

3. Nested For Loops:

A loop inside another loop is called a nested loop. The number of


loops depend on the complexity of a problem. Suppose, a loop, outer
loop, running n number of times consists of another loop ins ide it,
inner loop, running m number of times. Then, for each execution of
the outer loop from 1...n, the inner loop runs maximum of m times.
We can put loops one inside another to solve a certain
programming problems. Loops may be nested as follows:

for (initialization ; continuation condition ; update)


{
for (initialization ; continuation condition ; update )
{
statement(s);
}
statement(s); // you can put more statements.
}
Or as the following figure:

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

Let's take a look at a trace of two nested loops.

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;

for(i=0; i<=5; i++)


{

for( j=0; j <= 5; j++)


{
cout << i << j <<" \t";
}

cout <<"\n";
}

return 0;
}

6
LESSON 9

Example:

- Write a C++ program to print the following pattern.


1
12
123
1234
12345

#include <iostream>
int main()
{
int i,j;
for (i =1; i<5; i++)
{

for (j=1; j <= i; j++ )


{
cout <<j<<" ";
}
cout << endl;
}
getch();
return 0;
}

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:

- What is the output of the following C++ program?

#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“;
}
}

Common questions

Powered by AI

In the for statement, the initialization sets up the starting condition (e.g., 'int i = 0'), the continuation condition determines how long the loop will run (e.g., 'i < 10'), and the update adjusts the loop variable (e.g., 'i++'). This sequence allows iterative processing, like printing numbers from 0 to 9 using 'for (i = 0; i < 10; i++) cout << i;' where the loop iterates while 'i' is less than 10, incrementing 'i' by one each loop .

To output a geometric sequence like powers of two, start with the multiplier (e.g., 'int x = 1') and use a for loop multiplying 'x' by the sequence base (2 in this case) each iteration. The loop 'for (x = 1; x < 65; x *= 2) cout << x << " ";' outputs 1, 2, 4, 8, 16, 32, 64, demonstrating the power increment in each iteration .

Nested loops are used to perform repeated actions within each iteration of an outer loop. For example, in generating the pattern with coordinates (e.g., '00 01 02 ...'), the outer loop sets rows while the inner loop sets columns for each row, allowing comprehensive traversal of a grid structure with output based on both loop variables .

To calculate the factorial of a number 'n', initialize a variable (e.g., 'f = 1') to hold the product. Use a for loop starting from 2 up to 'n', multiplying 'f' by the loop variable 'i' in each iteration: 'for (int i = 2; i <= n; i++) f *= i;' This accumulates the product of all integers from 2 to 'n', giving 'n!' as required .

For loops in C++ control both horizontal and vertical repetition to generate visual patterns. In grid formation, nested loops dictate positions and separators (e.g., 'cout << i << j << "\t";'). Variations like triangles adjust inner loops based on outer loop counters, creating structures where each row's length or character count is a function of its index .

To produce a series of even numbers, we modify the update part of the for loop to increment by 2 (e.g., 'i += 2'). An example from the document uses 'for (i = 0; i < 10; i += 2) cout << i;' which outputs 0, 2, 4, 6, 8 by starting at 0 and increasing by 2 each iteration .

Nested for loops can print patterns by varying the range of iterations. For triangular patterns, an outer loop controls rows while an inner loop controls the number of elements per row, as shown with 'for (i = 1; i < 5; i++) for (j = 1; j <= i; j++) cout << j << " ";' producing a growing count each new line .

An infinite loop using the for statement omits all three components: 'for (;;)', meaning it has no initialization, condition, or update directly specified. This setup causes the loop to repeat indefinitely, useful for tasks requiring constant operation until an external condition ends the loop .

Using multiple initializations and updates in a for loop allows synchronized control over multiple variables. For example, 'for (int m = 1, n = 8; m < n; m++, n--)' initializes and separately updates two variables in tandem, useful for tasks like reverse iterating over a sequence in parallel with a forward iteration .

To sum only positive numbers from user input, use a for loop to take inputs, checking if each number is positive before adding it to a cumulative sum variable. The code effectively uses 'if (num > 0) sum += num;' within the loop to filter and aggregate only positive numbers .

You might also like