The code takes an integer input from the user and reverses it using a while loop.

First, it declares two variables - 'n' and 'sum'.

Then, it takes an integer input from the user and stores it in 'n' using the 'scanf' function.

Next, it enters a while loop which continues as long as 'n' is not equal to 0.

Inside the loop, it multiplies 'sum' by 10 and adds the remainder when 'n' is divided by 10. This effectively shifts the digits of 'sum' one place to the left and adds the last digit of 'n' to the ones place of 'sum'.

Then, it divides 'n' by 10 to remove the last digit.

Finally, it prints the reversed integer by using the 'printf' function to output the value of 'sum'.

Note that there is a mistake in the code - the line 'n/10' should be 'sum/10' to update the value of 'sum'. Therefore, the corrected code should be:

#include<stdio.h>
int main() {
    int n,sum=0;
    scanf("%d",&n);
    while(n!=0) {
        sum=sum*10+n%10;
        n/=10; // corrected line
    }
    printf("%d",sum);
}
C Program to Reverse an Integer: Explained with Code

原文地址: https://www.cveoy.top/t/topic/op8f 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录