You forgot the i++ in the first line of the for loop.
Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
Define "goes nuts". That is hard to imagine.
Explaining a problem correctly often results in more accurate answers and better help.
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
>>for (i = 0; i < n;++i){
What will happen if you only input 3 numbers? Answer: the final value of sum will be in the crapper because it will add in uninitialized array elements 4-20.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
You have to work out the simplest, clearest, and most efficient way to program.
#include <stdio.h>
#define SIZE 20
int main(void)
{
int i = 0, n = i;
int array[SIZE];
int sum = 0;
while (scanf("%d", &array[i]) !=0 ){
printf("Entered Integer number %d: was %d\n", i, array[i]);
sum += array[i]; //<----- add this line
i++;
}
/* Right here, i equals the number of int's you have put into the array, so
the for loop below could be simplified n=0;n<=i;n++. However it shows an
even simpler and more efficient answer - put the sum into the same while()
loop as the entry (why the hell not?), and forget this second loop,
completely - it's useless.
*/
//Ditch this loop like a bad habit :(
for (i = 0; scanf("%d", &array[i]) == 0; i++){
sum = sum + array[i];
printf( "The sum is: %d\n", sum);
return (sum); //??? you're joking right?
}
printf("The sum was %d", sum);
return 0;
}
Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185