To find fisrt and second maximum number using pointers in c++
// max.cpp : Defines the entry point for the console application.
//Finds second maximum number in the array.
#include "stdafx.h"
#include<iostream>
using namespace std;
//Define a function max which gives maximun and second maxium number.
//Pass two int variables by-refernce and an array.
void max(int [],int *,int *);
int _tmain(int argc, _TCHAR* argv[])
{
//Define three int variables and an array of your required size.
int max1,max2,i,a[10];
cout<<"enter array elements"<<endl; //Input value of array elements.
for(i=0;i<10;i++) //Loop for input.
{
cin>>a[i];
}
max(a,&max1,&max2); //Call the function.
//These lines will execute after function execution.
cout<<"\nMaximum number is"<<max1<<endl;
cout<<"\n 2nd maximum number is"<<max2<<endl;
return 0;
}
//Function will receive address of variables and array.
void max(int b[10],int *m1,int *m2)
{
int j,min=b[0];//Define an int min required to find 2nd maximum number.
*m1=b[0];
for(j=0;j<10;j++) //First find maximum number.
{
if(b[j]>*m1)
*m1=b[j]; //Maximum number is in *m1.
if(b[j]<min) //Find minimum number
min=b[j];
}
cout<<"\nMinimum number is"<<min<<endl;
*m2=min;
for(j=0;j<10;j++) //Now here the logic for second maximum number.
{
//If b[J] is greatar than *m2 and b[j] is less than *m1 which is
//maximum number then assign *m2 the value of element of array pointing
//currently.
if(b[j]>*m2 && b[j]<*m1)
{
*m2=b[j];
}
}
}
Comments
Post a Comment