In this tutorial you will learn about the C program to Swap First and Last Digit of a Number and its application with practical example.
C Program to Swap First and Last Digit of a Number
In this tutorial, we will learn to create a C program that will Swap the First and Last Digit of a Number in C programming
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Arithmetic operations in C programming.
- Operators in C programming.
What is swapping?
In swapping we swap the data of two variables or the data in the variable. In this program, we will swap the first and last digits from each other and print the resultant data of that variable.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
1. Declaring the variables for the program. 2. Taking the input number from the user. 3. Finding the digits in that given number. 4. Passing those variables to the program. 5. Swapping the First and Last Digit of a Number. 6. Printing the resultant number to the user. 7. End the program. |
Swapping the First and Last Digit of a Number
In this program first, we will take the input number from the user. Then we will separate the digits from that number. And at last, we will print that output number
Let us take the example program from the below code for Swap First and Last Digit of a Number.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include <stdio.h> #include <math.h> int main() { //declaring the required variables for the program int no, fdigit, flag, ldigit, x, y, sno; //no = it will hold the input integer value. //x = it will hold the integer value. //y = it will hold the integer value. //fdigit = it will hold the integer value first digit. //ldigit = it will hold the integer valuelast digit. //sno = it will hold the swapped integer value. //Taking the input number from the user. printf("\n Please Enter any number that you wish : "); scanf("%d", & no); //breaking down into seperate digits flag = log10(no); fdigit = no / pow(10, flag); ldigit = no % 10; x = fdigit * (pow(10, flag)); y = no % x; no = y / 10; sno = ldigit * (pow(10, flag)) + (no * 10 + fdigit); //printing the output swapped digits. printf(" \n The number after Swapping First Digit and Last Digit = %d", sno); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- no = it will hold the integer value.
- fdigit = it will hold the integer value.
- ldigit = it will hold the integer value.
- x = it will hold the integer value.
- y = it will hold the integer value.
- sno = it will hold the integer value.
- flag = it will hold the integer value.
Input Number from the user for the program.
Swapping the First and Last Digit of a Number.
Printing output swapped number.