Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.607221'
Loops: While III.
Loops: While III.
Task: Reverse a positive integer:
Write a C program that prompts the user to enter a positive integer and reverses its digits using a while loop. Display the result using printf().
Hint: 1021%10=1 (%10, modulo division gives the last digit)
1021/10=102 (/10, integer division cuts the last digit)
Try to cut and build the reverse number
Solution
#include
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Invalid input. Please enter a positive integer.\n");
return 0;
}
int reverse = 0;
while (number != 0) {
reverse = reverse * 10 + number % 10;
number /= 10;
}
printf("The reverse of %d is %d.\n", number, reverse);
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter a positive integer. The scanf() function is used to scan the input from the user and store it in the number variable. The program checks if the number is negative. If it is negative, it prints an error message and terminates the program. Otherwise, it initializes the reverse variable to 0. The while loop continues as long as number is not equal to 0. In each iteration, it multiplies reverse by 10 and adds the rightmost digit of number using the modulus operator (%). Then, it divides number by 10 to remove the rightmost digit. Once number becomes 0, the loop terminates. Finally, it uses printf() to display the result.