Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 29

C Exercise 29

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Given a positive integer with no more than 5 digits, requirements: 1) find how many digits it has, 2) print its digits in reverse order.

**Program Analysis:** Learn to break down each digit, as explained below.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

int

main

(

)

{

long

a

,

b

,

c

,

d

,

e

,

x

;

printf

(

"

Please enter a 5-digit number:

"

)

;

scanf

(

"

%ld

"

,&

x

)

;

a

=

x

/

10000

;

/*

Extract the ten-thousands digit

*/

b

=

x

%

10000

/

1000

;

/*

Extract the thousands digit

*/

c

=

x

%

1000

/

100

;

/*

Extract the hundreds digit

*/

d

=

x

%

100

/

10

;

/*

Extract the tens digit

*/

e

=

x

%

10

;

/*

Extract the ones digit

*/

if

(

a

!=

0

)

{

printf

(

"

For a 5-digit number, the reverse is: %ld %ld %ld %ld %ld

\

n

"

,

e

,

d

,

c

,

b

,

a

)

;

}

else

if

(

b

!=

0

)

{

printf

(

"

For a 4-digit number, the reverse is: %ld %ld %ld %ld

\

n

"

,

e

,

d

,

c

,

b

)

;

}

else

if

(

c

!=

0

)

{

printf

(

"

For a 3-digit number, the reverse is: %ld %ld %ld

\

n

"

,

e

,

d

,

c

)

;

}

else

if

(

d

!=

0

)

{

printf

(

"

For a 2-digit number, the reverse is: %ld %ld

\

n

"

,

e

,

d

)

;

}

else

if

(

e

!=

0

)

{

printf

(

"

For a 1-digit number, the reverse is: %ld

\

n

"

,

e

)

;

}

}

The output of the above example is:



请输入 5 位数字:12345

为 5 位数,逆序为: 5 4 3 2 1

100 Classic C Language Examples 100 Classic C Language Examples