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

C Exercise 1

C Exercise 1

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Given the four digits 1, 2, 3, and 4, how many three-digit numbers with distinct digits and no repetitions can be formed? What are they?

**Analysis:** The digits that can be placed in the hundreds, tens, and units positions are all 1, 2, 3, and 4. Generate all permutations, then remove those that do not meet the condition.

Example

#include

<

stdio.h

int

main

(

)

{

int

i

,

j

,

k

;

printf

(

"

\

n

"

)

;

for

(

i

=

1

;

i

<

5

;

i

++

)

{

// The following is a triple nested loop

for

(

j

=

1

;

j

<

5

;

j

++

)

{

for

(

k

=

1

;

k

<

5

;

k

++

)

{

// Ensure that i, j, and k are all different

if

(

i

!=

k

&&

i

!=

j

&&

j

!=

k

)

{

printf

(

"

%d,%d,%d

\

n

"

,

i

,

j

,

k

)

;

}

}

}

}

}

The output of the above example is:



1,2,3

1,2,4

1,3,2

1,3,4

1,4,2

1,4,3

2,1,3

2,1,4

2,3,1

2,3,4

2,4,1

2,4,3

3,1,2

3,1,4

3,2,1

3,2,4

3,4,1

3,4,2

4,1,2

4,1,3

4,2,1

4,2,3

4,3,1

4,3,2

100 Classic C Language Examples 100 Classic C Language Examples