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;
// Print output headers
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:
Previous: Write a program in C to convert a binary number to octal.
Next: Write a program in C to convert a decimal number to hexadecimal.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join