Monday 25 September 2017

Integers in an array are unique and increasingly sorted. Please write a function/method to find an integer from the array which equals to its index. For example, in the array {-3, -1, 1, 3, 5}, the number 3 equals its index 3.

#include<stdio.h>
#include<stdlib.h>

int main(){
    int i,*arr,len;
    scanf("%d",&len);
   
    //Dynamically allocating memory for array
    arr = (int*) malloc(len * sizeof(int));
   
    for(i=0;i<len;i++)
        scanf("%d",&arr[i]);
   
    //Traversing the array & finding the element which is equal to its index
    for(i=0;i<len;i++){
        if(arr[i]==i){
            printf("The number %d is equal to its index %d\n",arr[i],i);
        }
    }
}

No comments:

Post a Comment