Q. Write a program to compute the sum of digits of a given integer number
==> For the following program, code goes like this :
/* Program to compute the sum of digits of a given integer number */
#include<stdio.h>
int main()
{
int num,i,j,sum=0;
printf("Enter a number: ");
scanf("%d",&num);
do
{
i=num/10;
j=num%10;
num=i;
sum+=j;
}while(i!=0);
printf("\n The sum of digits is: %d ",sum);
return 0;
}
Output:
How the iteration works? if the user enters 1234 as input.
num i j num sum=0
1234 1234/10=123 1234%10=4 123 0+4=4
123 123/10=12 123%10=3 12 4+3=7
12 12/10=1 12%10=2 1 7+2=9
1 1/10=0 1%10=1 0 9+1=10
I have used Dev CPP to compile this program.
If you are using Turbo C++ IDE, then use conio.h in link section after stdio.h
and use getch(); to hold the output screen, just before the end of main function.
If you have any confusion regarding the program, please, comment below.
Happy Coding !
Thank you
Program to calculate the sum of digits entered by user in C
8:40 PM
C Programs
,
Calculate Compute Sum of digits entered by user in C
,
sum of digits in c
,
sum of digits in integer
Edit
0 comments:
Post a Comment