C program to convert Binary to Decimal & Decimal to Binary.
Program Source Code:
#include <stdio.h> int main() { int choice; int num, binary_val, decimal_val = 0, base = 1, rem; printf("Welcome to Binary & Decimal Converter\n"); printf("Enter 1 for B-D\n"); printf("Enter 2 for D-B\n"); printf("Enter Your Choice:\n"); scanf("%d",&choice); switch(choice) { case 1:printf("Enter a binary number(1s and 0s) \n");scanf("%d", &num); binary_val = num; while (num > 0) { rem = num % 10; decimal_val = decimal_val + rem * base; num = num / 10; base = base * 2; } printf("The Binary number is = %d \n", binary_val); printf("Its decimal equivalent is = %d \n", decimal_val); break; case 2: long num2, decimal_num, remainder, base2 = 1, binary = 0, no_of_1s = 0; printf("Enter a decimal integer \n"); scanf("%ld", &num2); decimal_num = num2; while (num2 > 0) { remainder = num2 % 2; if (remainder == 1) { no_of_1s++; } binary = binary + remainder * base2; num2 = num2 / 2; base2 = base2 * 10; } printf("Input number is = %ld\n", decimal_num);printf("Its binary equivalent is = %ld\n", binary); printf("No.of 1's in the binary number is = %ld\n", no_of_1s); break; } }
Program Explanation for decimal to Binary Conversion:
In this C program, we are reading the decimal number using ‘num’ variable. A decimal number system is a base 10 number system using digits for 0 to 9 whereas binary number system is base 2 and uses 0 and 1. Check whether the number is less than or equal to zero. Divide the number by 2 and store the remainder in the array. Increase the length of the array by 1. After the execution of while loop, print the binary number and the number of 1’s.
Program Explanation for Binary to Decimal Conversion:
1. Take a binary number and store it in the variable num.
2. Initialize the variable decimal_val to zero and variable base to 1.
3. Obtain the remainder and quotient of the binary number. Store the remainder in the variable rem and override the variable num with quotient.
4. Multiply rem with variable base. Increment the variable decimal_val with this new value.
5. Increment the variable base by 2.
6. Repeat the steps 3, 4 and 5 with the quotient obtained until quotient becomes zero.
7. Print the variable decimal_val as output.
2. Initialize the variable decimal_val to zero and variable base to 1.
3. Obtain the remainder and quotient of the binary number. Store the remainder in the variable rem and override the variable num with quotient.
4. Multiply rem with variable base. Increment the variable decimal_val with this new value.
5. Increment the variable base by 2.
6. Repeat the steps 3, 4 and 5 with the quotient obtained until quotient becomes zero.
7. Print the variable decimal_val as output.
No comments:
Post a Comment