C Exercises: Accepts a positive integer less than 500 and prints out the sum of the digits of this number
Compute the sum of the digits of an integer less than 500
Write a C program that accepts a positive integer less than 500 and prints out the sum of the digits of this number.
Test data and expected output:
Input a positive number less than 500:
Sum of the digits of 336 is 12
Pictorial Presentation:
Sample Solution:
C Code:
#include <stdio.h>
int main() {
int a, x = 0, y;
// Prompt user for input
printf("Input a positive number less than 500: \n");
// Read the input value
scanf("%d", &a);
y = a;
if (y < 1 || y > 999) {
// Display error message if the number is out of range
printf("The given number is out of range\n");
} else {
// Calculate the sum of the digits
x += y % 10;
y /= 10;
x += y % 10;
y /= 10;
x += y % 10;
// Display the result
printf("Sum of the digits of %d is %d\n", a, x);
}
return 0;
}
Sample Output:
Input a positive number less than 500: Sum of the digits of 347 is 14
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to compute the product of the digits of an integer less than 500.
- Write a C program to calculate the sum of the digits using a recursive approach.
- Write a C program to compute the sum of the digits and check if the result is a prime number.
- Write a C program to sum the digits of a number and then output the reversed sum.
Go to:
PREV : Calculate and display sin(1x)\sin(\frac{1}{x})sin(x1) for a real number xxx.
NEXT : Sum the series 1^4+2^4+4^4+...+m^4.
C programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.