#include <stdio.h>

int main() 
{
    int originalNumber, reversedNumber = 0, remainder;

    // Get user input
    printf("Enter an integer: ");
    scanf("%d", &originalNumber);

    // Reverse the number
    while (originalNumber != 0) 
   {
        remainder = originalNumber % 10; // Get the last digit
        reversedNumber = reversedNumber * 10 + remainder; // Shift and add the digit
        originalNumber /= 10; // Remove the last digit
    }

    // Display the result
    printf("Reversed Number: %d\n", reversedNumber);

    return 0; // Indicate successful completion
}

Explanation

Including Libraries:

Including Libraries:

c

#include <stdio.h>

This line includes the standard input-output library, allowing us to use functions like printf and scanf.

Main Function:

c

int main() { ... }

This is the entry point of our program. It returns an integer value indicating how the program finished.

Variable Declaration:

c

int originalNumber, reversedNumber = 0, remainder;

Here, originalNumber stores the number input by the user, reversedNumber will hold the reversed result, and remainder is used to temporarily store each digit.

User Input:

c

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

We prompt the user to enter an integer and read that value into originalNumber.

Reversing the Number:

c

while (originalNumber != 0) {
remainder = originalNumber % 10; // Extract last digit
reversedNumber = reversedNumber * 10 + remainder; // Build reversed number
originalNumber /= 10; // Remove last digit
}

This loop runs until there are no digits left in originalNumber. Inside the loop:

We get the last digit using the modulus operator.
We update reversedNumber by shifting its current digits left and adding the last digit.
Finally, we remove the last digit from originalNumber.

Displaying the Result:

c

printf("Reversed Number: %d\n", reversedNumber);

After reversing, we print the final result.

Output

Enter an integer: 1234
Reversed Number: 4321

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights