for loop

Write a for loop that repeats seven times, asking the user to enter a number. The
loop should also calculate the sum of the numbers entered.

this is what i have so far..its not summing up the numbers entered. can anybody help me please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  int count=0;
    float total=0;
    int sum=0;
    
    for( count=0; count <=7; count++)
    {
        int number;
        int sum;
        total+=sum;
        cout << "enter a number"<< endl;
        cin >> number;
       
        
    }
    cout << 'the sum is '<<sum<< endl;
    
    
    
    
You already declared int sum outside the loop, so you do not need to re-declare it anymore. You should also try to declare all your variables outside any sort of loops.

You are adding sums to total, but user's input goes into int num, not int sum. But you have the right idea with the total += sum, you're just adding the wrong variable. And you should add it AFTER the user has inputted the value.
@jae i declared all the variables outside and i still have a problem.. when it comes to adding up the numbers from the users input. its giving me a really BIG number...


int count=0;
float total=0;
int num=0;

for( count=0; count <=7; count++)
{

cout << "enter a number"<< endl;
cin >> num;
total+=num;


}
cout << 'the sum is '<<num<< endl;
try outputting your total instead ;)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
    float total = 0;
    
    for(int count = 0; count < 7; count++)  // Loop 7 times
    {
        int num = 0;   // moved declaration of count and num to keep their scope smaller
        std::cout << "enter a number" << std::endl;
        std::cin >> num;
        total += num;
    }
    std::cout << "the sum is " << total << std::endl; // " instead of ' and total instead of num
}
Last edited on
Topic archived. No new replies allowed.