C PROGRAM
Find the sum of digits and reverse of a number |C Program|
Introduction
Factorial calculation is a fundamental concept in mathematics and computer science. This C program calculates the factorial of a given number using an iterative approach. The blog post will discuss factorials, the iterative solution, and provide a detailed explanation of the code.
Code
#include<stdio.h>
#include<conio.h>
void main() {
int n, sum = 0, r = 0, d;
clrscr();
// Input
printf("Enter a number (minimum 3 digits): ");
scanf("%d", &n);
// Digit Sum and Number Reversal
while (n > 0) {
d = n % 10;
sum = sum + d;
r = (r * 10) + d;
n = n / 10;
}
// Output
printf("\nSum of digits = %d", sum);
printf("\nReverse = %d", r);
getch();
}
Output
Enter a number (minimum 3 digits): 12345
Sum of digits = 15
Reverse = 54321
In this example, the user inputs the number 12345. The program then calculates the sum of its digits (1+2+3+4+5 = 15) and reverses the number (54321). The output displays both the digit sum and the reversed number.
You can try running the program with different input numbers to observe how it accurately calculates the sum of digits and reverses the given number. The output will vary based on the user's input.
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console input/output header <conio.h>.
2. Main Function:
Serves as the entry point of the program.
3. Input:
Users input a number with a minimum of 3 digits.
4. Digit Sum and Number Reversal:
The program uses a while loop to iterate through each digit of the number.
It extracts the last digit (d), updates the digit sum (sum), and constructs the reversed number (r).
5. Output:
Displays the sum of digits and the reversed number.
Conclusion
This C program provides a practical example of digit manipulation, showcasing the computation of digit sum and number reversal. Understanding such operations is beneficial for various applications, from simple arithmetic to more complex algorithms.
Feel free to run the program with different input numbers to observe how it accurately calculates the digit sum and reverses the given number. This example offers a glimpse into the world of digit-level operations in programming. Happy coding!
Post a Comment
0 Comments