Objective
The modulo operator, %
, returns the remainder of a division. For example, 4 % 3 = 1
and 12 % 10 = 2
. The ordinary division operator, /
, returns a truncated integer value when performed on integers. For example, 5 / 3 = 1
. To get the last digit of a number in base 10, use as the modulo divisor.
Task
Given a five digit integer, print the sum of its digits.
Input Format
The input contains a single five digit number, .
Constraints
Output Format
Print the sum of the digits of the five digit number.
Sample Input 0
10564
Sample Output 0
16
HackerRank Sum of Digits of a Five Digit Number Solution in C (Sample-1)
#include <stdio.h>
int main() {
int n, sum = 0;
scanf("%d", &n); // Read the 5-digit number
// Extract digits and sum them
while (n > 0) {
sum += n % 10; // Add last digit
n /= 10; // Remove last digit
}
printf("%d\n", sum); // Print the result
return 0;
}
HackerRank Sum of Digits of a Five Digit Number Solution in C (Sample-2)
#include <stdio.h>
#include <string.h>
int main() {
char num[6]; // 5 digits + 1 null terminator
int sum = 0;
scanf("%s", num);
for (int i = 0; i < 5; i++) {
sum += num[i] - '0'; // Convert char to int
}
printf("%d\n", sum);
return 0;
}
0 Comments