I
last year
Iancountry asked

Let’s say we need to write a program that adds five numbers entered by the user, one by one. Do we start by declaring the first number as int = 1, or what’s the correct approach?

Abhay Jajodia
Expert
last year
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 for loop 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.