tryman - 1 year ago 63
C Question

# Array same element in C

c finding the array of the same element
A function called rLookupAr() takes in three parameters, array, size and target, and returns the subscript of the last appearance of a number in the array. The parameter size indicates the size of the array. For example, if array is {2,1,3,2,4} and target is 3, it will return 2. With the same array, if target is 2, it will return 3. If the required number is not in the array, the function will return –1. The function prototype is given below.

``````int rLookupAr(int array[], int size, int target);
``````

Write a C program to test the function.

A sample input and output session is given below:

Enter array size: 5 Enter 5 numbers: 2 1 3 2 4 Enter the target number: 2 rLookupAr() = 3

Enter array size: 5 Enter 5 numbers: 2 1 3 2 4 Enter the target number: 5 rLookupAr() = -1

This is my code

``````#include <stdio.h>
int rLookupAr(int array[], int size, int target);

int main() {
int numArray[80];
int target, i, size;

printf("Enter array size: ");
scanf("%d", &size);

printf("Enter %d numbers: ", size);
for (i = 0; i < size; i++)
scanf("%d", &numArray[i]);

printf("Enter the target number: ");
scanf("%d", &target);

printf("rLoopupAr(): %d", rLookupAr(numArray, size, target));

return 0;
}

int rLookupAr(int array[], int size, int target) {
int j,i;

for (j = 0; j < size; j++)
if(array[i] == target)
return j;

return -1;
}
``````

I do not know how to implement when same array elements numbers are the same as bolded

You can code it looping through the array in reverse way like

``````int rLookupAr(int array[], int size, int target) {
int j;

for (j = size-1; j >= 0; j--)
if (array[j] == target)
return j;

return -1;
}
``````

Or looping through the whole and store the value in a lookup variable

``````int rLookupAr(int array[], int size, int target) {
int j;
char found = -1;

for (j = 0; j < size; j++)
if (array[j] == target)
found = j;

return found;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download