Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

array subscript help please.

Status
Not open for further replies.

RavUnRex

Programmer
Oct 24, 2005
8
0
0
US
I am trying to write a program that will find the largest value in an array, and also will display the subscript of the largest value. I can find the largest value, but I have been working for the past 4 hours trying to get the subscript to display... anyone know how to go about this, without completely changing my program? This is a rather simple program; I am just having a mental block!!!

ARRAY:

#include <stdafx.h>
#include <stdio.h>
#define x 5

int
main(void)
{
double arr[x];
int i,
large;

/* Get Data */
printf("Enter %d numbers\n> ", x);
for (i = 0; i < x; ++i)
scanf("%lf", &arr);

large = arr[0];

for(i = 1; i < x; ++i)
if(arr > large)
large = arr;

printf("The largest value, %d has a subscript of x[%1d].", large, i);

return(large);
}
 
Keep track of the index.
Code:
#include <stdio.h>
#define x 5

int main(void)
{
   double arr[x];
   int i, large, [blue]li[/blue];

    /* Get Data */
   printf("Enter %d numbers\n> ", x);
   for ( i = 0; i < x; ++i )
      scanf("%lf", &arr[i]);

   large = arr[0];

   for ( i = 1; i < x; ++i )
      if ( arr[i] > large )
      [blue]{[/blue]
         large = arr[i];
         [blue]li = i;
      }[/blue]

   printf("The largest value, %d has a subscript of x[%1d].", large, [blue]li[/blue]);

   return(large);
}

/* my output
Enter 5 numbers
>1 5 2 4 3
The largest value, 5 has a subscript of x[1].
*/
[Slightly modified for simplicity.]
 
Thank you so much, I knew it was something simple I was missing. I just couldn't figure out how to keep track of the index like that.
Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top