Easy Tutorial
❮ C Examples Reverse Sentence Recursion C Function Ftell ❯

C Practice Example 5

C Language Classic 100 Examples

Question: Input three integers x, y, z and output these three numbers in ascending order.

Program Analysis: We aim to place the smallest number in x. First, compare x with y, and if x > y, swap the values of x and y. Then, compare x with z, and if x > z, swap the values of x and z. This ensures x is the smallest.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include <stdio.h>

int main()
{
    int x, y, z, t;
    printf("\nPlease input three numbers:\n");
    scanf("%d%d%d", &x, &y, &z);
    if (x > y) { /* Swap the values of x and y */
        t = x; x = y; y = t;
    }
    if (x > z) { /* Swap the values of x and z */
        t = z; z = x; x = t;
    }
    if (y > z) { /* Swap the values of z and y */
        t = y; y = z; z = t;
    }
    printf("Sorted in ascending order: %d %d %d\n", x, y, z);
}

The output of the above example is:

Please input three numbers:
1
3
2
Sorted in ascending order: 1 2 3

C Language Classic 100 Examples

❮ C Examples Reverse Sentence Recursion C Function Ftell ❯