#include <stdio.h>
#include <string.h>
#include <math.h>

// Function to convert octal to decimal
int octalToDecimal(const char *octal) {
    int decimal = 0;  // Variable to store the decimal value
    int length = strlen(octal);  // Get the length of the octal string

    // Loop through each character in the octal string
    for (int i = 0; i < length; i++) {
        // Convert the character to an integer
        int digit = octal[length - 1 - i] - '0';  // Extract digit from right to left
        decimal += digit * pow(8, i);  // Add to decimal value
    }

    return decimal;  // Return the computed decimal value
}

int main() {
    char octal[20];  // Array to hold octal input

    // Get user input
    printf("Enter an octal number: ");
    scanf("%19s", octal);  // Read the octal input

    // Call the conversion function
    int decimal = octalToDecimal(octal);
    printf("Decimal equivalent: %d\n", decimal);  // Print the result

    return 0;  // Indicate successful completion
}

Explanation:

Explanation:

  1. Header Files:
    • #include <stdio.h>: This is for standard input and output functions like printf() and scanf().
    • #include <math.h>: This is used to calculate powers (pow()) in the program, which is necessary to convert octal digits to decimal.
  2. octalToDecimal Function:
    • This function takes an integer as input, which represents the octal number.
    • It initializes two variables: decimalNumber to store the result and i to keep track of the power of 8.
    • The loop runs while octalNumber is not zero.
    • Inside the loop:
      • remainder = octalNumber % 10: This extracts the last digit of the octal number.
      • decimalNumber += remainder * pow(8, i): The digit is multiplied by 8^i and added to the decimal number.
      • octalNumber /= 10: The last digit is removed.
      • i++: This increments the power of 8 for the next digit.
  3. main Function:
    • This is where the execution starts. It first asks the user to input an octal number.
    • Then it calls the octalToDecimal function to perform the conversion and prints the result.

Output:

Enter an octal number: 157
Decimal equivalent: 111

How It Works:

  • When you input 157 (octal), the program treats it as:
    • 7 * 8^0 = 7
    • 5 * 8^1 = 40
    • 1 * 8^2 = 64
    • Total = 7 + 40 + 64 = 111 in decimal.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights