C Program example: Input a number and print sum of its digits

Categories: C Programming language

Input a number and print sum of 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 of 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:

Enter a no to which you have to sum digit: 1234

The sum of digit : 10

Top Blogs
Introduction to Implementation of Queue using Linked List Published at:- Input and Output Functions in C Published at:- Importance of C Programming Language Published at:- How does C Programming Language Work Published at:- History of C Language : Introduction to C Programming Language Published at:- Benefits of C language over other programming languages Published at:- C Language Interview Question and Answers Published at:- Pointer declaration in C ,Address operator Published at:- C Program example: Input a number and print sum of its digits Published at:- What values are printed when we run following? Published at:- C Interview Questions And Answers Published at:- Learn C Programming language with example Published at:- C Memory Management ! Dynamic memory allocation Published at:- Structure in C: Introduction Published at:- Loops in C Published at:- Example of Function with no return type and no argument Published at:- Functions with arguments and no return values. Published at:- Functions with arguments and return values -C Examples Published at:- Functions that return multiple values -C Example Published at:- Types of Function in C ! Library Function in C ! User Defined Function In C ! Function Definition Published at:- C Functions ! What is a Function Published at:-
R4Rin Team
The content on R4Rin.com website is created by expert teams.