|
CS256 - Fundamentals of Structured Programming
| Displaying exercises/e5/solution/h3.c
#include <stdio.h>
#include <stdlib.h>
/**
* Prompt ("num? ") for an integer number from the user, then get the number
* from the user. If the number read is evenly divided by 3 print "Foo", if
* it's evenly divided by 5 print "Bar" and if it's evenly divided by both 3
* and 5 print "FooBar". If it is not evenly divided by either, just print
* the number itself. If scanf fails to read read the number (return value
* is not 1), then print "Not a number".
* Hint: To determine if a number is divisible by another, use the mod (%)
* operator. A number is evenly divisible by another if the result of the
* mod operation is 0 (i.e. x % 7 == 0 when x is divisible by 7.)
*
* Example input/outputs:
* > ./h3
* num? 15
* FooBar
* > ./h3
* num? 5
* Bar
* > ./h3
* num? 43
* 43
*/
int main(void)
{
int num;
printf("num? ");
if (scanf("%d", &num) != 1) printf("Not a number");
else if (num % 3 == 0 && num % 5 == 0) printf("FooBar\n");
else if (num % 3 == 0) printf("Foo\n");
else if (num % 5 == 0) printf("Bar\n");
else printf("%d\n", num);
return 0;
}
|