7) Write a C program to swap first and last digits of a number.
Answers
Answer:
#include <stdio.h>
#include <math.h>
int main()
{
int n,no_of_digits, fst_digit,lst_digit,temp_a,temp_b,swapped_no
printf("\n Please Enter any Number: ");
scanf("%d", & n);
no_of_digits = log10(n)
fst_digit = n/pow(10,no_of_digits)
lst_digit = n%10
temp_a = fst_digit * pow(10,no_of_digits)
temp_b = n%temp_a
n = temp_b/10
swapped_no = lst_digit *(pow(10,no_of_digits)) + (n*10 + fst_digit)
printf("The Number after Swapping First Digit and Last Digit = %d", swapped_no);
return 0;
}
Explanation:
Here, we are using log10(logarithm of base 10) to count the number of digits of a given number.
Digit count of number is always equal to the upper bound of log10 of the number. i.e
digit_count = upper_bound of log10(Number)
NOTE: logarithm is define only for positive numbers, not defined for negative numbers.
Explanation of above code is given below by taking the example:
Suppose user entered the Number = 1234
no_of_digits = log10(n) = 3
fst_digit = 1234 / pow(10, 3) = 1234 / 1000 = 1.234 = 1
lst_digit = 1234 % 10 = 4
temp_a = fst_digit * (pow(10, no_of_digits))
temp_a = 1 * pow(10, 3) = 1 * 1000 = 1000
temp_b = n % temp_a = 1234 % 1000 = 234
n = 234 / 10 = 23.4 = 23
swapped_no = lst_digit * (pow(10, no_of_digits)) + (n * 10 + fst_digit)
swapped_no = 4 * pow(10, 3) + (23 * 10 + 1)
swapped_no = 4000 + (230 + 1) = 4231