Monday, 28 October 2013

[C Programming] Find Maximum and Minimum number in array of numbers

#include<stdio.h>
#define ARRAY_SIZE 100 /* Define Your ARRAY Size */

int find_max(int input[], int size)
{
  int max, index;
 
  max = input[0];
 
  for (index = 1; index < size; index++)
  {
if (max < input[index])
  max = input[index];
    }
    return max;
}

int find_min(int input[], int size)
{
  int min, index;
 
  min = input[0];
 
  for (index = 1; index < size; index++)
  {
if (min > input[index])
  min = input[index];
    }
    return min;
}

void main()
{
  /* We can dynamically allocate memory for an array using malloc() based on array_size requested from end user*/
  int set_of_numbers[ARRAY_SIZE];
  int size, index;
  int maximum, minimum;
 
  printf("Please enter number list size\n");
  scanf("%d", &size);
 
  if (size <= 0) {
  printf("Please enter valid size\n");
  return;
     }

  printf("Enter numbers\n");
  for (index = 0; index < size; index++)
  scanf("%d", &set_of_numbers[index]);

printf("List of numbers entered by user\n");
  for (index = 0; index < size; index++)
  printf("%d\n", set_of_numbers[index]);
 
  maximum = find_max(set_of_numbers, size);
  minimum = find_min(set_of_numbers, size);
 
  printf("Maximum number: %d\n", maximum);
  printf("Minimum number: %d\n", minimum);
}

Output:
-----------
Please enter number list size
5
Enter numbers
12
34
2
7
8
List of numbers entered by user
12
34
2
7
8
Maximum number: 34
Minimum number: 2

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...