(1) Using a FOR loop to write a program that will promt the user for 5 numbers a
ID: 670056 • Letter: #
Question
(1) Using a FOR loop to write a program that will promt the user for 5 numbers and calculate the sum of the 5 numbers. You've written a similar program in the last lab using a WHILE loop, however for counting loops, a FOR loop is easier to work with.
(2) Using a FOR loop to write a program that will calculate the sum of the first n positive integers. The value of n is provided by the user, and you program should be able to validate the user input to make sure n is a positive integer.
Sum_n = 1+2+3+...+n
Explanation / Answer
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int i=0;
int number,sum = 0;
for (i=0;i<5;i++) {
cout << "Enter the " << (i+1) << " number : ";
cin >> number;
sum = sum+number;
}
cout << "Sum of five numbers " << sum;
cout << " Enter the value of n : ";
cin >> number;
sum = 0;
for(i=1;i<=number;i++)
{
sum = sum+i;
}
cout << "Sum of first " << number << " numbers is " << sum;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.