﻿ C Program: Convert an octal number into binary - w3resource

# C Exercises: Convert an octal number into binary

## C For Loop: Exercise-54 with Solution

Write a program in C to convert an octal number into binary.

Visual Presentation: Sample Solution:

C Code:

``````#include <stdio.h>  // Include the standard input/output header file.
#include <math.h>   // Include the math header file.
int main() {
// Declare variables
long int n1, n5, p = 1;
long int dec = 0, i = 1, j, d;
long int binno = 0;

printf("\n\nConvert Octal to Binary:\n");
printf("-------------------------\n");

// Get octal input
printf("Input an octal number (using digits 0 - 7): ");
scanf("%ld", &n1);

// Store input number
n5 = n1;

// Convert octal to decimal
// Loop through each octal digit
for (j = n1; j > 0; j = j / 10) {
// Get current digit
d = j % 10;

// Update power of 8
if (i == 1) {
p = p * 1;
} else {
p = p * 8;
}

// Add digit * power of 8 to result
dec = dec + (d * p);

// Increment power
i++;
}

// Convert decimal to binary
i = 1; // Reset power

// Repeatedly divide decimal by 2
for (j = dec; j > 0; j = j / 2) {
// Get remainder and add to result
binno = binno + (dec % 2) * i;

// Update power of 2
i = i * 10;

// Divide decimal
dec = dec / 2;
}

// Print octal and binary result
printf("\nThe Octal Number: %ld\nThe equivalent Binary Number: %ld\n\n", n5, binno);

return 0; // Indicate successful completion of the program
}
```
```

Sample Output:

```Convert Octal to Binary:
-------------------------
Input an octal number (using digit 0 - 7) :57

The Octal Number : 57
The equivalent Binary  Number : 101111
```

Flowchart: C Programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