Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- same_value_as_index_v1.c
- Suppose you are given a sorted array, such as A = {-5, -1, 2, 4, 6}.
- Write an algorithm which takes this sorted array as input and
- returns as output an ‘index’,
- if the value stored at A[index] is same as ‘index’,
- else return -1.
- Example, for array A, the value returned is 2, as A[2] == 2.
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- // Returns index if A[i] = i, otherwise returns -1.
- int same_value_as_index( int A[], int n, int i)
- {
- if( A[i] == i )
- return i;
- else
- return -1;
- }
- int main(void)
- {
- int A[] = {-5, -1, 2, 4, 6};
- int i, n;
- n = sizeof(A) / sizeof(A[0]); // or
- //n = sizeof(A) / sizeof(int);
- for( i=0; i<n; i++)
- {
- printf("\n i = %d \t A[%d] = %d \t same_value_as_index(A,n,i) = %d \n",
- i, i, A[i], same_value_as_index(A,n,i) );
- }
- return 0;
- } // main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement