Add, Update, Delete Array Elements [C/C++]

Add, Update, Delete Array Elements [C/C++]. This article is actually just a note. I will not write until the detailed explanation of what it looks like. But if you are confused, you can doodle in the comments column below. : D

Sorry for the few words I wrote in Indonesian.

Ahmad Lukman Hakim
Add, Update, Delete Array Elements [C/C++ ]
Add, Update, Delete Array Elements [C/C++ ]
#include <iostream>
using namespace std;

int main(){
    int pilihan, hapus, count, oldData, newData, inputData, indexKe;
    int data[] = {2, 12, 6, 12, 12, 7, 6, 12};
    int n = sizeof(data)/sizeof(data[0]);

    // view array
    cout << "Data : ";
    for(int i=0; i<n; i++){
        cout << data[i] << " ";
    }

    // list options
    cout << endl << endl;
    cout << "1. Delete Data Array" << endl;
    cout << "2. Update Data Array" << endl;
    cout << "3. Add Data Array" << endl;
    cout << "Pilih: ";
    cin >> pilihan;

    // option1
    if(pilihan == 1){
        // input user
        cout <<endl<< "Data yang akan dihapus : ";
        cin >> hapus;

        // menampilkan data yang dihapus
        cout << endl << "Data " << hapus << " berhasil dihapus!" << endl;
        
        count = 0;
        //menampilkan data yang telah dihapus
        cout << endl << "Data sekarang : " << endl << endl;
        cout << "[ ";
        for(int i=0; i<n; i++){
            if(data[i] == hapus){
                ++count;
            }else{
                cout<< data[i] <<" ";
            }
        }
        cout << "]";

        // menampilkan berapa banyak data yang berhasil dihapus
        cout << endl << endl <<"COUNTER: " << count << " data berhasil dihapus!";
    }

    // option2
    else if(pilihan == 2){
        // input user
        cout << endl << "Input data lama: ";
        cin >> oldData;
        cout << "Input data baru: ";
        cin >> newData;
        
        // proses pengubahan data
        for(int i=0; i<n; i++){
            if(data[i] == oldData){
                data[i] = newData;
            }
            cout << data[i] << " ";
        }
    }

    // option3
    else if(pilihan == 3){
        // input pengubahan data
        cout << endl << "Nilai yang akan ditambahkan: ";
        cin >> inputData;
        cout << "Index ke berapa: ";
        cin >> indexKe;

        // mengganti data index + 1 dengan data sebelumnya
        for(int i=n-1; i>=indexKe; i--){
            data[i + 1] = data[i];
        }

        // mengisi data index sebelumnya dengan data barus
        data[indexKe] = inputData;
        n++;

        // menampilkan data setelah ditambahkan
        for (int i=0; i<n; i++){
            cout << data[i] << " ";
        }
    }

    return 0;
}

Leave a Reply