R4R
Right Place For Right Person TM
 
R4R C C ExamplesInput a number and sum its digits
previous

Home

Next

Learn C with example

Input a number and sum its digits

In this example we are going to find digits of a number and then add these digits to find the sum of digits.

In this we are including two header library files and five predefined  functions. In this example we first take number then find there digits and then add these digits to find sum in while loop.

To find digits we just find the modulo of 10 .This will gives last digit .Then add it into another variable(r). To find next digit we need to cut last digit so divide by 10 and store it into a varaible(i). Repeat while loop until  i in not equals to zero.

Then finally print the sum(r).

/* input a number and sum its digit */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,p,r=0;
clrscr();
printf("\nEnter a number to sum its digit :\t");
scanf("%d",&i);
while(i!=0)
{
p=i%10;
r=r+p;
i=i/10;
}
printf("The sum of digit\t:%d",r);
getch();
}

Output Of Example

Enter a no to which you have to sum digit: 1234
The sum of digit :10
previous

Home

Next


Tolal:0 Click:
Show All Comments

Post Your Comments

Your Name:

Your Email ID :
Comments :
URL
  =* Enter SUM

Tutorials,Examples,Questions and Answer

R4R
R4R
R4R
R4R
R4R
R4R
R4R
R4R