Problem:
Write a program to display the following format 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:
- Line 1 & 2, include the header files needed to run the functions inside this program.
- 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.
- Line 4: the curly brace indicates the start of main function.
- Line 5: the function clrscr() will clear all the previous outputs from the screen.
- 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).
- Line 7: we have sent the 1st line of output to the screen and moved the cursor to next line using endl keyword.
- 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.
- Line 9: we have send next line of output to the screen and again moved the cursor to next line.
- 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).
- Line 11: the body of while-loop starts.
- 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
- 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.
- Line 15: the body of while-loop ends.
- 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).
- Line 17: the keyword getch() will keep the output displayed on the screen unless the user presses any key from keyboard.
- Line 18: end of the program with end of the main() function.
No comments:
Post a Comment