Thursday, 14 April 2016

C And C++ Program to delete all duplicate elements from an array Problem Solution.


C Solution:

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

    int ar[1000],sz,i,j,k;

    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]){
                for(k = j; k < sz-1; k++)ar[k] = ar[k+1];
                sz--;
            }
        }
    }
    printf("\nArray elements after deleting duplicates : ");
    for(i = 0; i < sz; i++)printf("%d ", ar[i]);

    return 0;
}

C++ Solution:

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

    int ar[1000],sz;

    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]){
                for(int k = j; k < sz-1; k++)ar[k] = ar[k+1];
                sz--;
            }
        }
    }
    cout << endl << "Array elements after deleting duplicates : ";
    for(int i = 0; i < sz; i++)cout << ar[i] << " ";

    return 0;
}

No comments:

Post a Comment