R
R
Romazvar2021-07-03 22:15:13
C++ / C#
Romazvar, 2021-07-03 22:15:13

How can a for loop count input?

#include <iostream>

int main()
{
    int sum = 0;

    // Разрешаем пользователю ввести до 10 чисел
    for (int count=0; count < 10; ++count)
    {
        std::cout << "Enter a number to add, or 0 to exit: ";
        int val;
        std::cin >> val;

        // Выходим из цикла, если пользователь введет 0
        if (val == 0)
            break;

        // В противном случае, добавляем число к общей сумме
        sum += val;
    }

    std::cout << "The sum of all the numbers you entered is " << sum << "\n";

    return 0;
}

How can the for loop read how many times I entered characters and if this number reaches 10, then the program ends, we did not select anything. Please explain

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-07-04
@Romazvar

You have a loop of 10 iterations ( for (int count=0; count < 10; ++count)). With a possible early exit ( break).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question