C program to add digits of a number: Here we are using modulus operator(%) to extract individual digits of number and adding them.
#include<stdio.h>
void main()
{
int n, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d",&n);
while( n != 0 )
{
remainder = n % 10;
sum = sum + remainder;
n = n / 10;
}
printf("Sum of digits of entered number = %d\n",sum);
getch();
}
void main()
{
int n, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d",&n);
while( n != 0 )
{
remainder = n % 10;
sum = sum + remainder;
n = n / 10;
}
printf("Sum of digits of entered number = %d\n",sum);
getch();
}
output :-
Add digits using recursion :-
#include <stdio.h>
#include<conio.h>
int add_digits(int);
int main()
{
int n, result;
scanf("%d", &n);
result = add_digits(n);
printf("%d\n", result);
getch();
}
int add_digits(int n)
{
static int sum = 0;
if (n == 0)
{
return 0;
}
sum = n%10 + add_digits(n/10);
return sum;
}
No comments:
Post a Comment