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

C Exercise 67

C Exercise 67

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Input an array, swap the largest element with the first element and the smallest element with the last element, then output the array.

**Program Analysis:** The answer in Tan Haoqiang's book has a problem.

Example

#include

<

stdio.h

#include

<

stdlib.h

void

fun

(

int

s

,

int

n

)

{

int

i

;

int

max

=

s

[

0

]

;

int

a

=

0

;

for

(

i

=

0

;

i

<

n

;

i

++

)

{

if

(

s

[

i

]

max

)

{

max

=

s

[

i

]

;

a

=

i

;

}

}

s

[

a

]

=

s

[

0

]

;

s

[

0

]

=

max

;

int

j

;

int

min

=

s

[

n

1

]

;

int

b

=

n

1

;

for

(

j

=

0

;

j

<

n

;

j

++

)

{

if

(

s

[

j

]

<

min

)

{

min

=

s

[

j

]

;

b

=

j

;

}

}

s

[

b

]

=

s

[

n

1

]

;

s

[

n

1

]

=

min

;

}

void

printf_s

(

int

s

,

int

n

)

{

int

i

;

for

(

i

=

0

;

i

<

n

;

i

++

)

printf

(

"

%d

"

,

s

[

i

]

)

;

printf

(

"

\

n

"

)

;

}

int

main

(

)

{

int

s

[

20

]

;

int

i

,

n

;

printf

(

"

Set the array length (<20):

"

)

;

scanf

(

"

%d

"

,&

n

)

;

printf

(

"

Enter %d elements:

\

n

"

,

n

)

;

for

(

i

=

0

;

i

<

n

;

i

++

)

scanf

(

"

%d

"

,&

s

[

i

]

)

;

fun

(

s

,

n

)

;

printf_s

(

s

,

n

)

;

return

0

;

}

The output result is:

设置数组长度(<20):5 

输入 5 个元素:

12 123 4 65 21

123 12 21 65 4 

100 Classic C Language Examples 100 Classic C Language Examples