User need to input 2 type of input 3 times, which is number 1 for pass and number 2 for fail...program need to give the summary of how many user input number 1 and number 2
#include <stdio.h>
int main() {
int result[3];
int pass;
int fail;
for (int i = 1; i <= 3; i++) {
printf("Enter Result (Pass=1 Fail=2) :");
scanf("%d", &result[i]);
}
if (&result == 1) {
pass = pass + 1;
}
if (&result == 2) {
fail = fail + 1;
}
printf("%d", pass);
printf("%d", fail);
}
Some issues:
&result == 1
takes the address of the array result
and tries to compare that to the integer 1
. This will, if the code even compiles, very rarely be true. You want to compare result[index]
with 1
(or 2
).result
is an int[3]
, you are only allowed to access result[0]
, result[1]
and result[2]
.pass
and fail
are uninitialized and contains indeterminate values. Reading those, which is required in pass = pass + 1;
, will make the program have undefined behavior. Initialize them to 0
.I suggest not using an array and then do the comparisons with 1
and 2
inside the loop.
Example:
#include <stdio.h>
int main(void) {
int result;
int pass = 0;
int fail = 0;
for (int i = 0; i < 3; i++) {
printf("Enter Result (Pass=1 Fail=2) :");
if (scanf("%d", &result) != 1) {
fputs("Erroneous input\n", stderr);
return 1;
}
if (result == 1) {
pass = pass + 1;
} else if (result == 2) {
fail = fail + 1;
} else {
printf("The invalid input %d will not be counted\n", result);
}
}
printf("pass: %d\n", pass);
printf("fail: %d\n", fail);
}