C Program to Find Max and Min Using Pointers

    The program receives an array of numbers as input and finds the minimum number and a maximum number using pointers.

    Advertisements

    This program is intended for intermediate level learners familiar with the concept of pointers. If you are not familiar with pointer concepts, visit the link below to learn about pointers with an example.

    C Programming Tutorial – Pointers

    You can also learn about implementing linear search and binary search algorithms, it will strengthen your concepts.

    Learn implementation of Linear Search and Binary Search

    Advertisements

    Problem Definition

    We want to write a program to find the MAX and MIN using pointers in an array of numbers. The program accept 10 numbers from user and store them in an array of integers.

    We then use two pointers to locate the maximum and the minimum of the array. The pointer traverse through all the values of the array and compares it with value of max which is 0 at the beginning.

    If the number in array greater than max current value, then make the new number as new max value, otherwise keep looking for another max. The same logic applies to minimum of array.

    Flowchart – Find Max and Min using Pointers

    Flowchart

    Program Source Code – Find MAX and MIN using Pointers

#include <stdio.h>

#include <conio.h>

int main()

{

    int i,j,temp,tempmin, max,min;

    max = temp = tempmin = 0;

    int arr[10];

    min = arr[0];

    printf("Enter up to 10 numbers:\n");

    for(i=0;i<=10;i++)
    {

        scanf("%d",&arr[i]);

    }

    int *ptr1, *ptr2;

    ptr1 = arr;

    ptr2 = arr;

    for(i=1;i<=10;i++)
    {

      if(max <= *ptr1)
      {

     temp = max;

     max = *ptr1;

     *ptr1 = temp;

     }

     ptr1++;

   }

    printf("MAX=%d\n",max);

// finding minimum

for(j=1;j<=10;j++) { 

    if(min >= *ptr2)
    {

        tempmin = *ptr2;

        *ptr2 = min;

        min = tempmin;

    }

    ptr2++;

    }

    printf("MIN=%d\n",min);

    system("PAUSE");

    return 0;

}

Output – Find MAX and MIN using Pointers

The output of the program is given below. The array stores the 10 numbers and MAX and MIN is found using pointers. The MAX value in example is 87 and MIN value is 5 after the program completes.

Enter up to 10 numbers:
23
5
66
87
34
65
32
21
25
85
45
MAX=87
MIN=5
Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version