Find sum of digits of a given number in C

Code:

With While Loop

#include<stdio.h>
int main()
{
int N,r,sum;
sum=0;
printf("Give a number:");
scanf("%d",&N);
while(N!=0)
{
    r=N%10;
    sum=sum+r;
    N=N/10;
}
printf("%d",sum);
    return 0;
}

With for loop:
Check below I didn’t initialized the for loop,

#include<stdio.h>
int main()
{
int N,r,sum;
sum=0;
printf("Give a number:");
scanf("%d",&N);
for( ;N!=0;N=N/10){
    r=N%10;
    sum=sum+r;
}
printf("%d",sum);
    return 0;
}

For Loop Another:

#include<stdio.h>
int main()
{
int N,r,sum;
printf("Give a number:");
scanf("%d",&N);
for(sum=0;N!=0;N=N/10){
    r=N%10;
    sum=sum+r;
}
printf("%d",sum);
    return 0;
}

 

with do while loop

#include<stdio.h>
int main()
{
int N,r,sum;
sum=0;
printf("Give a number:");
scanf("%d",&N);
do{
    r=N%10;
    sum=sum+r;
    N=N/10;
}while(N!=0);
printf("%d",sum);
    return 0;
}

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.