for sum

look at this please:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
    int num1;
    cout << "Enter 5 numbers to get average: ";


    for (int i = 1; i < 5; i++)
    {
        cin >>num1;
        num1+=1;
    }

cout << num1;


    return 0;
}

the out put must be 5
but why the out put become 2?
help me please
Why did you decide that output must be 5?!
you input a number. and then you add 1 to it.
in the next loop you put a new value into num1 and add 1 to it again. so you are not caclulating the average.
you should add all numbers the user enters and divide the sum by 5.
@Sarah93

Maybe you should first initialize num1 to 0, otherwise your num1+=1 could wind up being a weird number. To check, compile and run this slightly modified code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Test.cpp : main project file.

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    int num1;
    cout << "Enter 5 numbers to get average: ";
	
	cout << "num1 = " << num1 << endl;;

    for (int i = 1; i < 5; i++)
    {
        cin >>num1;
        num1+=1;
    }

cout << num1;


    return 0;
}


Also, you are only inputting 4 numbers. i starts out as 1, and i < 5 would be 4.
I think you should just use another variable to increase (like num2+=1; instead of num1+=1;) and print that one at the end because all you are doing is reading num1 then adding a 1 to it

Edit: Also as whitenite1 said start i as 0 not 1, from 1 to 5 is only 4 numbers not 5
Last edited on
@gelatine and Madguy

I think Sarah93 is just trying to figure why num1 doesn't end up equaling 5, as she alludes to in..
the out put must be 5
but why the out put become 2?


I think it is for controlling what (s)he feels what the result should be.

EDIT..

@Madguy

I think you meant num2+=num1;
Last edited on
@whitenite1

Yes I know for that was my answer.. he means the output must be 5 because after reading 5 numbers the counter must print 5 at the end and not 2, it printed 2 because the last number he input was 1 then num+=1 added 1 more to it.
@Madguy

Sorry about that. I forgot to notice that the variables were the the same for input and adding one to it. I'll try to be a little more observant in the future.
Topic archived. No new replies allowed.