Output location in an array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gactimus

    #1

    Output location in an array

    I made the program below. It outputs the smallest number in the array. What
    I would like to know is how do I output the array location. I am at a loss.

    For example, since the smallest number in the array is 2, the output should
    be 2 for the number and 1 for the location. If anyone could help or point
    me in the right direction that would be great. Thanks.


    -------------------
    #include <iostream>
    using namespace std;

    int main()
    {

    int array[3];

    array[0] = 5;
    array[1] = 2;
    array[2] = 10;

    int k = 0;
    for (int i = 0; i < 3; i++)
    if (array[i] < array[i+1])
    k = i;

    cout << k;


    return 0;
    }
  • Vyacheslav Kononenko

    #2
    Re: Output location in an array

    Gactimus wrote:
    [color=blue]
    > I made the program below. It outputs the smallest number in the array.[/color]
    It does not[color=blue]
    > What
    > I would like to know is how do I output the array location. I am at a loss.[/color]

    You need to fix your program then it should be clear for you.
    [color=blue]
    > For example, since the smallest number in the array is 2, the output should
    > be 2 for the number and 1 for the location. If anyone could help or point
    > me in the right direction that would be great. Thanks.
    >[/color]
    I think right direction is to think before you program, sorry.
    [color=blue]
    > [skip][/color]
    --
    Regards,
    Slava

    Comment

    • Howard

      #3
      Re: Output location in an array


      "Gactimus" <gactimus@xrs.n et> wrote in message
      news:1100028264 .AejCN2DZfRBBcL rMtYpPQw@bubban ews...[color=blue]
      >I made the program below. It outputs the smallest number in the array. What
      > I would like to know is how do I output the array location. I am at a
      > loss.
      >
      > For example, since the smallest number in the array is 2, the output
      > should
      > be 2 for the number and 1 for the location. If anyone could help or point
      > me in the right direction that would be great. Thanks.
      >
      >
      > -------------------
      > #include <iostream>
      > using namespace std;
      >
      > int main()
      > {
      >
      > int array[3];
      >
      > array[0] = 5;
      > array[1] = 2;
      > array[2] = 10;
      >
      > int k = 0;
      > for (int i = 0; i < 3; i++)
      > if (array[i] < array[i+1])
      > k = i;
      >
      > cout << k;
      >
      >
      > return 0;
      > }[/color]

      That's likely to crash! The if statement compares against array[i+1], and
      when i equals 2, it will try to access array[3], which is illegal (undefined
      behavior).

      Let's look at what your code actualy does. You say it reports the smallest
      number, but it doesn't. The variable k gets the value of i, which is the
      index ("location", in your terms), not the value from the array. To get the
      value, you need to set some variable equal to array[i]. You can do that in
      a second variable, named min, for instance. In that case, the if statement
      needs {} brackets, with two assignments inside it: one to assign i to k, and
      one to assign array[i] to min.

      Now that you have a min variable, use that to compare the current array
      value against it, instead of comparing it against array[i+1]. For example,
      your if statement could be "if (array[i] < min)".

      Of course, you need to have a starting value for min. One convenient
      starting value would be array[0], especially since you're already defaulting
      k to 0.

      Once you do that, your can optimize the loop a little, by startng at 1
      isntead of 0 (since you already have k set to 0 and min set to array[0]).
      So your for loop goes "for (int i = 1; i < 3; ++i)".

      (Get into the practice of using ++i instead of i++. It's not important
      here, but may be in later work, and it's a good habit to develop.)

      So what's that look like now?

      int k = 0;
      int min = array[0];
      for (int i = 1; i < 3; ++i)
      {
      if (array[i] < min)
      {
      k = i;
      min = array[i];
      }
      }
      cout << "min is " << min << " at index " << k << "\n";

      (You probably should also get in the habit of using constant variables for
      things like the array size, instead of explicit constants like "3" in the
      for loop. That way, you can change the array size in just one place and
      have al code that refers to the array size changed at once.)

      -Howard






      Comment

      • Gactimus

        #4
        Re: Output location in an array

        Vyacheslav Kononenko <vyacheslav@NOk ononenkoSPAM.ne t> wrote in
        news:H09kd.1886 $Ny6.3254@menck en.net.nih.gov:
        [color=blue]
        > Gactimus wrote:
        >[color=green]
        >> I made the program below. It outputs the smallest number in the array.[/color]
        >
        > It does not[/color]

        You're right. It seemed like it worked the first time but when I changed the
        numbers around I realized it was wrong.

        Comment

        • Vyacheslav Kononenko

          #5
          Re: Output location in an array

          Howard wrote:
          [color=blue]
          > "Gactimus" <gactimus@xrs.n et> wrote in message
          > news:1100028264 .AejCN2DZfRBBcL rMtYpPQw@bubban ews...
          >[color=green]
          >>I made the program below. It outputs the smallest number in the array. What
          >>I would like to know is how do I output the array location. I am at a
          >>loss.
          >>
          >>For example, since the smallest number in the array is 2, the output
          >>should
          >>be 2 for the number and 1 for the location. If anyone could help or point
          >>me in the right direction that would be great. Thanks.
          >>
          >>
          >>-------------------
          >>#include <iostream>
          >>using namespace std;
          >>
          >>int main()
          >>{
          >>
          >>int array[3];
          >>
          >>array[0] = 5;
          >>array[1] = 2;
          >>array[2] = 10;
          >>
          >>int k = 0;
          >>for (int i = 0; i < 3; i++)
          >> if (array[i] < array[i+1])
          >>k = i;
          >>
          >>cout << k;
          >>
          >>
          >>return 0;
          >>}[/color]
          >
          >
          > That's likely to crash! The if statement compares against array[i+1], and
          > when i equals 2, it will try to access array[3], which is illegal (undefined
          > behavior).
          >
          > Let's look at what your code actualy does. You say it reports the smallest
          > number, but it doesn't. The variable k gets the value of i, which is the
          > index ("location", in your terms), not the value from the array. To get the
          > value, you need to set some variable equal to array[i]. You can do that in
          > a second variable, named min, for instance. In that case, the if statement
          > needs {} brackets, with two assignments inside it: one to assign i to k, and
          > one to assign array[i] to min.
          >
          > Now that you have a min variable, use that to compare the current array
          > value against it, instead of comparing it against array[i+1]. For example,
          > your if statement could be "if (array[i] < min)".
          >
          > Of course, you need to have a starting value for min. One convenient
          > starting value would be array[0], especially since you're already defaulting
          > k to 0.
          >
          > Once you do that, your can optimize the loop a little, by startng at 1
          > isntead of 0 (since you already have k set to 0 and min set to array[0]).
          > So your for loop goes "for (int i = 1; i < 3; ++i)".
          >
          > (Get into the practice of using ++i instead of i++. It's not important
          > here, but may be in later work, and it's a good habit to develop.)
          >
          > So what's that look like now?
          >
          > int k = 0;
          > int min = array[0];
          > for (int i = 1; i < 3; ++i)
          > {
          > if (array[i] < min)
          > {
          > k = i;
          > min = array[i];
          > }
          > }
          > cout << "min is " << min << " at index " << k << "\n";
          >
          > (You probably should also get in the habit of using constant variables for
          > things like the array size, instead of explicit constants like "3" in the
          > for loop. That way, you can change the array size in just one place and
          > have al code that refers to the array size changed at once.)
          >
          > -Howard
          >[/color]
          Do you really think that to post the full answer here will help him
          learn programming? Especially with an extra variable that is completly
          unnecessary:

          int k = 0;
          for (int i = 1; i < 3; ++i)
          if (array[i] < array[k])
          k = i;

          cout << "min is " << array[k] << " at index " << k << "\n";


          --
          Regards,
          Slava

          Comment

          • DaKoadMunky

            #6
            Re: Output location in an array

            >int k = 0;[color=blue]
            >int min = array[0];
            >for (int i = 1; i < 3; ++i)
            >{
            > if (array[i] < min)
            > {
            > k = i;
            > min = array[i];
            > }
            >}
            >cout << "min is " << min << " at index " << k << "\n";[/color]

            Is variable min necessary?

            It seems that keep tracking of the index would be sufficient. At any given
            time the minimum value thus far could be retrieved from the array.

            Just curious.

            Comment

            • chris

              #7
              Re: Output location in an array

              DaKoadMunky wrote:[color=blue][color=green]
              >>int k = 0;
              >>int min = array[0];
              >>for (int i = 1; i < 3; ++i)
              >>{
              >> if (array[i] < min)
              >> {
              >> k = i;
              >> min = array[i];
              >> }
              >>}
              >>cout << "min is " << min << " at index " << k << "\n";[/color]
              >
              >
              > Is variable min necessary?
              >
              > It seems that keep tracking of the index would be sufficient. At any given
              > time the minimum value thus far could be retrieved from the array.
              >
              > Just curious.[/color]

              I was curious too :)

              It was possible that this could be an optimisation (although it would be
              a micro-optimisation). However g++ seems to produce virtually identical
              code if it is there or not.

              Chris

              Comment

              • Howard

                #8
                Re: Output location in an array


                "Vyacheslav Kononenko" <vyacheslav@NOk ononenkoSPAM.ne t> wrote in message
                news:9s9kd.1889 $Ny6.3020@menck en.net.nih.gov. ..[color=blue][color=green]
                >>[/color]
                > Do you really think that to post the full answer here will help him learn
                > programming? Especially with an extra variable that is completly
                > unnecessary:
                >
                > int k = 0;
                > for (int i = 1; i < 3; ++i)
                > if (array[i] < array[k])
                > k = i;
                >
                > cout << "min is " << array[k] << " at index " << k << "\n";
                >[/color]

                You're correct, the extra variable isn't needed here. It doesn't make it
                wrong or even bad form, though. He might want that information later. It's
                simply old habit that I keep important information in an identifiable
                variable instead of requiring a "lookup" to get it later. Call it
                "pre-emptive optimization". :-)

                As for posting the whole answer, yes, I *do* think it helped, in this case.
                He tried something, and it was wrong. By the time I'd explained the
                problems and potential solutions, in prose, I was afraid he'd just be even
                more confused if it wasn't put back together as real code. I walked him
                through each step of the corrections, and guided him to the final result.
                So, yes, I think it was very helpful.

                -Howard


                Comment

                • Vyacheslav Kononenko

                  #9
                  Re: Output location in an array

                  Gactimus wrote:
                  [color=blue]
                  > "Howard" <alicebt@hotmai l.com> wrote in
                  > news:WL9kd.8722 38$Gx4.50820@bg tnsc04-news.ops.worldn et.att.net:
                  >
                  >[color=green]
                  >>"Vyacheslav Kononenko" <vyacheslav@NOk ononenkoSPAM.ne t> wrote in message
                  >>news:9s9kd.18 89$Ny6.3020@men cken.net.nih.go v...
                  >>
                  >>[color=darkred]
                  >>>Do you really think that to post the full answer here will help him
                  >>>learn programming? Especially with an extra variable that is completly
                  >>>unnecessar y:
                  >>>
                  >>>int k = 0;
                  >>>for (int i = 1; i < 3; ++i)
                  >>> if (array[i] < array[k])
                  >>> k = i;
                  >>>
                  >>> cout << "min is " << array[k] << " at index " << k << "\n";[/color]
                  >>
                  >>You're correct, the extra variable isn't needed here. It doesn't make
                  >>it wrong or even bad form, though. He might want that information
                  >>later. It's simply old habit that I keep important information in an
                  >>identifiabl e variable instead of requiring a "lookup" to get it later.
                  >>Call it "pre-emptive optimization". :-)
                  >>
                  >>As for posting the whole answer, yes, I *do* think it helped, in this
                  >>case. He tried something, and it was wrong. By the time I'd explained
                  >>the problems and potential solutions, in prose, I was afraid he'd just
                  >>be even more confused if it wasn't put back together as real code. I
                  >>walked him through each step of the corrections, and guided him to the
                  >>final result. So, yes, I think it was very helpful.[/color]
                  >
                  >
                  > Okay, I appreciate all your help so far but I still haven't finished the
                  > program. The goal of the program is to to pass an array to a function, get
                  > two values of which I explained earlier, put those values in a structure
                  > and then return the single structure item with the two imbedded values.
                  > After working on it for the last few hours, I have gotten the program down
                  > to one error but I am stuck. Any help would be great.
                  >
                  > Here is my code:
                  >
                  > -------------------
                  > #include <iostream>
                  > using namespace std;
                  >
                  > struct minimum
                  > {
                  > int lowest;
                  > int index;
                  > };
                  >
                  > const minimum array[] = {5,9,6,3,2,10};
                  > minimum function(int array[]);
                  > void output(minimum t);
                  >
                  >
                  > int main()
                  > {
                  > minimum pass = function(array) ;
                  > output(pass);
                  >
                  > return 0;
                  > }
                  >
                  > minimum function(int array[])[/color]

                  you should pass size of the array as a second parameter otherway your
                  function is rather useless(unless your task is define a function that
                  finds minimum and index of array THAT HAS 7 elements):
                  minimum function(int array[], int size)

                  and call will be then
                  minimum pass = function(array, sizeof(array)/sizeof(array[0]));[color=blue]
                  > {
                  > minimum total;
                  > int k = 0;
                  > int min = array[0];[/color]

                  It is not a mistake but you already have "total" why not to use it
                  instead of "k" and "min"?[color=blue]
                  >
                  > for (int i = 1; i < 7; ++i)[/color]
                  for(int i = 1; i < size; ++i)[color=blue]
                  > {
                  > if (array[i] < min)
                  > {
                  > k = i;
                  > min = array[i];
                  > }
                  > }
                  >[/color]
                  [color=blue]
                  > total.index = k;
                  > total.lowest = min;[/color]
                  you will not need this two statements if you use total before.
                  [color=blue]
                  > return total;
                  > }
                  >
                  > void output(minimum t)
                  > {
                  > cout << "The number closest to Zero is " << t.lowest << ".\n";
                  > cout << "The index of the number is " << t.index << ".\n";
                  > }[/color]
                  --
                  Regards,
                  Slava

                  Comment

                  Working...