-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2ndLargest_Smallest.c
More file actions
57 lines (56 loc) · 1.54 KB
/
2ndLargest_Smallest.c
File metadata and controls
57 lines (56 loc) · 1.54 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
54
55
56
57
/* Aim of the program: Write a program to find out the second smallest and second largest
element stored in an array of n integers.
Input: Size of the array is ‘n’ and read ‘n’ number of elements from a disc file.
Output: Second smallest, Second largest */
#include <stdio.h>
#include <limits.h>
void search(int arr[], int n, int *secondSmallest, int *secondLargest)
{
int smallest = INT_MAX, largest = INT_MIN;
*secondSmallest = INT_MAX;
*secondLargest = INT_MIN;
for (int i = 0; i < n; i++)
{
if (arr[i] < smallest)
{
*secondSmallest = smallest;
smallest = arr[i];
}
else if (arr[i] < *secondSmallest && arr[i] != smallest)
{
*secondSmallest = arr[i];
}
if (arr[i] > largest)
{
*secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > *secondLargest && arr[i] != largest)
{
*secondLargest = arr[i];
}
}
}
int main()
{
FILE *file;
file = fopen("C:/Users/KIIT/Desktop/DAA Lab/input.txt", "r");
if (file == NULL)
{
printf("Error\n");
return 1;
}
int n;
fscanf(file, "%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
fscanf(file, "%d", &arr[i]);
}
fclose(file);
int secondSmallest, secondLargest;
search(arr, n, &secondSmallest, &secondLargest);
printf("Second smallest element: %d\n", secondSmallest);
printf("Second largest element: %d\n", secondLargest);
return 0;
}