Wednesday, 5 February 2014

A Program Using "While" Loop

Problem:

Write a program to display the following format using while loop:
The format to be printed using while-loop
Print this format using while-loop

Solution:

Here is the code that shows the given format using "while" loop:

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a=1,b=5;
cout<<"---------"<<endl;
cout<<"a\tb"<<endl;
cout<<"---------"<<endl;
while(a<=5)
{
cout<<a<<"\t"<<b<<endl;
a++;
b--;
}
cout<<"---------";
getch();
}

Explanation:


  1. Line 1 & 2, include the header files needed to run the functions inside this program.
  2. Line 3 indicates the start of "main" function of the program, and the keyword void indicates that this function doesn't have any return type.
  3. Line 4: the curly brace indicates the start of main function.
  4. Line 5: the function clrscr() will clear all the previous outputs from the screen.
  5. Line 6: we have declared two variables "a & b" and given them values 1 and 5 respectively (we can give them any value depending on our requirement).
  6. Line 7: we have sent the 1st line of output to the screen and moved the cursor to next line using endl keyword.
  7. Line 8: we have shown the names of variables "a" & "b" on the screen (as our requirement) and we've put space of a tab between a&b using \t (escape character) and again moved the cursor to next line using endl.
  8. Line 9: we have send next line of output to the screen and again moved the cursor to next line.
  9. Line 10: we've started a while-loop (as written in problem), this loop will work until the variable "a" remains less than or equal to 5 (since a=1, and every time loop will run it will increment 1 in "a" , so the loop will run for 5 times).
  10. Line 11: the body of while-loop starts.
  11. Line 12: we output the values of a & b and put a space of a tab between them using \t, and also move the cursor to next line using endl
  12. Line 13 & 14: since the value of a is increasing in the required output format and the value of b is decreasing, so we're making increment in a and decrements in b.
  13. Line 15: the body of while-loop ends.
  14. Line 16: we have sent the last line of output according to the required output (no endl required here because it is the last line of output).
  15. Line 17: the keyword getch() will keep the output displayed on the screen unless the user presses any key from keyboard.
  16. Line 18: end of the program with end of the main() function.

No comments:

Post a Comment