Yesterday I went for an interview where I have been asked to create a program to find largest and smallest among 5 numbers without using array.
I know how to create
int findMin(int t1, int t2, int t3, int t4, int t5)
{
int min1, min2, min3;
min1 = std::min(t1, t2);
min2 = std::min(t3, t4);
min3 = std::min(min1, min2);
return std::min(min3, t5);
}
int findMax(int t1, int t2, int t3, int t4, int t5)
{
int max1, max2, max3;
max1 = std::max(t1, t2);
max2 = std::max(t3, t4);
max3 = std::max(max1, max2);
return std::max(max3, t5);
}
These functions are very messy but easy to follow and thus easy to remember and it only uses the simple min and max methods which work best for 2 values.
void main()
{
int a,b,c,d,e,max;
max=a;
if(b/max)
max=b;
if(c/max)
max=c;
if(d/max)
max=d;
if(e/max)
max=e;
cout<<"Maximum is"<<max;
}
Heres what I did, without using an array. This was a method to return the highest number of 5 scores.
double findHighest(double score1, double score2, double score3, double score4, double score5)
{
double highest = score1;
if (score2 > score1 && score2 > score3 && score2 > score4 && score2 > score5)
highest = score2;
if(score3 > score1 && score3 > score2 && score3 > score4 && score3 > score5)
highest = score3;
if(score4 > score1 && score4 > score2 && score4 > score3 && score4 > score5)
highest = score4;
if (score5 > score1 && score5 > score2 && score5 > score3 && score5 > score4)
highest = score5;
return highest;
}
An array is going to be far more efficient, but I had to do it for homework without using an array.