Monday, October 17, 2011

How to print spaces using nested loop in C++

C++ Program:-



#include<iostream.h>
#include<conio.h>
void main(void)
{
clrscr();
for(int num1=1;num1<=10;num1++)
{
for(int num2=1;num2<=num1;num2++)
{
cout<<" ";
}
cout<<num1<<endl;
}

getch();
}

OUTPUT:-

 1
  2
   3
    4
     5
      6
       7
        8
         9
          10

NOTE:-
            In this program as you can see number of spaces in each line is increasing according to the number. lets discus about the logic of this program.
As you can see we use the first loop i.e  for(int num1=1;num1<=10;num1++) In this loop num1 is starting from 1 and ending at point 10 with the increment of 1. We use loop for following three purposes.
  1. For the printing the value of num1 i.e 1 ,2 ,3, 4.............. 10 . For this purpose we can simply use this statement Cout<<num1; so this line will simply print the number that will save to num1 each time. 
  2. For printing new lines 10 time.This can be done using this statement  Cout<<endl; so this line will always take the cursor to the new line with each value of loop.
  3. For printing the spaces that are increasing according to the number means 5 spaces for number 5 and similarly 10 spaces for number 10. This operation is done by using this nested loop.      for(int num2=1;num2<=num1;num2++)
    {
    cout<<" ";
    }                                       This loop is depending on the value of upper loop mean if the value of num1 is 5 then this loop will run 5 time because it is less than equal to num1.

No comments:

Post a Comment