Loop Assignment 15 β€” Octal to Decimal Conversion Using For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Convert an Octal Number to Decimal Using a For Loop

πŸ“‘ On this page:
  • Same Idea, Different Multiplier
  • Base 8 Place Values
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
πŸ“š In this program, you will learn:
  • How octal-to-decimal conversion is the same pattern as binary-to-decimal, with a different multiplier
  • Why the place value multiplies by 8 (not 2 or 10) each iteration
  • How octal digits are always 0-7 β€” and why any digit of 8 or 9 makes the input invalid
  • How n % 10 works here just as it did for binary β€” because octal digits happen to be valid decimal digits
  • How the same skeleton handles hex conversion once you switch to string input

Same Idea, Different Multiplier

If you've done the binary-to-decimal program from assignment 14, this one will feel like a small variation. The structure is identical: read a number, loop over its digits, multiply each digit by the current place value, add it to an accumulator, and double the place value each iteration. The only change is the multiplier.

For binary, the place value doubles (multiplied by 2 each iteration): 1, 2, 4, 8, 16, 32, … For octal, the place value multiplies by 8: 1, 8, 64, 512, 4096, 32768, … For decimal (base 10), the place value would multiply by 10: 1, 10, 100, 1000, … That's what makes base-10 so natural to us β€” we've memorised the multipliers. For octal, the multipliers grow faster, so octal numbers are shorter but their decimal equivalents grow quickly.

A quick intuition: octal 777 = 7Γ—64 + 7Γ—8 + 7Γ—1 = 448 + 56 + 7 = 511. So the "largest three-digit octal number" is 511 in decimal, not 999. Octal representation is compact but not nearly as compact as it looks at first glance. In fact, octal was historically used in computing as a shorthand for binary β€” three octal digits pack exactly one byte's worth of bits (0-511), and every octal digit corresponds to exactly three binary digits (000-111). That correspondence is why octal was popular in the era of 12-bit and 36-bit machines.

πŸ’‘ In one line: for each octal digit d (right to left), add d Γ— place to a running total, then multiply place by 8. Start at place = 1.

Diagram showing the octal number 745 broken into place values 64, 8, 1 with each digit contributing to a decimal sum of 485

Base 8 Place Values

The algorithm differs from binary-to-decimal in exactly one line: place *= 8 instead of place *= 2. Everything else is identical. That's the point of a well-designed pattern β€” the specifics (which base) live in one place, and the skeleton stays stable.

  1. Read the octal number as an integer. Validate non-negativity.
  2. Initialise decimal = 0 and place = 1.
  3. Loop while n > 0:
    • Extract the last digit: digit = n % 10.
    • Validate: digit must be 0-7. Octal has no digit 8 or 9.
    • Add digit Γ— place to decimal.
    • Multiply the place value: place *= 8.
    • Remove the last digit: n /= 10.
  4. Print decimal.

