[try Beta version]
Not logged in

 
Smallest Number

Nov 28, 2013 at 2:26pm
How to find the smallest number amoungest 4 numbers
Nov 28, 2013 at 2:35pm
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.
Nov 28, 2013 at 2:54pm
and how will i know which number was smaller first second third or 4th
Nov 28, 2013 at 3:26pm

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.
Nov 28, 2013 at 3:45pm
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 Nov 28, 2013 at 3:46pm
Nov 28, 2013 at 3:59pm
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?
Nov 28, 2013 at 4:12pm
@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 Nov 28, 2013 at 4:55pm
Nov 28, 2013 at 6:26pm
thanks friend let me check
Nov 28, 2013 at 6:48pm
thanks for help thank u so much
Last edited on Nov 28, 2013 at 7:13pm
Nov 28, 2013 at 6:49pm
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) );
Nov 28, 2013 at 7:52pm
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.