Basic array question

Just started learning about arrays...I'm coding a pretty basic program that performs tasks on an array of numbers from a file

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
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
using namespace std;
ifstream infile;
ofstream outfile;

int main ()
{
	int num;
	int value [10];
	int sum=0;
	infile.open("E:\\CFiles\\DataFile4.txt");

	
	for (num=0;num<=9;num++)
	{	
		infile>>value[num];
		cout<<value[num]<<" ";
	}

	if (num=3)
	{
		cout<<endl<<endl;
		infile>>value[num];
		cout<<value[num]<<endl;
		cout<<endl;
	}
	
	for (num=5;num<=9;num++)
	{
		infile>>value[num];
		sum=sum+value[num];
		cout<<sum<<endl;
	}
}


My question is about line 33. I want to output ONLY the total sum of nums 5-9, but it's outputting each incremental step. 5+6, 6+7, etc. What should I change?
Move the cout out of the for loop.
Wow. That WAS simple. Thanks!
This code

1
2
3
4
5
6
7
	if (num=3)
	{
		cout<<endl<<endl;
		infile>>value[num];
		cout<<value[num]<<endl;
		cout<<endl;
	}


has no any sense. You assign 3 to num and reenter a value for value[3]. What is the sense of these manipulations?!
sum=sum+value[num];

can be

sum+=value[num];

I assume with if (num=3) you meant if (num==3) , = assigns, == compares. In either case, it's pointless. If you are assigning then there is no need for the if-statement, and if you're comparing the block will never execute because you left num==9 at the end of your for-loop. Also, avoid using global variables in for-loops, they allow for the declaration and definition of a new variable, like so
1
2
3
4
5
6

for (int a=0; a<10; a++)
{
      //code
}


Additionally, I don't understand why you take in 10 values, put them in the array, then take in another 5 values, put them in the last 5 spaces of the array and add those last five values. If that's what you meant to do, then ignore my comment.


Topic archived. No new replies allowed.