Created
April 14, 2014 13:59
-
-
Save ashokfernandez/10650556 to your computer and use it in GitHub Desktop.
FizzBuzz Using C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdbool.h> | |
#define STARTING_NUMBER 1 | |
#define ENDING_NUMBER 100 | |
enum CASES { MULTIPLE_OF_THREE = 1, MULTIPLE_OF_FIVE, MULTIPLE_OF_BOTH }; | |
/** | |
* Tests if 'number' is a multiple of 'multiple', returns TRUE or FALSE accoringly | |
*/ | |
static inline bool isMultiple(int number, const int multiple){ | |
return (number % multiple) == 0; | |
} | |
int main(void){ | |
/* Initalise a few variables */ | |
int currentNumber = STARTING_NUMBER; | |
bool multipleOfFive = false; | |
bool multipleOfThree = false; | |
int result = 0; | |
for(; currentNumber <= ENDING_NUMBER; currentNumber++){ | |
/* Test for multiples */ | |
multipleOfFive = isMultiple(currentNumber, 5); | |
multipleOfThree = isMultiple(currentNumber, 3); | |
/* Merge the test for multiples into two bit integer so we can identify which case we have | |
with a switch statement | |
Our Cases are: | |
01 - Mulitple of Three | |
10 - Multiple of Five | |
11 - Multiple of Both | |
*/ | |
result = 0; | |
result |= multipleOfThree | (multipleOfFive << 1); | |
/* Using the switch statement we are able to jump straight to the relevant case instead of | |
messing around with cascaded if statements */ | |
switch(result){ | |
case MULTIPLE_OF_THREE: | |
printf("Fizz\n"); | |
break; | |
case MULTIPLE_OF_FIVE: | |
printf("Buzz\n"); | |
break; | |
case MULTIPLE_OF_BOTH: | |
printf("FizzBuzz\n"); | |
break; | |
/* If none of the above conditions are met then just print the number */ | |
default: | |
printf("%i\n", currentNumber); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment