I need to sum the digits of a number entered by the user.
For example:
- If the input equal to 20, make 2 + 0 = 2
- If the input equals 45, make 4 + 5 = 9
VisualG and C can be used.
I need to sum the digits of a number entered by the user.
For example:
VisualG and C can be used.
Use the rest of the division for 10:
int resto= 20 % 10; //obtem o resto da divisão por 10
int valorSemDireita= 20 / 10; //Como é um inteiro vai retirar o nº da direita
resultado= resto + valorSemDireita;
Assuming this entry number can range from 0 to several decimal places.
The logic to solve the problem would be to individually divide the number by 10 until it reaches 0;
Then the code can look like this:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
int a,soma=0,aux;
printf("Digite um numero:");
scanf("%d",&a);
while(a!=0)
{
aux=a%10;
a=a/10;
soma+=aux;
}
printf("\nA soma dos digitos eh:%d",soma);
}