C Program To Print 3 Numbers In Ascending Order Using If Else
Sorting numbers is a fundamental operation in programming, allowing data to be arranged in a meaningful sequence. While complex algorithms exist for large datasets, for a small, fixed number of items, simple conditional logic is often sufficient.
In this article, you will learn how to write a C program that takes three numbers as input and prints them in ascending order using if-else conditional statements.
Problem Statement
The challenge is to accept three distinct numerical inputs from a user and display them from the smallest to the largest. This requires a mechanism to compare the numbers and make decisions based on their relative values, a task perfectly suited for if-else constructs in C. The key is to cover all possible orderings of the three numbers to ensure correctness.
Example
Consider the following input and desired output:
- Input: Enter three numbers:
5,2,8 - Output: The numbers in ascending order are:
2, 5, 8
Background & Knowledge Prerequisites
To understand and implement the C program for sorting three numbers, familiarity with the following core C concepts is helpful:
- Basic C Program Structure: Including header files (
#include) and themainfunction. - Input/Output Operations: Using
printf()for displaying text andscanf()for reading user input. - Variables and Data Types: Declaring and using integer variables (e.g.,
int num1;). - Conditional Statements: Understanding
if,else if, andelsefor decision-making logic. - Relational Operators: Using operators like
<,>,<=,>=for comparing values.
Use Cases or Case Studies
Arranging numbers in order has numerous practical applications, even for just three items:
- Ranking Data: Quickly determining the top, middle, and bottom scores in a small competition or survey.
- Simple Game Logic: Identifying the highest or lowest roll of three dice, or ordering players based on initial scores.
- Displaying Options: Presenting a range of prices, sizes, or difficulty levels in a logical sequence.
- Filtering and Validation: Ensuring that three input values adhere to a specific numerical order requirement.
- Finding Extremes: Easily identifying the minimum, maximum, and median values among three inputs without complex algorithms.
Solution Approaches
For printing three numbers in ascending order using if-else, a direct comparison method is efficient and straightforward.
Approach 1: Direct Comparison using Nested If-Else
This approach systematically compares the three numbers to identify their relative order, then prints them in the correct sequence. It involves a series of nested if-else statements to cover all possible permutations.
One-line summary
This method uses conditional logic to determine which of the three numbers is smallest, then the next smallest, and finally the largest, printing them in order.Code example
// Sort Three Numbers in Ascending Order
#include <stdio.h>
int main() {
// Step 1: Declare three integer variables to store the numbers
int num1, num2, num3;
// Step 2: Prompt the user to enter three numbers
printf("Enter three integers: ");
// Step 3: Read the three numbers from the user
scanf("%d %d %d", &num1, &num2, &num3);
// Step 4: Use if-else statements to determine the order and print
printf("The numbers in ascending order are: ");
if (num1 <= num2 && num1 <= num3) {
// num1 is the smallest
printf("%d, ", num1);
if (num2 <= num3) {
printf("%d, %d\\n", num2, num3);
} else {
printf("%d, %d\\n", num3, num2);
}
} else if (num2 <= num1 && num2 <= num3) {
// num2 is the smallest
printf("%d, ", num2);
if (num1 <= num3) {
printf("%d, %d\\n", num1, num3);
} else {
printf("%d, %d\\n", num3, num1);
}
} else {
// num3 is the smallest
printf("%d, ", num3);
if (num1 <= num2) {
printf("%d, %d\\n", num1, num2);
} else {
printf("%d, %d\\n", num2, num1);
}
}
return 0;
}
Sample output
Enter three integers: 17 5 32
The numbers in ascending order are: 5, 17, 32
Enter three integers: 100 20 50
The numbers in ascending order are: 20, 50, 100
Enter three integers: 7 7 2
The numbers in ascending order are: 2, 7, 7
Stepwise explanation
- Include Header: The
stdio.hheader is included for standard input/output functions likeprintfandscanf. - Declare Variables: Three integer variables (
num1,num2,num3) are declared to store the numbers provided by the user. - Get Input: The program prompts the user to enter three integers and uses
scanfto read these values into the declared variables. - First Comparison (Finding the Smallest):
- The outermost
ifcondition(num1 <= num2 && num1 <= num3)checks ifnum1is the smallest among the three. - If
num1is indeed the smallest, it is printed first.
- Nested Comparison (Ordering the Remaining Two):
- Inside the first
ifblock, a nestedif (num2 <= num3)compares the remaining two numbers (num2andnum3). - If
num2is less than or equal tonum3, they are printed in the ordernum2, num3. Otherwise, they are printed asnum3, num2.
- Second Smallest Check:
- The
else if (num2 <= num1 && num2 <= num3)block is executed ifnum1was not the smallest. This checks ifnum2is the smallest. - If
num2is the smallest, it's printed first, and thennum1andnum3are compared to determine their relative order and printed.
- Third Smallest Check:
- The final
elseblock is executed if neithernum1nornum2was the smallest, implyingnum3must be the smallest. -
num3is printed first, and thennum1andnum2are compared and printed in ascending order.
- Return 0: The
mainfunction returns0to indicate successful execution.
Conclusion
Using if-else statements provides a clear and direct way to sort a small, fixed number of items like three integers. This method is easy to understand and implement, making it suitable for scenarios where algorithmic complexity is not a primary concern. While less scalable than loop-based sorting algorithms for larger datasets, its simplicity makes it effective for specific, limited sorting tasks.
Summary
- Read three integer values from the user.
- Employ a series of nested
if-elseconditions to compare the numbers. - Identify the smallest number first, then determine the order of the remaining two.
- Print the numbers sequentially from the smallest to the largest, ensuring ascending order.