The below code will find the maximum and minimum numbers in an array.
Logic: Use linear search to search for the max and min numbers.
Code:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,size,max,min;
//get the size of the array
printf("Welcome\nEnter the total number of elements(numbers):");
scanf("%d",&size);
//declare an array
int numbers[size];
//take input , to fill the array.
printf("Enter numbers");
for(i=0;i<size;i++)
{
scanf("%d",&numbers[i];
}
/*to calculate maximum and minimum,these variables need to be initialized with some data,therefore we initialize it with the first elements of the array*/
max=numbers[0];
min=numbers[0];
//use linear search to find the max and min number of the array
//star from index 1 as min and max are already initialized with the element at index o
for(i=1;i<size;i++)
{
//if the number at index i is greater then the number in max then put the number at i in max
if(max<numbers[i])
max=numbers[i];
//if the number at index i is less then the number in min then put the number at i in min
if(min>numbers[i])
min=numbers[i];
}
//print the max and min numbers
printf("\nMax is %d\nMin is %d",max,min);
printf("\npress any key to continue");
getch();
}
Logic: Use linear search to search for the max and min numbers.
Code:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,size,max,min;
//get the size of the array
printf("Welcome\nEnter the total number of elements(numbers):");
scanf("%d",&size);
//declare an array
int numbers[size];
//take input , to fill the array.
printf("Enter numbers");
for(i=0;i<size;i++)
{
scanf("%d",&numbers[i];
}
/*to calculate maximum and minimum,these variables need to be initialized with some data,therefore we initialize it with the first elements of the array*/
max=numbers[0];
min=numbers[0];
//use linear search to find the max and min number of the array
//star from index 1 as min and max are already initialized with the element at index o
for(i=1;i<size;i++)
{
//if the number at index i is greater then the number in max then put the number at i in max
if(max<numbers[i])
max=numbers[i];
//if the number at index i is less then the number in min then put the number at i in min
if(min>numbers[i])
min=numbers[i];
}
//print the max and min numbers
printf("\nMax is %d\nMin is %d",max,min);
printf("\npress any key to continue");
getch();
}
Post a Comment