C Exercise 5
100 Classic C Language Examples
**Problem:** Enter three integers x, y, z and output these three numbers from smallest to largest.
**Program Analysis:** We want to put the smallest number in x. First compare x with y; if x>y, swap the values of x and y. Then compare x with z; if x>z, swap the values of x and z. This makes x the smallest.
Example 1
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
int
main
(
)
{
int
x
,
y
,
z
,
t;
printf
(
"
\
n Please enter 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 from smallest to largest: %d %d %d
\
n
"
,
x
,
y
,
z
)
;
}
The output of the above example is:
Please enter three numbers:
1
3
2
从小到大排序: 1 2 3
Example 2
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
// Swap the values of two variables
void
swap
(
int
a
,
int
b
)
{
int
temp
=
a
;
a
=
b
;
b
=
temp
;
}
int
main
(
)
{
int
a
,
b
,
c
;
printf
(
"\nPlease enter three numbers:\n"
)
;
scanf
(
"%d %d %d"
,
&
a
,
&
b
,
&
c
)
;
if
(
a
b
)
{
swap
(
&
a
,
&
b
)
;
}
if
(
a
c
)
{
swap
(
&
a
,
&
c
)
;
}
if
(
b
c
)
{
swap
(
&
b
,
&
c
)
;
}
printf
(
"Sorted from smallest to largest: %d %d %d\n"
,
a
,
b
,
c
)
;
return
0
;
}