I
Ian
asked

Expert
Abhay Jajodia answered
Hi Ian,
Good question. You don’t need to declare the first number as 1. Instead, you can use a loop that runs 5 times and asks the user to enter a number each time. You just keep adding each input to a running total.
Here’s how you can do it in C++:
#include
using namespace std;
int main() {
int sum = 0; // to store the total
int number; // to hold each number entered by the user
for (int i = 1; i <= 5; i++) {
cout << "Enter number " << i << ": ";
cin >> number;
sum += number; // add the number to the total
}
cout << "Total sum is: " << sum << endl;
return 0;
}
How it works:
You start with
sum = 0— the total will build up as users enter numbers.A
forloop runs 5 times (from 1 to 5).In each iteration, the user enters a number, and it’s added to
sum.
So, no need to start by declaring a number as 1. The loop and input take care of that.
If you have more questions, I am here to help.
C++
This question was asked as part of the Learn C++ Basics course.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer