for loop

Jul 26, 2013 at 8:16am
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;
    
    
    
    
Jul 26, 2013 at 8:22am
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.
Jul 26, 2013 at 8:30am
@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;
Jul 26, 2013 at 9:38am
try outputting your total instead ;)
Jul 26, 2013 at 9:48am
closed account (z05DSL3A)
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 Jul 26, 2013 at 9:55am
Topic archived. No new replies allowed.