Saturday, April 18, 2009

Program to find the sum of last and first digit of a four digit number

Exercise 10

If a four digit number is input through a keyboard, write a program to obtain the sum of the first and last digit of this number.

Solution:

#include<stdio.h>
#include<conio.h>


void main()
{
int n, i, sum=0;
printf(“Enter a four digit number: ”);
scanf(“%d”, &n);
/* The logical part of the program */
sum=sum+(n%10);
for(i=1; i<4; i++)
n=n/10;
sum=sum+n;
printf(“\nThe sum of the last and first digit of the four digit No. = %d”, sum);
getch();
}

In this program the last number is been extracted by finding the remainder by dividing by 10. And then the number is divided thrice by 10, thus we get the first digit of the number and then adding it with the sum, which already contains the last digit.
The logical part of the program is solved with the truth table of the program:
Let us assume that the user has inputted the value of n=4793, and the declared value of sum=0
initial condition n=4793 sum=0 + (4793%10) = 0 + 3 =3
i = 1 n=4793/10=479 sum=3
i = 2 n=479/10=47 sum=3
i = 3 n=47/10=4 sum=3+4=7

So, we find that at the end of the truth table the value of sum = 7 (first digit + last digit)
The output of the program is as follows:
Enter a four digit number: 4793
The sum of the last and first digit of the four digit No. = 7

2 comments:

  1. fab code jst amazing thanks a lot

    ReplyDelete
  2. yo yo bro thanks for the fast delivery

    ReplyDelete

Please give your valuable comments or queries if you fell its helpful or if you like the contents of the site. Thanks...