Thursday, 14 April 2016

C And C++ Program count total number of duplicate elements in an array Problem Solution.


C Solution:

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

    int ar[100],i,j,sz,cnt = 0;

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

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

    for(i = 0; i < sz; i++){
        for(j = i+1; j < sz; j++){
            if(ar[i] == ar[j]){
                cnt++;
                break;
            }
        }
    }
    printf("\nTotal number of duplicate elements found in array = %d", cnt);

    return 0;
}

Another Way:

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

    int ar[100],i,j,sz,cnt[100] = {0},dup = 0,sum = 0,mxRange = -99999;

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

    printf("Enter elements in array (Separated by space): ");
    for(i = 0; i < sz; i++){
        scanf("%d", &ar[i]);
        cnt[ar[i]]++;
        if(ar[i] > mxRange)mxRange = ar[i];
    }
    for(i = 0; i < mxRange; i++){
        if(cnt[i] > 1){
            dup += cnt[i]-1;
        }
    }
    printf("\nTotal number of duplicate elements found in array = %d", dup);

    return 0;
}

C++ Solution:

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

    int ar[100],sz,cnt = 0;

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

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

    for(int i = 0; i < sz; i++){
        for(int j = i+1; j < sz; j++){
            if(ar[i] == ar[j]){
                cnt++;
                break;
            }
        }
    }
    cout << endl << "Total number of duplicate elements found in array = " << cnt << endl;

    return 0;
}

Another Way:

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

    int ar[100],i,j,sz,cnt[100] = {0},dup = 0,sum = 0,mxRange = -99999;

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

    cout << "Enter elements in array (Separated by space): ";
    for(i = 0; i < sz; i++){
        cin >> ar[i];
        cnt[ar[i]]++;
        if(ar[i] > mxRange)mxRange = ar[i];
    }
    for(i = 0; i < mxRange; i++){
        if(cnt[i] > 1){
            dup += cnt[i]-1;
        }
    }
    cout << endl << "Total number of duplicate elements found in array = " <<  dup << endl;;

    return 0;
}

No comments:

Post a Comment