Objective: Write a simple program to demonstrate while loop and compute the summ
ID: 3847473 • Letter: O
Question
Objective: Write a simple program to demonstrate while loop and compute the summation. The main purpose of this homework is to review the understanding of for while loop.
Problem: Using C++, write a program with 1 while loop to print out the numbers and summation. The iteration number is read directly from command line, e.g., ./executable iteration.
Output:
In this example, I use 5 for WHILE LOOP
Assume the executable file is called solution, then your program should be executed as ./solution 5
The screen should show
1
2
3
4
5
Summation is: 15
Requirement
- You can choose any positive integer (program will give error or crash if you have negative number) for WHILE LOOP.
- Should give error or crash if argument number is not exactly 2
- To print the summation, e.g., cout << “Summation is: “ << summation << endl; (endl = end of line)
- Enhance understanding for if statement and argument input in C++
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
int i,number,summation;
summation = 0;
i=1;
cout<<"Enter the number : "; //input the number
cin>>number;
cout<<endl;
while(i<=number) //while loop
{
cout<<i<<endl;
summation = summation + i;
i++;
}
cout << "Summation is: "<< summation << endl;
return 0;
}
Output:
Enter the number :
1
2
3
4
5
Summation is: 15
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.