» » » C program to convert binary to decimal using for loop

# C program to convert binary to decimal using for loop

• c program to convert binary to decimal using array and for loop.
• Lets us see an example program on c to convert binary format number to decimal format.
• Write a function which accepts a number as binary.
•       rem = n%10;
•         n /= 10;
•         decimal += rem*pow(2,i);
• This is the logic to get decimal format of the number.

Program #1 : write a c program to convert binary to decimal using while loop function

1. #include <stdio.h>
2. int convertBinaryToDecimal(long long n);
3.
4. int main()
5. {
6.     long long n;
7.     printf("Enter a binary number: ");
8.     scanf("%lld", &n);
9.     printf("%lld binary format= %d decimal format", n, convertBinaryToDecimal(n));
10.
11.     getch();
12. }
13.
14. int convertBinaryToDecimal(long long n)
15. {
16.     int decimal = 0, i = 0, rem;
17.     while (n!=0)
18.     {
19.         rem = n%10;
20.         n /= 10;
21.         decimal += rem*pow(2,i);
22.         ++i;
23.     }
24.     return decimal;
25. }

Output:

Program #2 : write a c program to convert binary to decimal using while loop function

1. #include <stdio.h>
2. int convertBinaryToDecimal(long long n);
3.
4. int main()
5. {
6.     long long n;
7.     printf("Enter a binary number: ");
8.     scanf("%lld", &n);
9.     printf("%lld binary format= %d decimal format", n, convertBinaryToDecimal(n));
10.
11.     getch();
12. }
13.
14. int convertBinaryToDecimal(long long n)
15. {
16.     int decimal = 0, i = 0, rem;
17.     for (i=0; n!=0;i++)
18.     {
19.         rem = n%10;
20.         n /= 10;
21.         decimal += rem*pow(2,i);
22.
23.     }
24.     return decimal;
25. }

Output:

1. Enter a binary number:
2. 1011
3. 1011 binary format= 11 decimal format

You Might Like: