for-loop

Here in this page we will discuss two examples,

print number in ascending and descending order

In this program, we will print number in ascending and descending order,

#include<iostream.h>
#include<conio.h>

void main()
{
   clrscr();
   int num,count;

   cout<<"Enter number: ";
   cin>>num;

   count=num;

  // loop start
   for(int i=1;i<=num;i++)
   {
    cout<<i<<"  "<<count--<<endl;
   }

  getch();
}

In the program, we have declared two variables.

int num,count

Where, input is stored by the user in variable num while the value of variable num is assigned in variable count.

count = num;

suppose user entered value 5 so,

num =5

and

count = 5;

Now after this, the loop starts.

in the loop

for(int i=1;i<=num; i++)
{
  cout<<i<<" "<<count--<<endl;
}

means,

for(int i=1; i<=5; 1++)
{
  cout<<1<<" "<<5--<<endl;
}

this loop will execute like this,

for-loop


execute and terminate a loop manually by given numbers

#include<iostream.h>
#include<conio.h>
void main()
{
  clrscr();
  int first,last;

  cout<<"To set starting point to start counting: ";
  cin>>first;
  cout<<"To set ending point to finish counting : ";
  cin>>second;

  cout<<endl;

  for(int i=first;i<second+1;i++)
    cout<<i<<" "; // body of loop

  cout<<endl;

// print variable s and e values
  cout<<"1st number is "<<first<<endl;
  cout<<"last number is "<<second<<endl;

  getch();
}
OUTPUT:-
TO set starting point to start counting: 5
To set ending point to finish counting : 18

5  6  7  8  9  10  12  13  14  15  16  17  18
1st number is : 5
last number is:18

Calculating total of even and odd numbers

#include<iostream.h>
#include<conio.h>
void main()
{
  clrscr();
  int num,even=0,odd=0;

  cout<<"Enter the last Number: ";
  cin>>num;

  for(int i=0;i<=num;i=i+2)  // for even numbers
  {
    even= even+i; // store even numbers
    cout<<i<<" ";
  }
    cout<<" = "<<even;

    cout<<endl;

   for(int j=1; j<=num; j=j+2)  //for odd numbers
   {
     odd = odd+j;   // store odd numbers
     cout<<j<<" ";
   }
     cout<<" = "<<odd;

  getch();
}
OUTPUT:-
0 2 4 6 8 = 20
1 3 5 7 9 = 25

Generate a table of given number using for loop

#include<iostream.h>
#include<conio.h>

void main()
{
   clrscr();
   int num;

   cout<<"Enter number: ";
   cin>>num;

   for(int i =1; i<=10; i++)
   {
      cout<<num<<" x "<<i<<"\t = "<<num*i<<endl;
   }
   getch();
}
OUTPUT:-

Enter number: 4
 4 x 1   = 4 
 4 x 2   = 8 
 4 x 3   = 12
 4 x 4   = 16
 4 x 5   = 20
 4 x 6   = 24
 4 x 7   = 28
 4 x 8   = 32
 4 x 9   = 36
 4 x 10  = 40