(C ++ ) (using loop, without using void command) Write a program that asks the u
ID: 3737910 • Letter: #
Question
(C ++ ) (using loop, without using void command)
Write a program that asks the user for a positive integer value by prompting "Enter a positive integer number: ", read in that number, then use a loop to get the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2,3, 4…50. It should print "The total of all the integers from 1 to 50 is …"
Input validation: when user enters a invalid number, the program should prompt user "The number cannot be less than one."
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a positive integer number: "<<endl;
cin >> n;
while(n<=0) {
cout<<"The number cannot be less than one. Enter a positive integer number: "<<endl;
cin >> n;
}
int sum = 0;
for(int i=1;i<=n;i++) {
sum+=i;
}
cout<<"The total of all the integers from 1 to "<<n<<" is "<<sum<<endl;
return 0;
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.