Write a function to find binary equivalent of given decimal number.
Important note:
You have to display a switch menu like this:
Press <1> for Problem 1
Press <2> for Problem 2
Press <3> for Problem 3
Press <4> for Problem 4
Press <0> for exit
When user presses 1 your program should execute problem 1, when he/she press 2 it should execute problem 2 and so on. It clearly shows that you have to do the whole lab in one .c file.
To find the binary equivalent of the given number run the program and input 1. Other cases (2,3,4) doesn't work because you didn't provide Problem 2, Problem 3 and Problem 4. To quit the program input 0.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int read_int() {
int number;
scanf("%d", &number);
return number;
}
// function to find the binary representation of a decimal number
void bin(int n)
{
int b[32];
int i = 0;
while (n > 0) {
b[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--)
printf("%d", b[j]);
}
int main()
{
printf("Press <1> for Problem 1\nPress <2> for Problem 2\nPress <3> for Problem 3\nPress <4> for Problem 4\nPress <0> for exit\n");
int n = read_int(), num;
switch(n) {
case 1:
printf("Input a decimal number: ");
num = read_int();
printf("Binary representation of %d is ", num);
bin(num);
printf("\n");
break;
case 2:
printf("The Problem 2 doesn't exist\n");
printf("\n");
break;
case 3:
printf("The Problem 2 doesn't exist\n");
printf("\n");
break;
case 4:
printf("The Problem 2 doesn't exist\n");
printf("\n");
break;
case 0:
return 1;
default:
printf("Input a number between [1:4] or input 0 to quit: ");
printf("\n");
}
return 0;
}
Comments
Leave a comment