C programming about scanf and array -
i try make program when enter 3 5 2 5 5 5 0
=>
enter numbers: 3 5 2 5 5 5 0
the largest number 5
the occurrence count of largest number 4
int main() { int a[10]; int i,max, count; printf("enter numbers: "); for(i=0;i<10;i++) { scanf("%d",&a[i]); } max=a[0]; count=1; for(i=1;i<10;i++) { if(max<a[i]) { count = 1; max = a[i]; } else if(max==a[i]) { count++; } } printf("the largest number %d\n",max); printf("the occurrence count of largest number %d",count); return 0; }
it code, totally wrong..
i don't know should do
please me
you've got several errors.
- in first loop, want read
a[i]
, nota[10]
. - your code corrently assumes type in 10 numbers. looks wanted value of 0 end list. me, i'd use end-of-file end list. check
0
need lineif(a[i] == 0) break;
in loop. check eof (or other non-numeric input cause problems) check seescanf
returns 1. - in case enter less 10 numbers, you'll need new variable knows how many variables entered. set
nn = i
after first loop. - then need change second loop run
1
nn
, not10
.
putting together, have:
#include <stdio.h> int main() { int a[10]; int i,max, count, nn; printf("enter numbers: "); for(i=0;i<10;i++) { if(scanf("%d",&a[i]) != 1) break; if(a[i] == 0) break; } nn = i; max=a[0]; count=1; for(i=1;i<nn;i++) { if(max<a[i]) { count = 1; max = a[i]; } else if(max==a[i]) { count++; } } printf("the largest number %d\n",max); printf("the occurrence count of largest number %d\n",count); return 0; }
this seems work.
Comments
Post a Comment