Tuesday 23 July 2013

Chapter 1 Solutions Problem[H][g)

Well, i guess first chapter is pretty basic to understand and it's problems are fairly easy.  i thought to start posting solutions from Chapter 2, but i would like to do some problems of Chapter 1, which i have found tricky.
I am assuming you already have prerequisites that i had suggested. if you don't. kind see my previous post. you would find it there and one more important thing while you reading chapter. i would recommend you to design example programs by yourself. if you can't do them, see the solution by author and then try to make by yourself. it would surely help you to get more familiar with "c".

Solution for Problem [H](g) from 1st chapter.

Question --->If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.(Hint: Use the modulus operator ‘%’)

Solution
This problem can be easily solved using loops, but since author didn't mention loop in this chapter. so, i would solve it simple procedure.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int sum=0,a, num; /* initialization of sum means initially sum would have value 0* /
printf("Enter a Five Digit Number\n");
scanf("%d",&num);
a=num%10; /* % obtains remainder of division */
sum=sum+a; /*initially sum has value 0 and whatever will the value of a, will be added and stored                            in sum */
num=num/10; /* by doing this new value of num will be 10th of original value i.e if num is 93236 .                             new num would be 9323  not 9323.6 since num is an integer variable.*/
a=num%10;
sum=sum+a;
num=num/10;

a=num%10;
sum=sum+a;
num=num/10;

a=num%10;
sum=sum+a;
num=num/10;

a=num%10;
sum=sum+a;
num=num/10; /*option line because by doing this num would become 0* /

printf("Sum of digits of the Number is %d\n",sum);
return 0;
}

No comments:

Post a Comment