Thursday, 14 April 2016

C and C++ Program to find second largest number in an array Problem Solution.


C Solution:

#include <stdio.h>
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    int ar[10000],i,mx1,mx2,sz;

    printf("Enter size of the array: ");
    scanf("%d", &sz);

    printf("Enter elements in the array (Separated by space): ");
    for(i = 0; i < sz; i++) scanf("%d", &ar[i]);

    mx1 = ar[0];
    mx2 = ar[0];

    for(i = 1; i < sz; i++){
        if(ar[i] > mx1){
            mx2 = mx1;
            mx1 = ar[i];
        }
        else if(ar[i] > mx2)mx2 = ar[i];
    }
    printf("First largest = %d\n", mx1);
    printf("Second largest = %d\n", mx2);

    return 0;
}

C++ Solution:

#include <iostream>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    int ar[10000],mx1,mx2,sz;

    cout << "Enter size of the array: ";
    cin >> sz;

    cout << "Enter elements in the array (Separated by space): ";
    for(int i = 0; i < sz; i++) cin >> ar[i];

    mx1 = ar[0];
    mx2 = ar[0];

    for(int i = 1; i < sz; i++){
        if(ar[i] > mx1){
            mx2 = mx1;
            mx1 = ar[i];
        }
        else if(ar[i] > mx2)mx2 = ar[i];
    }
    cout << "First largest = " << mx1 << endl;
    cout << "Second largest = " << mx2 << endl;

    return 0;
}

No comments:

Post a Comment