Tuesday, 5 August 2014

Sum of Two Numbers..

Calculate Sum Of Digits

Sum Of Digits means add all the digites of any number, for example we take any number like 358. Its sum of digits is 3+5+8=16. Using given code we can easily find sum of digites of any number.
/*****************************************************
			 Calculate Sum Of Digits
******************************************************/

#include< stdio.h>
#include< conio.h>
void main()
{
int a,no,sum=0;
clrscr();
printf("enter any num : ");
scanf("%d",&no);
while(no>0)
{
a=no%10;
no=no/10;
sum=sum+a;
}
printf("\nSum of Digits : %d",sum);
getch();
}
Output
Enter any number : 584
Sum of Digits : 17

Explanation of program

a=no%10;
Here we find remainder of given number, using Modulo Operator we find remainder of any number, Using this step we get only last digits.
a=no/10;
Here After dividing any number by 10 we get all digits except last digits.
Sum=Sum+a;;
Using this statement we find sum of all digits. In first iteration it add 0 and last digits and store in Sum variable, in second iteration it add Previous sum values and last digits of new number and again store in Sum variable, and so on upto while condition is not false.

No comments:

Post a Comment

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...