Question

Values are entered into an array by the user and then i have this For Loop to compare the numbers once they have all been entered. What i'm trying to do is find the first larger number in the array.

i = 0;
next = a[++i];
for (i = 0; i < len; i++)
{
    if (a[i] > a[next])
    {
        ++next;

        if (a[i] < a[next])
        {
          printf("%d is the first larger number.", a[i]);
        }
    }

}

When I debug my program I see that when "i" is being compared to a[next] its not taking the value of the number inside that position "i" of the array. i've attempted using "i" instead of a[i] when starting my If statements but that doesn't seem to fix the issue.

Here is my Corrected code. made a few more minor changes just for practice

#include <stdio.h>

int main(int argc, const char * argv[])
{
const int len = 4;
int a[len];
int i;
int j = a[i-1];

for (i = 0; i < len; i++) {
    printf("Enter a number:");
    scanf("%d", &a[i]);
}

i = 0;
for (i = 1; i < len; i++) {
    if (a[i] > a[j])
    {
          printf("%d is the first larger number.", a[i]);
        break;
    }

}

}
Était-ce utile?

La solution

I think you're looking for the first place where the array is not decreasing; i.e., the index of the first element i such that a[i] > a[i-1].

for (i = 1; i < len; i++) {
    if (a[i] > a[i-1]) {
        printf("%d is the first larger number", a[i]);
        break;
    }
}

A new version, printing out the first part of the sequence:

for (i = 1; i < len; i++) {
    if (a[i] > a[i-1]) {
        printf("\n%d is the first larger number", a[i]);
        break;
    }
    printf("%d ", a[i]);
}

Autres conseils

Whatever what you are trying to achieve!! you never say: next = a[++i]; than a[i] > a[next] !! a[next] can be beyond the size of your array

EX:

A[] = {0, 7, 2, 3, 1}

next = A[1] = 7

A[next] = A[7] = !! //what u think it is?

Assuming that you are looking for the first local maximum, one solution is to declare a variable called best to keep track of the largest number seen so far. Set best to the first element of the array a[0]. Then check for the first element of the array that is less than best.

best = a[0]; 
for ( i = 1; i < len; i++ )
{
    if ( a[i] > best ) 
        best = a[i];
    else if ( a[i] < best )
        break;
}
printf( "%d is the first larger number.\n", best );
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top