Slider

C Program to Convert Octal to Decimal.

In this C program tutorial, we are going to learn how to convert an Octal to a Decimal number. Let's understand the process with an example.
In this C program tutorial, we are going to learn how to convert an Octal to a Decimal number. Let's understand the process with an example. 

Step-by-step Algorithm:

Step 1: Input the octal number from the user.
Step 2: Initialize the decimalNum variable to 0, and base variable to 1. The decimalNum will store the final decimal equivalent, and the base is used to keep track of the current place value (powers of 8).
Step 3: Convert octal to decimal using a while loop. In each iteration, we extract the last digit (remainder) of the octal number using the modulus operator %. Then, we multiply the digit with the current base value and add it to the decimalNum. We update the octalNum by removing the last digit (integer division by 10) and increasing the base by multiplying it by 8, which represents the next place value (8 raised to the power of the current position).
Step 4: Output the decimal equivalent of the octal number.

C Code:

//C program to Convert Octal to Decimal.
#include <stdio.h>

int main() {
    int octalNum, decimalNum = 0, base = 1, remainder;

    printf("Enter an octal number: ");
    scanf("%d", &octalNum);

    // Convert octal to decimal
    while (octalNum != 0) {
        // Extract the last digit
        remainder = octalNum % 10; 
        // Multiply digit with base and add to decimalNum
        decimalNum += remainder * base;
        // Remove the last digit
        octalNum /= 10; 
        // Increase base by a power of 8 for next digit
        base *= 8; 
    }

    printf("Decimal equivalent: %d\n", decimalNum);

    return 0;
}
Output:
Enter an octal number: 127
Decimal equivalent: 87

Time Complexity: O(log N)
Space Complexity: O(1)

0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents