write a program to find the sum of digits of 4 digit number using for loop in c language.
Answers
Answered by
2
Answer:
For example, if the input is 98, the variable sum is 0 initially
98%10 = 8 (% is modulus operator, which gives us the remainder when 98 is divided by 10).
sum = sum + remainder
so sum = 8 now.
98/10 = 9 because in C language, whenever we divide an integer by another one, we get an integer.
9%10 = 9
sum = 8 (previous value) + 9
sum = 17
9/10 = 0.
So finally, n = 0, the loop ends; we get the required sum.
Happy new year all of you
Answered by
0
The code to execute the given task is as follows:-
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int copyOfn = n;
int sumOfDigits = 0;
for(; copyOfn > 0; copyOfn /= 10) {
sumOfDigits += (copyOfn %10);
}
printf("Sum of digits of %d is %d", n, sumOfDigits);
return 0;
}
- First, we take a 4-digit number as input from the user in variable 'n'.
- We then copy the value 'n' in another variable 'copyOfn'.
- We run a for-loop till the value of copyOfn is greater than 0.
- We then calculate the sum of digits of the n in the for-loop.
- We then print the sum of digits calculated.
#SPJ3
Similar questions