I need to compute the sum of the values in an array of integers of length 25 read from a file named "numbers.txt." Below is my program that lists the numbers and crashes. Please help to solve the issue and please explain the solution.
You need a similar loop to read in the values. I've put your code in a loop.
1 2 3 4 5 6 7 8 9 10 11 12 13
int numcases = 25 , i = 0,j,k, num, sum = 0;
int array [numcases] = { 0 }; // initialise values to zero
for (int i = 0; i != 5; ++i) // ask for 5 values
{
fscanf(ifp,"%d", &num);
array [i] = num;
printf ("%d", num);
sum = sum + num;
}
im sorry, i tried to run your code but it failed to compile saying: variable-sized object may not be initialized, [Warning] excess elements in array initializer, and [Warning] (near initialization for `array')
The code was meant to demonstrate where you should put a loop in. Apart from the initialisation of the array (using a C++11 construct) and the loop, the rest is your code.
Also, I deliberately initialised only 5 elements even though the array has 25 elements. I expected you to think about it rather than providing a solution you could just copy and hand in.
Ok so basically you are saying that I should use a for loop instead of a while? Also, I am sorry I misunderstood your intentions. I hope you believe me when I say this is not homework but review for a test I have tomorrow. I need to figure out how to use arrays by tomorrow. Thank you for helping!
Ok so basically you are saying that I should use a for loop instead of a while?
No. I said what I meant. "You need a similar loop to read in the values"
I wasn't commenting on the kind of loop, but the fact that you had to put that code that reads in a value into a loop. Did you not find it strange that you had an array, but you couldn't decide what index to use for the array?
1 2 3
fscanf(ifp,"%d", &num);
array [i] = num;
If I have the time, I'll help as far as I can. To be honest, I thought I did.