I currently am having a small trouble in my code, I am supposed to make a program that adds / sums all numbers inside of an array, while I have no problem in doing that, I currently have a problem with the part in which you are supposed to scan the numbers to be put in the array, here are the example of the input
3
5
1 2 3 4 5
8
1 2 3 4 5 6 7 8
9
1 2 3 4 5 6 7 8 9
What this means is that, the user inputs number "3" as it means to create 3 arrays, the number "5" afterward means to put 5 numbers inside of the array (1 2 3 4 5), after the user has inputted the numbers inside of an array, the user inputs "8" which means to make another array consisting of 8 numbers, and then putting numbers into the array again, and so on.
However I am having a problem in which after inputting all the numbers in the array that consists of 5 number, the program instead inputs 5 number into another array again (instead of asking the amount of numbers to be put inside of another array), so instead the number "8 1 2 3 4" gets inputted in another array, and I did not know which part I did wrong.
Here are my C code :
#include <stdio.h>
int main(){
int x, y;
int i;
int n;
int c=1;
int count=0;
int sum=0;
scanf("%d", &y); //this determines the amount of array to be inputted
scanf("%d", &x); //this determines the amount of numbers to be inputted inside of an array
int line[x];
for(int i=0; i<y; i ){
sum=0;
for(int i=0; i<x; i ){
scanf("%d", &line[i]); //scan number for the array
sum = line[i];
}
printf("Case #%d: %d\n", c, sum);//output of all sum
c ;
}
}
CodePudding user response:
You need to read the size for each array - currently you only read it once. e.g.:
int numLines;
scanf("%d", &numLines);
for(int lineIdx = 0; lineIdx < numLines; lineIdx ) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
int line[numNumbers];
for(int i = 0; i < numNumbers; i ) {
scanf("%d", &line[i]);
}
}
Additionally you can avoid storing the individual numbers, since you're only interested in the sum, e.g.:
int sum = 0;
for(int i = 0; i < numNumbers; i ) {
int number;
scanf("%d", &number);
sum = number;
}
Also you could defer outputting the sums until all inputs have been processed, so it doesn't visually get interleaved into the input.
This would be a possible way to write that program: godbolt
#include <stdio.h>
int main() {
// get the number of arrays we need to read
int numLines;
scanf("%d", &numLines);
// The sums of each array
int sums[numLines];
for(int lineIdx = 0; lineIdx < numLines; lineIdx ) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
// sum up all the numbers of the array
sums[lineIdx] = 0;
for(int i = 0; i < numNumbers; i ) {
int number;
scanf("%d", &number);
sums[lineIdx] = number;
}
}
// after all arrays have been entered,
// output the sums for each case:
for(int lineIdx = 0; lineIdx < numLines; lineIdx ) {
printf("Case #%d: %d\n", lineIdx, sums[lineIdx]);
}
}