My C program outputs undesired array values -
i've been tasked code program processes simple 1d array return element values, compiler has been behaving strangely; outputting more values have array elements.. it's not being compliant 1 of statements (one prints new line character every 8 elements) , not assigning largest value variable. think other 2 problems go away once first problem fixed, however.
here brief:
design, code , test program that:
- fills 20 element array (marks) random numbers between 0 , 100.
- prints numbers out 8 line
- prints out biggest number, smallest number , average of numbers
and here code:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ srand(time(null)); int marks[20]; int = 0; int sum = 0; int min; int max; for(i;i<=sizeof(marks);i ++){ marks[i] = rand() % 100; sum += marks[i]; if(i % 8 == 0){ printf("\n"); } printf("%d ", marks[i]); if(marks[i]>max){ max = marks[i]; } else if(marks[i]<min){ min = marks[i]; } } printf("\n\nthe minimum value is: %d", min); printf("\nthe maximum value is: %d", max); printf("\n\nthe average value is: %d", sum / sizeof(marks)); return 0; }
please can me correct output?
sizeof() function returns byte length of array, code "thinks" array 20 * whatever byte size int
s on machine. want use i < 20
in loop or go
for (i;i<sizeof(marks)/sizeof(int); ++) { ...
note not want <=
operator in for
loop, since arrays 0 indexed, marks[20]
1 beyond array.
Comments
Post a Comment