romeroj1994
romeroj1994

Reputation: 39

count the amount of integers the user enters using a loop

#include <iostream>
int main()
{
  int cnt = 0, sum = 0, value = 0;
    std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl;
    if (cnt = value) 
    ++cnt;          
    while (std::cin >> value)

       sum += value;  

    std::cout << "the sum is: " << sum << std::endl;
    std::cout << "the amount of numbers you entered are: " << cnt << std::endl;

    return 0;

}

The if statement that I have is wrong and does not count the amount of integers the user enters into value.

How can I make the program count the amount of integers the user enters using a loop?

Upvotes: 2

Views: 1163

Answers (1)

ibezito
ibezito

Reputation: 5822

Solution explained

in order to count the number of integers provided, simply add 1 to cnt whenever a new input is given. (see line with //** comment below).

Also, the cnt==value check at start is not required (and there's one '=' character missing there).

updated code

To sum it all up, your code should be changes as follows:

#include <iostream>
int main()
{
    int cnt = 0, sum = 0, value = 0;
    std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl;      
    while (std::cin >> value)
    {
       sum += value;  
       cnt++; //**
    }
    std::cout << "the sum is: " << sum << std::endl;
    std::cout << "the amount of numbers you entered are: " << cnt << std::endl;

    return 0;

}

Upvotes: 4

Related Questions