The validation step is new compared to binary β€” not because octal digits are harder to check, but because octal has more valid digits (0 through 7), so there's a wider range to accept and reject. If the user enters 1089, that's not octal (8 and 9 aren't valid octal digits), and the program should say so clearly rather than computing a nonsense value.

Octal Calculation Decimal Note
000Zero is zero in both bases
77Γ—17Single digit β€” max is 7
101Γ—8 + 0Γ—18First two-digit octal
171Γ—8 + 7Γ—115Notice 17 in octal is 15 in decimal
1001Γ—6464First three-digit octal
7457Γ—64 + 4Γ—8 + 5Γ—1485Worked example
7777Γ—64 + 7Γ—8 + 7Γ—1511Largest three-digit octal

The row for octal 17 is worth pausing on. In decimal, 17 is seventeen. In octal, 17 is fifteen (1Γ—8 + 7). Same digits, different value β€” because the multiplier for the second position is 8, not 10. This is the kind of subtlety that catches beginners: they see "17" and assume the value is 17, but the program computes 15. Being explicit about the base at every step is the way to avoid confusion.

Complete C Program

Program: octal to decimal using a for loop

#include <stdio.h>

int main(void) {
    long long n;

    printf("Enter an octal number (digits 0-7 only): ");
    if (scanf("%lld", &n) != 1 || n < 0) {
        printf("Invalid input. Please enter a non-negative octal number.\n");
        return 1;
    }

    long long original = n;    /* keep for display */
    long long decimal = 0;
    long long place = 1;

    /* The for loop's three parts: no initializer (n already set),
       condition n > 0, update n /= 10 */
    for (; n > 0; n /= 10) {
        int digit = n % 10;
        if (digit < 0 || digit > 7) {
            printf("Invalid octal digit %d β€” octal digits are 0-7 only.\n", digit);
            return 1;
        }
        decimal += digit * place;
        place *= 8;
    }

    printf("Octal %lld = Decimal %lld\n", original, decimal);
    return 0;
}
                                    

And here's the same logic using strtoll with base 8, which is what production code typically uses:

Alternative: use strtoll with base 8

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char input[64];
    printf("Enter an octal number: ");
    if (scanf("%63s", input) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    char *end;
    long long decimal = strtoll(input, &end, 8);

    if (*end != '\0') {
        printf("Invalid octal number β€” %s contains non-octal digits.\n", input);
        return 1;
    }

    printf("Octal %s = Decimal %lld\n", input, decimal);
    return 0;
}
                                    

Same trade-off as in the binary program β€” the manual loop is instructive, the library version is shorter and safer. Both compute the same result. Use whichever fits the context: manual for the assignment, strtoll when writing real code that needs to convert user-supplied numbers.

Program Output

Enter an octal number (digits 0-7 only): 745
Octal 745 = Decimal 485
                                

A few more to try. Input 17 gives 15 β€” remember, octal 17 is 1Γ—8 + 7 = 15, not 17. Input 100 gives 64. Input 777 gives 511. Input 0 gives 0. Input 7 gives 7. Input 1089 gives an error message because 8 and 9 aren't valid octal digits. Input βˆ’17 gives an error because the input is negative.

Step-by-Step Explanation

Let's trace 745 through the loop, then look at the differences from binary conversion.

1. Reading and validating input

The initial scanf reads the number, and the check n < 0 rejects negatives (there's no standard way to write a negative octal number in this format). The individual-digit validation happens inside the loop, which lets us report the specific invalid digit.

2. Saving the original value

The loop destroys n. Saving original = n before the loop lets the final message print "Octal 745 = Decimal 485" rather than "Octal 0 = Decimal 485".

3. The main loop for 745

Trace:

  1. Start: n = 745, decimal = 0, place = 1
  2. Iteration 1: digit = 5, decimal += 5Γ—1 = 5, place = 8, n = 74
  3. Iteration 2: digit = 4, decimal += 4Γ—8 = 32 (total 37), place = 64, n = 7
  4. Iteration 3: digit = 7, decimal += 7Γ—64 = 448 (total 485), place = 512, n = 0
  5. Loop exits β€” final decimal = 485

Check: 7Γ—64 + 4Γ—8 + 5Γ—1 = 448 + 32 + 5 = 485. Matches.

4. Why the multiplier is 8, not 2 or 10

Each position in an octal number represents a power of 8. The rightmost position is 8⁰ = 1, the next is 8¹ = 8, the next is 8² = 64, and so on. So to convert digit-by-digit, you multiply each digit by the appropriate power of 8. The place variable tracks this power, starting at 1 and multiplying by 8 each iteration. Writing place *= 2 (like the binary program) would give a wrong answer; place *= 8 is the correct multiplier for octal.

5. Why octal digits are 0-7, not 0-9

In base-8 notation, there are exactly 8 symbols used: 0, 1, 2, 3, 4, 5, 6, 7. The digit 8 doesn't exist β€” it's represented as "10" in octal. Similarly, 9 is "11" in octal. So an "octal" input like 1089 is nonsensical β€” it uses digits that don't exist in base 8. The validation catches this and tells the user rather than silently producing garbage.

There's an interesting history here: octal was popular in computing because each octal digit corresponds to exactly three binary digits (bits). One byte (8 bits) is conventionally split as 3-3-2 or two octal digits plus a remainder. On old 12-bit and 36-bit architectures, octal was the natural display format. Modern systems prefer hexadecimal because each hex digit corresponds to exactly four binary digits, which fits bytes more neatly (two hex digits = one byte). But octal still shows up in file permissions on Unix systems β€” the famous chmod 755 is an octal number, meaning rwxr-xr-x.

6. Why n % 10 extracts "octal digits" here

Same reasoning as in the binary program β€” the coincidence works because octal digits are a subset of decimal digits. The user typed "745" as a decimal number (seven hundred forty-five in the C compiler's view). 745 % 10 = 5, 745 / 10 = 74. The loop extracts the decimal digits 5, 4, 7 in that order and treats them as octal digits. Because octal digits are valid decimal digits (0-7), the arithmetic works out. If octal had required a symbol like "A" for ten (which it doesn't, but hexadecimal does for A-F), this approach would break β€” which is exactly why the hexadecimal program (assignment 18) uses string input instead.

7. Overflow considerations

Both n and decimal use long long. A 12-digit octal number like 777777777777 has value 7Γ—(8^11 + 8^10 + ... + 1) = 7Γ—(8^12 βˆ’ 1)/7 = 8^12 βˆ’ 1 = 68,719,476,735, which fits comfortably in long long (max ~9.2 quintillion). For much larger octal numbers, you'd need a big-number library. For the assignment, 12-15 digits is more than sufficient.

🎯 Remember this: octal is just base 8. Each digit contributes digit Γ— place to the decimal value, where place starts at 1 and multiplies by 8 each iteration (right to left). Validate that digits are 0-7. If you've done the binary program, the only change is place *= 8 instead of place *= 2.

Frequently Asked Questions

1. Why does the program treat octal 17 as decimal 15?

Because 17 in base 8 means 1Γ—8 + 7Γ—1 = 15 in base 10. The digits look familiar but the position weights are different. This is the most common source of confusion in base conversion β€” the symbols are the same, but the meaning depends on which base they're interpreted in. Octal 17 is not the same value as decimal 17. The program's job is to translate between the two interpretations.

2. What happens if the input has an 8 or 9 in it?

The program reports an error and stops. In octal, only 0-7 are valid digits β€” an "8" or "9" is meaningless because it doesn't correspond to any single octal digit. The validation if (digit < 0 || digit > 7) catches this. Without the check, the program would compute something (treating "8" as a value of 8Γ—place, which overflows the digit's intended range) β€” a nonsensical answer presented as if valid. The error message is the honest response.

3. Could I convert to hex using the same loop?

Almost β€” but there's a wrinkle. In hexadecimal, digits go from 0 to 15, and for values 10-15 we use letters A-F. Those letters aren't decimal digits, so the n % 10 extraction fails (the user can't type "A" as part of an integer literal). You'd need to read the input as a string and process characters, converting 'A'-'F' to their numeric values 10-15. The skeleton β€” extract digit, multiply by place, add to total, multiply place by 16 β€” is the same, but the digit extraction step needs a string-level approach. Assignment 18 covers this case in detail.

4. Is octal still used today?

Yes, mostly in one specific place: Unix file permissions. The chmod command takes octal numbers like 755 (meaning rwxr-xr-x) or 644 (rw-r--r--). Each octal digit encodes the read/write/execute permissions for one class of user (owner, group, others), so a three-digit octal number describes the entire permission scheme compactly. Beyond that, octal is largely historical β€” most of the C language's early use of octal (like the 0 prefix for octal literals in C) is a legacy of the 1970s computing landscape.

5. Why use long long instead of int?

Octal numbers get large quickly. The largest 10-digit octal number is 7Γ—8⁹ + 7Γ—8⁸ + ... = 8¹⁰ βˆ’ 1 = 1,073,741,823 β€” close to INT_MAX. So a 10-digit octal input can overflow int if it's large enough. Using long long for both n and decimal avoids that concern β€” a 19-digit octal number fits comfortably. And an octal number of 12+ digits, while larger than what int can hold, is still well within long long's range.

6. How would I convert in the other direction (decimal to octal)?

Different algorithm: instead of extracting and multiplying, you divide repeatedly and record remainders. while (n > 0) { digit = n % 8; print digit; n /= 8; } β€” but the digits come out in reverse order, so you either print them in reverse (via an array or recursion) or store them for later. Assignment 16 covers this exact conversion. It's the mirror image of this program: here we're extracting and multiplying, there we'll be dividing and collecting.

πŸ’‘ Tip: After this program, compare it side-by-side with assignment 14 (binary to decimal). The only differences are (a) place *= 8 instead of place *= 2, and (b) the digit validation range is 0-7 instead of 0-1. Everything else is identical. That's the whole idea of a well-designed pattern β€” the base is a parameter, and the rest of the code doesn't care. Once you see that, you can write base-N conversion for any N between 2 and 10 (or beyond, with string input) in a couple of minutes.

πŸ“– Related Tutorials

  • 14. Convert a Binary Number to Decimal Using a While Loop
  • 16. Convert a Decimal Number to Octal Using a Do-While Loop
  • 17. Count the Number of 1s in Binary Representation Using a While Loop
  • 18. Convert a Hexadecimal String to Decimal Using a For Loop
  • 6. Count the Digits in an Integer Using a While Loop
  • C FOR Loop
  • Bitwise Operators
  • All 30 Loop Assignments

Previous Topic: -->> 14. Convert a Binary Number to Decimal Using a While Loop   ||   Next Topic: -->> 16. Convert a Decimal Number to Octal Using a Do-While Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.