Advertisement
dmilicev

same_value_as_index_v1.c

May 27th, 2020
144
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3.     same_value_as_index_v1.c
  4.  
  5.     Suppose you are given a sorted array, such as A = {-5, -1, 2, 4, 6}.
  6.     Write an algorithm which takes this sorted array as input and
  7.     returns as output an ‘index’,
  8.     if the value stored at A[index] is same as ‘index’,
  9.     else return -1.
  10.  
  11.     Example, for array A, the value returned is 2, as A[2] == 2.
  12.  
  13.  
  14.     You can find all my C programs at Dragan Milicev's pastebin:
  15.  
  16.     https://pastebin.com/u/dmilicev
  17.  
  18. */
  19.  
  20. #include <stdio.h>
  21.  
  22.  
  23. // Returns index if A[i] = i, otherwise returns -1.
  24. int same_value_as_index( int A[], int n, int i)
  25. {
  26.     if( A[i] == i )
  27.         return i;
  28.     else
  29.         return -1;
  30. }
  31.  
  32.  
  33. int main(void)
  34. {
  35.     int A[] = {-5, -1, 2, 4, 6};
  36.     int i, n;
  37.  
  38.     n = sizeof(A) / sizeof(A[0]);   // or
  39.     //n = sizeof(A) / sizeof(int);
  40.  
  41.     for( i=0; i<n; i++)
  42.     {
  43.         printf("\n i = %d \t A[%d] = %d \t same_value_as_index(A,n,i) = %d \n",
  44.                 i, i, A[i], same_value_as_index(A,n,i) );
  45.     }
  46.  
  47.     return 0;
  48.  
  49. } // main()
Advertisement
RAW Paste Data Copied
Advertisement