Find the Second Maximum and Second Minimum Elements of an Array

97Views
No Comments

共计 1116 个字符,预计需要花费 3 分钟才能阅读完成。

This program comes under the array operations in Data Structure. In this program, we will create an array take input from the user, and sort the array then we’ll find the second maximum number and second minimum number.

For sorting, I have used an insertion array inside the program.

#include <stdio.h>

//Defining the prototypes
void printA(int a[], int n);
void sortA(int a[], int n);

int main() {
    int n;
    int a[10];
    int secondMax;
    int secondMin;
    
    //Getting the size of array user want to input
    printf("Enter the size of the array maximum 10 and minimum 5\n");
    scanf("%d", &n);
    if(n>10 || n<5) {
        printf("You cannot make array size more than 10 and less than 5");
        return 0;
    }
    
    //Getting input from user to array
    for(int i=0; i<n; i++) {
        printf("Enter the %dth element of array\n", i+1);
        scanf("%d", &a[i]);
    }
    sortA(a,n);
    printf("Sorted array: ");
    printA(a,n);
    secondMin = a[1];
    secondMax = a[n-2];
    printf("\n %d is the second maximum value of the array\n", secondMax);
    printf("\n %d is the second minimum value of the array\n", secondMin);
    return 0;
}

//Sorting using insertion sort method
void sortA(int a[], int n) {
    for(int i=1; i<n; i++) {
        int key = a[i];
        int j = i-1;
        while(key<a[j] && j>=0) {
            a[j+1] = a[j];
            j = j-1;
        }
        a[j+1] = key;
    }
}

//Array Printing Function
void printA(int a[], int n) {
    for(int i=0; i<n; i++) {
        printf("%d \t", a[i]);
    }
}
Find the Second Maximum and Second Minimum Elements of an Array

正文完
 
Amitesh Kumar
Copyright notice: Our original article, by Amitesh Kumar 2023-02-01 publish, total 1116 words.
转载说明:Unless otherwise specified, all articles are published by cc-4.0 protocol. Please indicate the source of reprint.
Comment(No Comments)