Using iterative function print the given number in reverse order in C language

In C programming, reversing a number means printing its digits in reverse order. This can be achieved using an iterative approach with a while loop that extracts digits from right to left and builds the reversed number.

Syntax

int reverse(int number) {
    int reversed = 0;
    while (number > 0) {
        reversed = reversed * 10 + number % 10;
        number = number / 10;
    }
    return reversed;
}

Algorithm

The algorithm to reverse a number using iterative function −

Step 1: Declare variables number and reverse
Step 2: Initialize reverse = 0
Step 3: While number > 0
        (a) reverse = reverse * 10 + number % 10
        (b) number = number / 10
Step 4: Return reverse

Example

Here's a complete program that reverses a number using an iterative function −

#include <stdio.h>

int reverse(int number) {
    int reversed = 0;
    while (number > 0) {
        reversed = reversed * 10 + number % 10;
        number = number / 10;
    }
    return reversed;
}

int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("Reverse of %d is %d
", number, reverse(number)); return 0; }

Output

Enter a number: 356789
Reverse of 356789 is 987653

How It Works

The algorithm works by repeatedly extracting the last digit using the modulo operator (%) and building the reversed number by multiplying the current reversed value by 10 and adding the extracted digit. The original number is then divided by 10 to remove the processed digit.

For example, with input 356789:

  • Iteration 1: reversed = 0*10 + 9 = 9, number = 35678
  • Iteration 2: reversed = 9*10 + 8 = 98, number = 3567
  • And so on until all digits are processed

Conclusion

Using an iterative approach with a while loop is an efficient way to reverse numbers in C. The algorithm has O(log n) time complexity where n is the input number, making it suitable for reversing numbers of any reasonable size.

Updated on: 2026-03-15T13:41:17+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements