Arrays result/output wrong

Write your question here.
hey guy i am adding arrays when user give input from keyboard,d but the result is different from what i give input... Please sort it out
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  
#include <iostream>

using namespace std;

int main()
{
    int add[5];
    int n, sum=0;
    for(int x=0; x<5; x++){
        cout<<"Enter Value : " <<endl;
        cin >> n;
        sum += add[n];
    }

    cout << sum;
    return 0;
}
1
2
cin >> add[x];
sum += add[x];
try this.............



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main()
{
    int add[5];
    int n, sum=0;
    for(int x=0; x<5; x++){
        cout<<"Enter Value : " <<endl;
        cin >> n;
        add[x]=n;
        sum+=add[x];
    }

    cout << sum;
    return 0;
}
Last edited on
The array isn't adding anything useful here, the program can be written just as well without it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{

	int n, sum=0;

	for (int x=0; x<5; x++)
	{
		cout << "Enter Value : " << x+1 << endl;
		cin >> n;
		sum += n;
	}

	cout << "Total = " << sum << endl;
	return 0;
}


I'd suggest, if using an array, at least put it to work:
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
26
27
#include <iostream>

using namespace std;

int main()
{
    const int size = 5;

    int add[size];

    // Get the input and store it
    for (int x=0; x<size; x++)
    {
        cout<<"Enter Value : " << x+1 << endl;
        cin >> add[x];
    }

    // calculate the total of the values in the array
    int sum = 0;
    for (int x=0; x<size; x++)
    {
        sum += add[x];
    }

    cout << "Total = " << sum;
    return 0;
}



Last edited on
Topic archived. No new replies allowed.