Problem Definition:
Decimal to binary conversion program in c. Decimal number has base 10 and binary number has base 2. Since the bases of both numbers are different it requires mathematical operation to be carried-out. To develop the programming logic we must have an understanding of the required mathematical operations. These mathematical operations will form programming constructs.
Desired Output:
Decimal number: 5
Binary number: 101
Problem Analysis:
In order to develop a program lets begin by understanding the conversion process of decimal number to binary number.
Following is the conversion process algorithm:
Step 1: Divide the number by 2.
Step 2: Store remainder.
Step 3: Divide the quotient by 2.
Step 4: Repeat the step 2 and step 3 till the quotient becomes 0.
Step 5: Binary number would be remainder in each step.
Example to understand conversion process:
Decimal number = 5
Step 1: 5/2: Remainder : 1, Quotient: 2
Step 2: Store Remainder 1.
Step 3: 2/2: Remainder : 0, Quotient: 1
Step 4: Store Remainder 0
Step 4: 1/2 Remainder : 1, Quotient : 0
Step 5: Store Remainder 1
Binary number equivalent to decimal number 5 is 101
Coding and Documentation:
Program for Decimal to binary conversion program in c
#include <stdio.h> int main() { int b = 0, x; int remaining, i =1, step = 1; printf("Enter number"); scanf("%d", &x); while(x!=0) { remaining = x%2; x=(int)(x/2); b=b+remaining*i; i=i*10; } printf("Binary:%d", b); return 0; }
Output: Enter Number: 5 Binary Number: 101
Code Analysis:
In this code, the user will input a decimal number to be stored in variable x. Program uses a “while loop” and its terminating condition is defined as x!=0. When x becomes 0 the loop terminates. “While loop” can also be replaced by “for” loop. “While loops” are also called entry controlled loops. Instructions are executed within the “while loop” and desired result is obtained.
Leave a Reply