Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS101 / KCS201 Programming for Problem Solving - Using C Language
Lab Exercises
20. Write a program to convert the binary number into a decimal number and vice versa.
/*
File: Prgrm20.c
Author: Aditya Saini
Date: Sept 30, 2019
Description: Program to convert the binary number into a decimal number and vice versa.
*/
#include <stdio.h>
#include <math.h>
#include <math.h>
int binary_to_decimal (int);
int decimal_to_binary (int);
int main (void)
int decimal_to_binary (int);
int main (void)
{
int choice;
int binary_number;
int decimal_number;
//Input Choice.
printf ("***Menu***\n");
printf ("1 Binary to Decimal\n");
printf ("2 Decimal to Binary\n");
printf ("Choose 1 or 2: ");
scanf ("%d", &choice);
int binary_number;
int decimal_number;
//Input Choice.
printf ("***Menu***\n");
printf ("1 Binary to Decimal\n");
printf ("2 Decimal to Binary\n");
printf ("Choose 1 or 2: ");
scanf ("%d", &choice);
switch (choice)
{
//Function call and output the result.
case 1:
printf ("Input binary number: ");
scanf ("%d", &binary_number);
decimal_number = binary_to_decimal (binary_number);
printf ("Decimal number: %d", decimal_number);
break;
case 2:
printf ("Input decimal number: ");
scanf ("%d", &decimal_number);
binary_number = decimal_to_binary (decimal_number);
printf ("Binary number: %d", binary_number);
break;
default:
printf ("Error! Wrong Choice!");
}
return 0;
};
//Convert Binary to Decimal
int binary_to_decimal (int binary_number)
{
int decimal_number;
int i;
decimal_number = 0;
i = 0;
while (binary_number != 0)
{
decimal_number = decimal_number + (binary_number % 10) * pow (2, i);
binary_number = binary_number / 10;
i++;
}
return decimal_number;
};
//Convert Decimal to Binary
int decimal_to_binary (int decimal_number)
{
int binary_number;
//Convert Binary to Decimal
int binary_to_decimal (int binary_number)
{
int decimal_number;
int i;
decimal_number = 0;
i = 0;
while (binary_number != 0)
{
decimal_number = decimal_number + (binary_number % 10) * pow (2, i);
binary_number = binary_number / 10;
i++;
}
return decimal_number;
};
//Convert Decimal to Binary
int decimal_to_binary (int decimal_number)
{
int binary_number;
int i;
binary_number = 0;
i = 0;
while (decimal_number != 0)
{
binary_number = (decimal_number % 2) * pow (10, i) + binary_number;
decimal_number = decimal_number / 2;
i++;
}
return binary_number;
};
binary_number = 0;
i = 0;
while (decimal_number != 0)
{
binary_number = (decimal_number % 2) * pow (10, i) + binary_number;
decimal_number = decimal_number / 2;
i++;
}
return binary_number;
};
Output
***Menu***
1 Binary to Decimal
2 Decimal to Binary
Choose 1 or 2: 2
Input decimal number: 13
Binary number: 1101
1 Binary to Decimal
2 Decimal to Binary
Choose 1 or 2: 2
Input decimal number: 13
Binary number: 1101
No comments:
Post a Comment
Please do not post spam links.