Skip to content
doubtly

2 answers

Best answer

Answer: Repeatedly take the last digit (n % 10), append it to rev (rev = rev × 10 + digit) and drop it from n (n = n / 10).

Logic (n = 123): rev = 3, then 32, then 321; the loop stops when n becomes 0.

Program:

#include <stdio.h>

int main()
{
    int n, rev = 0, digit;

    printf("Enter an integer: ");
    scanf("%d", &n);

    while (n != 0)
    {
        digit = n % 10;          /* last digit */
        rev = rev * 10 + digit;  /* append it to rev */
        n = n / 10;              /* remove last digit */
    }

    printf("Reversed number = %d\n", rev);

    return 0;
}

Sample output (actual run):

Enter an integer: 12345
Reversed number = 54321
Doubtly · 23 Apr 2022 Report
Was this answer helpful?

Answer: repeatedly take the last digit with % 10, append it to the reversed number, and drop it with / 10.

#include <stdio.h>

int main() {
    int n, rev = 0, digit;
    printf("Enter an integer: ");
    scanf("%d", &n);

    while (n != 0) {
        digit = n % 10;          /* last digit        */
        rev = rev * 10 + digit;  /* append it to rev  */
        n = n / 10;              /* remove last digit */
    }

    printf("Reversed number = %d\n", rev);
    return 0;
}

Trace for 1234:

  • digit 4 → rev = 4, n = 123
  • digit 3 → rev = 43, n = 12
  • digit 2 → rev = 432, n = 1
  • digit 1 → rev = 4321, n = 0 (loop stops)

Output: Reversed number = 4321. In C the % and / operators keep the sign, so a negative input like −123 gives −321.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.