Code:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int passes = 0;
int failures = 0;
int student = 1;
while (student <= 10)
{
printf ("Enter 1 for pass, 2 for fail: ");
int result;
scanf ("%d", &result);
if (result == 1)
{
passes = passes + 1;
}
else
{
failures = failures + 1;
}
student = student + 1;
}
printf ("%d students passed,", passes);
printf (" %d students failed.\n", failures);
if (passes > 8)
{
puts("Congratulations! Instructor gets a bonus!");
}
return 0;
}
Above code gives me the correct number of pass/fail grades corresponding with my input, but if I don't assign "passes" and "failures" to zero, I get weird output. Why does it do this, I thought un-assigned output by default was 0? Here is the output for when I just had it as "int passes;" and "int failures;" at the top.
Code:
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
Enter 1 for pass, 2 for fail: 1
10 students passed, 4096 students failed.
Congratulations! Instructor gets a bonus!
As you can see, at the end of the program, 4096 was the value of "failures". Nothing else about the code was different!