21xrx.com
2024-03-28 16:38:43 Thursday
登录
文章检索 我的文章 写文章
C程序在数组中查找最小值
2021-07-07 07:03:15 深夜i     --     --
C

C 程序以查找数组中的最小或最小元素。 它还打印它在整数列表中出现的位置或索引。

如何在数组中找到最小的数?

我们的算法假设第一个元素为最小值,然后将它与其他元素进行比较,如果一个元素小于它,则它成为新的最小值,重复这个过程,直到扫描完完整的数组。

 

C语言求数组中最小的数

#include <stdio.h>


int main()
{
  int array[100], size, c, location = 0;

  printf("Enter number of elements in array\n");
  scanf("%d", &size);

  printf("Enter %d integers\n", size);

  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);

  for (c = 1; c < size; c++)
    if (array[c] < array[location])
      location = c;

  printf("Minimum element is present at location %d and its value is %d.\n", location+1, array[location]);
  return 0;
}

 

程序输出:

如果最小值在数组中出现两次或更多次,则打印它首先出现的索引或最小索引处的最小值。 您可以修改代码以打印出现最小值的最大索引。 您还可以存储数组中出现最小值的所有索引。

下载数组程序中的最小元素。

用函数求最小值的C程序

我们的函数返回出现最小元素的索引。
 

#include <stdio.h>


int find_minimum(int[], int);
 
int main() {
  int c, array[100], size, location, minimum;
 
  printf("Input number of elements in array\n");
  scanf("%d", &size);
 
  printf("Input %d integers\n", size);
 
  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);
 
  location = find_minimum(array, size);
  minimum  = array[location];
 
  printf("Minimum element location = %d and value = %d.\n", location + 1, minimum);
  return 0;
}

int find_minimum(int a[], int n) {
  int c, index = 0;
 
  for (c = 1; c < n; c++)
    if (a[c] < min)
      index = c;

  return index;
}

使用指针的 C 编程代码

#include <stdio.h>


int main()
{
    int array[100], *minimum, size, c, location = 1;
   
    printf("Enter the number of elements in array\n");
    scanf("%d", &size);
   
    printf("Enter %d integers\n", size);
   
    for (c = 0; c < size; c++)
        scanf("%d", &array[c]);
   
    minimum = array;
    *minimum = *array;
   
    for (c = 1; c < size; c++)
    {
        if (*(array+c) < *minimum)
        {
           *minimum = *(array+c);
           location = c+1;
        }
    }
   
    printf("Minimum element found at location %d and it's value is %d.\n", location, *minimum);
    return 0;
}

 

  
  
下一篇: C中的线性搜索

评论区

{{item['qq_nickname']}}
()
回复
回复