void fizzbuzz(int i)
to handle your printing.
#include <stdio.h> #include <stdlib.h> void fizzbuzz(int num); int main(){ int i = 1; while(i < 100){ fizzbuzz(i); i++; } return 0; } void fizzbuzz(int num){ if((num % 3 == 0) && (num % 5) == 0){ printf("FizzBuzz\n"); }else if(num % 3 == 0){ printf("Fizz\n"); }else if(num % 5 == 0){ printf("Buzz\n"); }else{ printf("%d\n",num); } return; }
int isdigit( int ch ) { return( ch >= '0' && ch <= '9' ); } int islower( int ch ) { return( ch >= 'a' && ch <= 'z' ); } int toupper( int ch ) { if( ch >= 'a' && ch <= 'z' ) { return( ch + 'A' - 'a' ); } else { return( ch ); } }
10010101
method 1 - using powers of 2:
128 + 16 + 4 + 1 = 149method 2 - repeated multiplication:
0 x 2 + 1 = 1 1 x 2 + 0 = 2 2 x 2 + 0 = 4 4 x 2 + 1 = 9 9 x 2 + 0 = 18 18 x 2 + 1 = 37 37 x 2 + 0 = 74 74 x 2 + 1 = 149
186
method 1 - using powers of 2:
186 -128 = 58 -> 1 58 < 64 -> 0 58 - 32 = 26 -> 1 26 - 16 = 10 -> 1 10 - 8 = 2 -> 1 2 < 4 -> 0 2 - 2 = 0 -> 1 0 < 1 -> 0so 18610 = 101110102
method 2 - using repeated division
186 / 2 = 93 r 0 93 / 2 = 46 r 1 46 / 2 = 23 r 0 23 / 2 = 11 r 1 11 / 2 = 5 r 1 5 / 2 = 2 r 1 2 / 2 = 1 r 0 1 / 2 = 0 r 1reading upwards, answer = 10111010
B7A316
B = 1011
7 = 0111
A = 1010
3 = 0011
so B7A316 = 10110111101000112
1100111101010010
1100 = C
1111 = F
0101 = 5
0010 = 2
so 11101111010100102 = CF5216
-19
int main( void ) { int num = 0; int ch; ch = getchar(); // scan binary digits from left to right while( ch == '0' || ch == '1' ) { num = 2 * num + ( ch - '0' ); ch = getchar(); } printf("Value = %d\n", num ); return 0; }
Enter base: 7 Enter number: 5342 Value = 1892How would you modify your program to handle bases larger than 10?
int main( void ) { int base; int num=0; int ch; printf("Enter base: "); scanf("%d",&base); printf("Enter number: "); // skip the newline and any additional spaces ch = getchar(); while( ch == '\n' || ch == ' ' ) { ch = getchar(); } while(( ch >= '0' && ch <= '9' )||( ch >= 'A' && ch <= 'Z' )) { if( ch >= '0' && ch <= '9' ) { num = base*num + ( ch - '0'); } else { num = base*num + ( ch + 10 - 'A'); } ch = getchar(); } printf("Value = %d\n", num ); }
int main( void ) { int num; int power2=1; int ch; scanf("%d", &num ); // find the largest power of 2 that is not larger than num while( power2 <= num/2 ) { power2 = power2 * 2; } // now compute the binary digits from left to right while( power2 > 0 ) { if( num >= power2 ) { printf("1"); num = num - power2; } else { printf("0"); } power2 = power2 / 2; } printf("\n"); return 0; }