Beginner Number Problems C

Reverse a Number Program in C

Reverse the digits of an integer in C using a while loop and the % and / operators.

  • TimeO(d),
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

To reverse a number in C, start with reversed = 0. While n is not 0, take the last digit with n % 10, set reversed = reversed * 10 + digit, and remove the last digit with n = n / 10. For 1234 the loop runs four times and gives 4321. It takes O(d) time, where d is the number of digits, and needs no array or string.

while loopModulus and integer divisionBuilding a number digit by digitInteger overflow
1

Problem statement

Write a reverse a number program in C. Given an integer n, print the number with its digits in reverse order.

Use a while loop and the % and / operators. Do not convert the number to a string. For n = 1234 the output is 4321.

Input

An integer n.

Output

The reversed number.

Examples

Example 1
Inputn = 1234
Output4321

Digits come out as 4, 3, 2, 1 and are added to the result in that order.

Example 2
Inputn = 1200
Output21

The reversed digits are 0021. Leading zeros are not stored in an int, so the value is 21.

Constraints

  • The reversed value must fit in an int (up to 2147483647)
  • Use long long for numbers with 10 digits
2

Think before you code

Reveal the questions to ask yourself first
  • Which operator gives you the last digit of a number?
  • Which operator removes the last digit?
  • How do you add a digit to the right end of the number you are building?
3

Hints

Open one at a time — try again after each.
1 Hint 1
n % 10 gives the last digit. 1234 % 10 is 4.
2 Hint 2
n / 10 drops the last digit, because integer division throws away the remainder. 1234 / 10 is 123.
3 Hint 3
reversed * 10 + digit shifts the old digits left and puts the new digit at the end.
4

Approach

Reveal the step-by-step approach

Reverse digits in C: the three steps

Repeat these steps while n is not 0:

Step Code Meaning
1 digit = n % 10; Take the last digit
2 reversed = reversed * 10 + digit; Add it to the right of the result
3 n = n / 10; Remove the last digit from n

The loop stops when n becomes 0, which means every digit has been used. Save the original number in another variable first if you want to print it at the end, because the loop changes n.

Why a while loop?

You do not know the number of digits in advance. A while (n != 0) loop runs exactly once per digit, so it fits better than a for loop with a fixed count. See loops in programming for when to pick each loop.

5

Dry run

Walk through the example step by step

n = 1234, reversed = 0:

Pass | n    | digit = n % 10 | reversed = reversed*10 + digit | n = n / 10
-----+------+----------------+--------------------------------+-----------
1    | 1234 | 4              | 0*10 + 4 = 4                   | 123
2    | 123  | 3              | 4*10 + 3 = 43                  | 12
3    | 12   | 2              | 43*10 + 2 = 432                | 1
4    | 1    | 1              | 432*10 + 1 = 4321              | 0

n is now 0, so the loop stops. The answer is 4321.

6

Solution

Reveal the full C solution
solution.c
#include <stdio.h>

int main(void) {
    int n = 1234;
    int original = n;
    int reversed = 0;

    while (n != 0) {
        int digit = n % 10;
        reversed = reversed * 10 + digit;
        n = n / 10;
    }

    printf("Original number: %d\n", original);
    printf("Reversed number: %d\n", reversed);
    return 0;
}

Output:

Original number: 1234
Reversed number: 4321

The loop runs four times, once per digit. Only three int variables are used.

Reverse a number in C using a function, with user input

Putting the loop in a function lets you reuse it. Here it is also used to check whether the number is a palindrome, which is a common follow-up in labs.

#include <stdio.h>

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

int main(void) {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("Reverse of %d is %d\n", n, reverse(n));
    if (reverse(n) == n) {
        printf("%d is a palindrome number\n", n);
    } else {
        printf("%d is not a palindrome number\n", n);
    }
    return 0;
}
Enter a number: 121
Reverse of 121 is 121
121 is a palindrome number
Enter a number: 5678
Reverse of 5678 is 8765
5678 is not a palindrome number

n inside reverse() is a copy, so the n in main keeps its value.

Trailing zeros, negative numbers and zero

#include <stdio.h>

int main(void) {
    int nums[] = {1200, 7, -456, 0};
    for (int i = 0; i < 4; i++) {
        int n = nums[i], reversed = 0;
        while (n != 0) {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        printf("%d -> %d\n", nums[i], reversed);
    }

    long long big = 1999999999, rev = 0;
    while (big != 0) {
        rev = rev * 10 + big % 10;
        big /= 10;
    }
    printf("1999999999 -> %lld (needs long long)\n", rev);
    return 0;
}
1200 -> 21
7 -> 7
-456 -> -654
0 -> 0
1999999999 -> 9999999991 (needs long long)
  • 1200 gives 21. If you must print 0021, print the digits one by one inside the loop instead of building a number.
  • -456 gives -654. In C99 and later, % keeps the sign of the left operand, so every digit is negative and the result comes out negative too.
  • 0 gives 0. The loop never runs, and reversed stays 0.
  • 1999999999 fits in an int, but its reverse 9999999991 does not. Signed overflow is undefined behaviour in C, so use long long and %lld for such inputs.

The Java version of this problem is on reverse a number without using strings. For more digit programs, see C programs for beginners.

TimeO(d), where d is the number of digits (about log10 n)
SpaceO(1)
7

Review before the interview

Common mistakes

  • Writing reversed = digit * 10 + reversed. The order is reversed * 10 + digit.
  • Forgetting to initialise reversed to 0, so it starts with a garbage value.
  • Printing n after the loop and expecting the original number. The loop has made it 0. Save a copy first.
  • Using while (n > 0), which skips negative numbers completely. Use while (n != 0).
  • Using int when the reversed number can be larger than 2147483647.

Edge cases to test

  • n = 0: the loop does not run and the answer is 0.
  • Single digit: the number is its own reverse.
  • Trailing zeros: 1200 becomes 21, because an int cannot hold leading zeros.
  • Negative input: -456 becomes -654 with while (n != 0).

Interview follow-ups

  • How would you count the digits while reversing?
  • How would you find the sum of the digits using the same loop?
  • How would you print the reversed digits of 1200 as 0021?

Keep practising

Building your programming basics?

CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.

Chat with us