Sorting Using 3 Variables in C Language
Learn, how you can sort values using three variables easily. However, there are many methods you can do it from here is the one.
After including the library and creating the main method.
1. First, we'll declared three variables 'n1', 'n2' , 'n3' and temporary variable 'temp'
2. Then, we'll be taking input from users in these three variables, 'n1', 'n2', 'n3'
3. After that we're using the if-else condition to swap variables:
if n1 is greater than n2, then we're swapping the value using the temporary variable
if n2 is greater than n3, then we're swapping the value using the temporary variable
if n1 is greater than n3, then we're swapping the value using the temporary variable
4. After all the swapping we're printing the value after swapping.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
void main(){ | |
int n1, n2, n3 , temp; | |
printf("Enter First Number"); | |
scanf("%d", &n1); | |
printf("Enter Second Number"); | |
scanf("%d", &n2); | |
printf("Enter Third Number"); | |
scanf("%d", &n3); | |
if(n1 > n2) | |
{ | |
temp = n1; // 20 <== 20 | |
n1 = n2; // 30 <== 30 | |
n2 = temp; // 20 <== 20 | |
} | |
if(n2 > n3) | |
{ | |
temp = n2; | |
n2 = n3; | |
n3 = temp; | |
} | |
if(n1 > n3) | |
{ | |
temp = n1; | |
n1 = n3; | |
n3 = temp; | |
} | |
printf("The sorted numbers are: %d \n %d \n %d", n1 , n2 , n3); | |
} |
Comments
Post a Comment