Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday, 24 March 2019

The Interview Question Today#18(13-3-19)(Elements in a given array are distinct)

Question:

Determines whether all the elements in a given 

array are distinct


Example:


Input: arr[]={1,2,3,4,5,3}
Output: Repeated Element Exists




Solution:

Approach:

ALGORITHM UniqueElements(A[0..n 1])

//Determines whether all the elements in a given array are distinct

//Input: An array A[0..n 1]

//Output: Returns “true” if all the elements in are distinct

// and “false” otherwise

for ← to do

for ← to do


if A[iA[jreturn false

return true


C program:


#include <stdio.h>

int main(){

 int array[100],d, c, n,flag=0;


  printf("Enter number of elements in array\n");

  scanf("%d", &n);

  printf("Enter %d integer(s)\n", n);

  for (c = 0; c < n; c++)

    scanf("%d", &array[c]);

   for (c = 0; c < n; c++){

    for(d=c+1;d<n;d++)  {

    if (array[c] ==array[d])    /* If required element is found */    {

        flag=1;

      printf("%d is present at location %d and %d.\n",array[d], c+1,d+1);

      break;    }

  }

  }

  if (flag==0){    printf("No repeated element present in the array.\n");

  }

  if (flag==1){

    printf("Repeated element present in the array.\n");

  }

  return 0;

}

Output:

Enter number of elements in array

5

Enter 5 integer(s)

4

5

6

4

5

4 is present at location 1 and 4.

5 is present at location 2 and 5.

Repeated element present in the array.

0 comments:

Post a Comment