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

C Language Examples - Finding the Largest Element in an Array

C Language Examples - Finding the Largest Element in an Array

C Language Examples C Language Examples

Find the largest element value in an array.

Example 1

#include

<

stdio.h

int

main

(

)

{

int

array

[

10

]

=

{

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

0

}

;

int

loop

,

largest

;

largest

=

array

[

0

]

;

for

(

loop

=

1

;

loop

<

10

;

loop

++

)

{

if

(

largest

<

array

[

loop

]

)

largest

=

array

[

loop

]

;

}

printf

(

"

The largest element is %d

"

,

largest

)

;

return

0

;

}

The output is:



最大元素为 9

User-defined output:

Example 2

#include

<

stdio.h

int

main

(

)

{

int

i

,

n

;

float

arr

[

100

]

;

printf

(

"

Enter the number of elements (0~100):

"

)

;

scanf

(

"

%d

"

, &

n

)

;

printf

(

"

\

n

"

)

;

// Receive user input

for

(

i

=

0

;

i

<

n

; ++

i

)

{

printf

(

"

Enter number %d:

"

,

i

1

)

;

scanf

(

"

%f

"

, &

arr

[

i

]

)

;

}

// Loop and store the largest element in arr[0]

for

(

i

=

1

;

i

<

n

; ++

i

)

{

// To find the minimum value, you can replace < with >

if

(

arr

[

0

]

<

arr

[

i

]

)

arr

[

0

]

=

arr

[

i

]

;

}

printf

(

"

The largest element is = %.2f

"

,

arr

[

0

]

)

;

return

0

;

}

The output is:



输入元素个数(0~100): 4



输入数字 1: 12

输入数字 2: 23

输入数字 3: 1 

输入数字 4: 3

最大元素为 = 23.00

C Language Examples C Language Examples