-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathfarthest_element.cpp
More file actions
53 lines (45 loc) · 1.74 KB
/
farthest_element.cpp
File metadata and controls
53 lines (45 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<stdio.h> //header files
#include<stdlib.h>
int main(){ //main function
int t; //taking input the no. of test cases
printf("Enter number of test cases: ");
scanf("%d",&t);
while(t--){
int n,k,far,min,near,max; //declaring variables
printf("Enter number of Integers : "); //no. of integers to be input
scanf("%d",&n);
int *arr=(int *)malloc(n*sizeof(int)); //dynamic allocation of arrar arr
printf("Enter distinct Integers : "); //taking input array elements
for (int j=0;j<n;j++){
scanf("%d",(arr+j));
}
printf("Enter the value of K: "); //input of integer K
scanf("%d",&k);
min=abs(*(arr)-(k)); //storing min value by supposing first element's diff is min
max=abs(*(arr)-(k)); //storing max value by supposing first element's diff is max
for (int i=0;i<n;i++){ //checking another elements to be farthest and nearest
if((abs(*(arr+i)-k))<min){
min=(abs(*(arr+i)-k));
}
if((abs(*(arr+i)-k))>max){
max=(abs(*(arr+i)-k));
}
}
printf("Farthest Element: "); //printing farthest no.
for (int j=0;j<n;j++){
if((abs(*(arr+j)-k))==max){
printf("%d ",*(arr+j));
}
}
printf("\n");
printf("Nearest Element: "); //printing nearest no.
for (int j=0;j<n;j++){
if((abs(*(arr+j)-k))==min){
printf("%d ",*(arr+j));
}
}
free(arr); //free up the memeory of arr
printf("\n\n");
}
return 0;
}