|
CS256 - Fundamentals of Structured Programming
| Displaying exercises/e5/solution/h2.c
#include <stdio.h>
/**
* Read three integers (say, a, b and c) using scanf. Do not print a prompt.
* The inputs will be either zero or one. Produce the output "pass" or "fail"
* depending on the values of a, b and c using the following
* table:
*
* a | b | c | output
* -------------------
* 0 | 0 | 0 | "pass"
* 0 | 0 | 1 | "fail"
* 0 | 1 | 0 | "pass"
* 0 | 1 | 1 | "fail"
* 1 | 0 | 0 | "pass"
* 1 | 0 | 1 | "fail"
* 1 | 1 | 0 | "fail"
* 1 | 1 | 1 | "pass"
*
* Example input/output:
* > ./h2
* 0 1 0
* pass
*/
int main(void)
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
/*
// Simple if-else chain method:
if (a == 0 && b == 0 && c == 0) printf("pass\n");
else if (a == 0 && b == 1 && c == 0) printf("pass\n");
else if (a == 1 && b == 0 && c == 0) printf("pass\n");
else if (a == 1 && b == 1 && c == 1) printf("pass\n");
else printf("fail\n");
// More concise version that assumes that a, b and c can only be 0 or 1:
// Recall that 0 is "false" and non-zero is "true".
if (!a && !b && !c) printf("pass\n");
else if (!a && b && !c) printf("pass\n");
else if ( a && !b && !c) printf("pass\n");
else if ( a && b && c) printf("pass\n");
else printf("fail\n");
// Even more concise, combines all the if expressions into one using ||:
if ((!a && !b && !c) || (!a && b && !c) || ( a && !b && !c) || ( a && b && c))
printf("pass\n");
else
printf("fail\n");
*/
// Assumes that a, b and c can only ever be 0 or 1:
if (a == 0) {
// b has no effect on pass/fail when a == 0:
if (c == 0) printf("pass\n");
else printf("fail\n");
} else {
// When a == 1, then pass when b and c are the same.
if (b == c) printf("pass\n");
else printf("fail\n");
}
return 0;
}
|