#include <stdio.h>int main(){ int num; int sum=0, rev=0; printf("Enter a number"); scanf("%d", &num); while(num>0) { sum=sum + num%10; rev=rev*10 + num%10; num=num/10; } printf("sum=%d\n", sum); printf("reverse=%d\n", rev); return 0;}
Question
#include <stdio.h>int main(){ int num; int sum=0, rev=0; printf("Enter a number"); scanf("%d", &num); while(num>0) { sum=sum + num%10; rev=rev*10 + num%10; num=num/10; } printf("sum=%d\n", sum); printf("reverse=%d\n", rev); return 0;}
Solution
This is a simple C program that takes an integer input from the user, calculates the sum of its digits, reverses the number, and then prints both the sum and the reversed number.
Here's a step-by-step explanation:
-
The program starts with the inclusion of the standard input-output library using
#include <stdio.h>. -
The
main()function is declared, which is the entry point of the program. -
Inside the
main()function, three integer variablesnum,sum, andrevare declared.numis for storing the user input,sumis for storing the sum of the digits, andrevis for storing the reversed number. -
The program then prompts the user to enter a number using
printf("Enter a number"). -
The entered number is read and stored in the
numvariable usingscanf("%d", &num). -
A
whileloop is used to iterate through each digit of the number. The condition for the loop to run isnum>0, which means the loop will continue untilnumbecomes 0. -
Inside the loop, the last digit of
numis added tosumandrevis multiplied by 10 and the last digit ofnumis added to it. This effectively reverses the number. -
numis then divided by 10 to remove the last digit. This process continues untilnumbecomes 0. -
After the loop ends, the sum of the digits and the reversed number are printed using
printf(). -
The program then returns 0 and ends.
Similar Questions
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.