Find the maximum and minimum values in an array in C language

Enter 10 numbers in an array (can be customized), find out the maximum and minimum values, and then output the maximum and minimum values

1. Direct comparison to find the maximum and minimum values

First set up max and min to be initialized to a[0] (the first number), and then compare them in turn. If it is small, then min is assigned a[i], and if it is large, max is assigned a[i].

#include<stdio.h>
int main()
{
	int a[10];
	for (int i = 0; i < 10; i++)//输入10个数字
		scanf("%d", &a[i]);

	int max = a[0];//最大值初始化为a[0]
	for (int i = 1; i < 10; i++)
	{
		if (max < a[i])
			max = a[i];
	}
	int min = a[0];
	for (int i = 1; i < 10; i++)
	{
		if (min > a[i])
			max = a[i];
	}
	printf("%d %d", max,min);
}

The result is as follows:

2. Sort and output the maximum and minimum values.

First pass the sorting method (bubble sorting, insertion sorting, etc.), first arrange the order, and then directly output the maximum and minimum values

code show as below:

#include<stdio.h>
int main()
{
	int a[10];
	for (int i = 0; i < 10; i++)//输入10个数字
		scanf("%d", &a[i]);
	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9-i; j++)//先排序
		{
			if (a[j] > a[j+1]) {
				int temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
		}
	}
	for (int i = 0; i < 10; i++)//逐个输出数组
		printf("%d ", a[i]);
	printf("\n%d %d", a[0], a[9]);//输出最大值、最小值
}

The result is as follows:

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/127990070