Here is the only correct code among presented here in other answers that does the task.:)
In fact you need a program that searches backward an alement of an array that satisfies a given condition. And if there is such an element then to output it.
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int a[] = { 5, 6, -4, -3, -2, -1, 4, 3, 2, 1, -2 };
const size_t N = sizeof( a ) / sizeof( *a );
int *first = a, *last = a + N;
while ( first != last && ( unsigned int )abs( *( last - 1 ) ) < 5 ) --last;
if ( first != last ) printf( "%d\n", *--last );
return 0;
}
The output is
6
Below there is demonstrated a general approach for such tasks
#include <stdio.h>
#include <stdlib.h>
int * find_backward( const int a[], size_t n, int ( *predicate )( int ) )
{
const int *first = a, *last = a + n;
while ( first != last && !predicate( *( last -1 ) ) ) --last;
return ( int * )last;
}
int is_greater_or_equal_to_5( int x )
{
return 5 <= ( unsigned int )abs( x );
}
int main( void )
{
int a[] = { 5, 6, -4, -3, -2, -1, 4, 3, 2, 1, -2 };
const size_t N = sizeof( a ) / sizeof( *a );
int *target = find_backward( a, N, is_greater_or_equal_to_5 );
if ( target != a ) printf( "%d\n", *--target );
return 0;
}
Using this approach you can use any integer arrays (even with zero size) and any conditions that are set by means of predicates.
For example if you want to find the last element of an array that is divisible by 3 you can write
#include <stdio.h>
#include <stdlib.h>
int * find_backward( const int a[], size_t n, int ( *predicate )( int ) )
{
const int *first = a, *last = a + n;
while ( first != last && !predicate( *( last -1 ) ) ) --last;
return ( int * )last;
}
int divisible_by_3( int x )
{
return x % 3 == 0;
}
int main( void )
{
int a[] = { 5, 6, -4, -3, -2, -1, 4, 3, 2, 1, -2 };
const size_t N = sizeof( a ) / sizeof( *a );
int *target = find_backward( a, N, divisible_by_3 );
if ( target != a ) printf( "%d\n", *--target );
return 0;
}
The output is
3
Take into account that this function allows also to deal with constant arrays.:)