Wednesday, December 30, 2009

Hi how are u ?

--
Regards
Amandeep
"GREAT LEADERS ARE MADE, NOT BORN"

www.zanetine.com

Tuesday, December 15, 2009

WAP to find the sum of the digits of a given number

After a long time I am writing a blog post for my own blog. :) . Past few weeks, I was so busy with studies and learning etc. and these days exams are going on. But still I am not able to get rid of my "Love with C". Before the exam of Punjabi and PC computing, I was making C-Programs, instead of preparing those subjects. Well, because its good for me because the program i was wanting to write but never due to my exams i wasn't trying that. I thought i'll take time. But yesterday due to some happenings, I was little frustrated so I just sat in front of computer and started writing the old pending program. I totally involved in program and it gave me desired result. So woooooopy.. :)

Program was, WAP to find the sum of the digits of a given number. Here i wasn't knowing about how to calculate the sum of the digits of a number whose size is not give. Finally i reached at the solution and finished this program.
So here it goes..

/*WAP to find the sum of the digits of a given number.*/


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
long int n,div;
int i,temp,sum=0,length;
char *str;
clrscr();
printf("\nEnter value = ");
scanf("%ld",&n);
ltoa(n,str,10); //converts long int to string
length=strlen(str); //found the length of string
temp=length-1;
div=pow(10,temp);
for(i=0;i<length;i++)>
{
sum+=(n/div)%10;
div=div/10;
}
printf("\n%d",sum);
getch();
}

Alternate Way


void main()
{
long int n,div,temp;
int sum=0;
clrscr();
printf("\nEnter value = ");
scanf("%ld",&n);
while(n>0)
{
  temp=n%10;
  n=n/10;
  sum+=temp;
}
printf("\n%d",sum);
getch();
}



I wish, try this program and if something is wrong in this program then just let me know. If any other idea to make this kind of program even better then also leave a reply with your own idea.

Regards
Amandeep Singh
Powered By Blogger