C Program To Find Reverses Of Given Number

Table of contents

#include <stdio.h>

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

    while(n>0) {
        reverse = reverse*10 + n%10;
        n /= 10;
    }
    printf("Reversed number = %d", reverse);
    return 0;
}

This program uses a single while loop and eliminates the extra variable remainder. The program works the same way as the previous one. The user is prompted to enter an integer, which is stored in the variable n. The while loop continues as long as n is greater than 0. In each iteration, the reverse variable is updated by adding the last digit of n obtained by n%10 and multiply it by 10. Finally, n is updated by dividing it by 10, which removes the last digit. After the while loop, the reversed number is printed.

EXPLANATION :

  1. The program prompts the user to enter an integer: "Enter an integer: "

  2. The user enters the integer 12345

  3. The program begins executing the while loop:

    • In the first iteration, the value of n is 12345. The value of reverse is updated to be reverse * 10 + n % 10 which is 0 * 10 + 12345 % 10 = 5. The value of n is updated to be n / 10 which is 12345 / 10 = 1234.

    • In the second iteration, the value of n is 1234. The value of reverse is updated to be reverse * 10 + n % 10 which is 5 * 10 + 1234 % 10 = 54. The value of n is updated to be n / 10 which is 1234 / 10 = 123.

    • In the third iteration, the value of n is 123. The value of reverse is updated to be reverse * 10 + n % 10 which is 54 * 10 + 123 % 10 = 543. The value of n is updated to be n / 10 which is 123 / 10 = 12.

    • In the fourth iteration, the value of n is 12. The value of reverse is updated to be reverse * 10 + n % 10 which is 543 * 10 + 12 % 10 = 5432. The value of n is updated to be n / 10 which is 12 / 10 = 1.

    • In the fifth iteration, the value of n is 1. The value of reverse is updated to be reverse * 10 + n % 10 which is 5432 * 10 + 1 % 10 = 54321. The value of n is updated to be n / 10 which is 1 / 10 = 0.

    • Since the value of n is 0, the condition of the while loop is no longer true and the loop exits.

  4. The program prints the final value of reverse which is 54321: "Reversed number = 54321"

So the output will be "Reversed number = 54321"

Note that the input can be any integer, The output will be the reversed version of the input number.