Reputation: 723
I need to make a C program to read the number of students(1<=students<=25
) in a class and for every student to read his exam score ex 10/20
15/20
etc(1<=score<=20
) and print the max and the max score of students and the average score of class.
I made the program but it performs the for
loop only once for some reason.
Can you please help me understand why?
here is the code :
#include <stdio.h>
int main(void) {
int m,i,b,sum,min,max,mo;
sum=0;
while (m<1 || m>25) {
printf("give number of students ");
scanf("%d",&m);
}
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) {
printf("give score of %d student",i);
scanf("%d",&b);
}
if(i==1) {
min=b;
max=b;
}
else {
if(b<min) min=b;
if(b>max) max=b;
}
sum=sum+b;
}
mo=sum/m;
printf("max is %d and min is %d and avg is %d",max,min,mo);
}
Upvotes: 1
Views: 109
Reputation: 863
1. You initialize 'm' here, without any prior value
int m,i,b,sum,min,max,mo;
2. Without a value, you check for this condition. Which means, a garbage value would be used. (May/May not fulfill your condition)
while (m<1 || m>25) {
3. The crucial scanf for m is inside the previous while. Without which your FOR would run for a basic i=1 and stop.
for (i=1; i<(m+1); i++) {
You need to understand about Garbage Values in C and vital step of initializing a variable to an initial value before using it.
You may read more on this link: What is a garbage value/How does it occur in C
Upvotes: 1
Reputation: 15793
You forgot to initialize the B
variabkle, so it loops m times, never asking you to insert a score!
Upvotes: 1
Reputation: 49373
First - initialize your variables:
int m,i,b,sum,min,max,mo; // these are declared and uninitialized
m = 0; // now it's initialized to 0
i = 0;
...
If you don't initialize them to something, you don't know what they are to start with.
Second - You need to change the value of b
:
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) { <-- here you're checking for b being valid
printf("give score of %d student",i);
scanf("%d",&b);
}
So the first time in b will be between 1 and 20, if you don't reset it to something invalid you'll never get here again. After you record the value of b:
sum=sum+b;
b = 0; // we're done with b for now, set it to something invalid for the while()
}
Upvotes: 1
Reputation: 9204
Not initialized the m
and using in while
condition
It is undefined behaviour
using uninitialized local variable in conditon
Want to implement the same
use
do
{
printf("give number of students ");
scanf("%d",&m);
}
while(m<1 || m>25);
for (i=1; i<(m+1); i++)
change the condition as i<=m
It's the good technique rather <
and then adding 1
Inside this loop use the same do while
loop
Upvotes: 1