//Program to print the sum of digits -of any number using for loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,sum=0,rem;
printf ("Enter the number ") ;
scanf ("%d",&n) ;
for( ;n>0;n/=10)
{
rem=n%10; /*taking last digit of number*/
sum+=rem;
}
printf("Sum of digits = %d\n",sum) ;
//printf("Hello world!\n");
return 0;
}
program2:
#include<stdio.h>
int sum(int n);
void main()
{
int num;
printf ("Enter the number ") ;
scanf("%d",&num) ;
printf("Sum of digits of %d is %d\n", num, sum(num));
}
int sum (int n)
{
int i, sum=0, rem;
while(n>0)
{
rem=n%10;
sum+=rem;
n/=10;
}
return(sum);
/*rem takes the value of last digit*/
/*skips the last, digi t of number*/
}
output:
enter the number:12
sum of the digits of the 12 is 3
3
PYTHON code:
def main():
sum1=rem=0
n=int(input("enter the number"))
for i in range(n):
if n>0:
rem=n%10
sum1=sum1+rem
n=n//10
print(sum1)
if __name__ == '__main__':
main()
output:
enter the number:264
output:10
No comments:
Post a Comment