Problem:
Write a program to show the following format using while loop:
 |
| Show this format using while-loop |
Solution:
Here is the code, that shows the given format as output, using while-loop:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,sum;
cout<<"------------"<<endl;
cout<<"num\tsum"<<endl;
cout<<"------------"<<endl;
num=1;
sum=0;
while(num<=5)
{
sum=num+sum;
cout<<num<<"\t"<<sum<<endl;
num++;
}
cout<<"------------"<<endl;
getch();
}
Explanation:
- Line 1 & 2: include header files needed to run the program.
- Line 3: declaration of the main() function.
- Line 4: starting of main() function's body.
- Line 5: clrscr() clears all the previous outputs from the screen.
- Line 6: declaration of two variables required.
- Line 7: output a set of dashes and move the cursor to next line using endl (depending upon the required output mentioned in the problem).
- Line 8: output two words "num" & "sum" and add space of a tab between these words using \t and move the cursor to next line.
- Line 9: output another line of dashes (as mentioned in required output format) and move cursor to next line.
- Line 10 & 11: give initial values to variables (0 to sum and 1 to num: these values also depend upon our requirement, so these can be different in different cases)
- Line 12: Declare the while-loop on the basis of variable "num". This loop will run until num remains less-than or equal-to 5.
- Line 13: Start of the body of while-loop.
- Line 14: Add value of num to the current value of sum (following our requirement).
- Line 15: Output the current values of both variables (num, sum) and add a tab's space between both using \t and move the cursor to next line.
- Line 16: Increment the value of num.
- Line 17: End the body of while-loop.
- Line 18: Output last line of dashes (as mentioned in required output format) and move the cursor to next line (we can skip endl in the last line of output if we want).
- Line 19: getch() holds the output still on the screen until the user presses any key from the keyboard.
- Line 20: End of the main() function's body.
No comments:
Post a Comment