Sunday, April 19, 2009

Program to interchange the last and first digit of a four digit number

Exercise 11

A four digit number is entered through the keyboard and the first and the last digit of the number is interchanged, and the new number so formed will be displayed to the user.

Solution:

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


void main()
{
int n, i, n1=0;
clrscr();
printf("Enter a four digit number: ");
scanf("%d", &n);
/* Logical Part of the program */
n1=n1+((n%10)*1000)+((n%1000)-(n%10))+(n/1000);
printf("\nTherefore the reversed first & last digit number= %d", n1);
getch();
}
This program is also a simple one, the logic which is implemented in this program is also very simple.
Let us understand the logic by the truth table:
Let us assume that the user has inputted the value of n = 4697 and n1 is take as 0 in the initial condition.

n1= 0+((4697%10)*1000)+((4697%1000)-(4697%10))+(4697/1000)
n1= 0+(7*1000)+(697-7)+(4)
n1= 0+7000+690+4
n1= 7694

Thus we can see by implementing this simple logic, only the first and the last digit of the inputted number is changed and the middle two digits remain unchanged.
The output of the program is as follows:
Enter a four digit number: 4697
Therefore the reversed first & last digit number= 7694

No comments:

Post a Comment

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