Smallest Number

How to find the smallest number amoungest 4 numbers
Just loop round the 4 numbers on first iteration keep hold of the first number, on the 2nd iteration compare first number to second if first number is smaller retain it, else replace with second number and repeat process until you reach the end of the list of numbers. You will then be holding the smallest number.
and how will i know which number was smaller first second third or 4th

and how will i know which number was smaller first second third or 4th


Say for example you decide to hold the numbers in a fixed sized array:
 
int numbers[] = {7,10,9,4};


You iterate through and read the current number into say an local variable named 'lowest' declared outside of your loop. You then compare the value of 'lowest' to each of the following numbers in the array. Thus:

lowest = 7

is lowest less than numbers[1], it is so lowest still holds 7
is lowest less than numbers[2], it is so lowest still holds 7
is lowest less than numbers[3], no, so replace number held by lowest with numbers[3] i.e. 4

You then finish the iteration and lowest holds the smallest number in our set.

I'm sure you can write some code that does that.
initialise something like a & b=1,
then use the following in your program :

1
2
3
4
5
6
7
8
9
10
a=numbers[0];
for (n=1;n<4;n++)
{
   if (numbers[n]<a)
      {
          a=numbers[n];
          b=n+1;
      }

cout<<"Number at position "<<b<<"is smallest.";



this should do the job...
be sure to tell me if its done.
Last edited on
Oh well done @dncp4312 - I was attempting to prompt @Sarmadas to come up with the code. Why use b and where is it declared anyway?
@ajh32
its said in the first line, initialize something like a and b=1 i.e b as 1;
i used it cuz he asked : how will i know which number was smaller first second third or 4th

it should give results as of line 10.

And since you asked about declaring b, make note that, i neither declared a, nor numbers, i havent started the main function, and not even included the header files. . .
I thnk you got my point. . .
Sarmadas shud do thir all. . .

pleasure helping...
Last edited on
thanks friend let me check
thanks for help thank u so much
Last edited on
closed account (D80DSL3A)
Another way for specifically 4 numbers is:
 
T low(T a, T b){ return a<b? a:b; }// type is T (not specified) 

Then call low( low(n1,n2), low(n3,n4) );
this way is correct and this process can be multithreaded. another way is to simply sort the array or vector C++ provide an algorithms libraries to data
Topic archived. No new replies allowed.