Thursday, 14 April 2016

C And C++ Program to delete an element from an array at specified position Problem Solution.


C Solution:

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

    int ar[1000],i,sz,pos;

    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]);

    printf("Enter the element position to delete : ");
    scanf("%d", &pos);

    if(pos == sz+1 || pos < 0)printf("Invalid position!\n");
    else for(i = pos-1; i < sz; i++)ar[i] = ar[i+1];

    printf("\nElements of array after delete are :");
    for(i = 0; i < sz-1; 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,pos;

    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];

    cout << "Enter the element position to delete : ";
    cin >> pos;

    if(pos == sz+1 || pos < 0)cout << "Invalid position!" << endl;
    else for(int i = pos-1; i < sz; i++)ar[i] = ar[i+1];

    cout << endl << "Elements of array after delete are :";
    for(int i = 0; i < sz-1; i++)cout << ar[i] << " ";

    return 0;
}

No comments:

Post a Comment