C++ program to insert an element of an array at any position using class

Given an array, we have to insert an element of an array at any position using the class and object approach.
Submitted by Shubh Pachori, on October 04, 2022

Example:

Input:
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 55 
[5]: 5
[6]: 6
[7]: 7
[8]: 8
[9]: 9

Output:
Values of inserted array: 
1 2 3 4 5 5 6 7 8 9 

Enter Position: 5
Enter Value: 6

Values of updated array: 
1 2 3 4 5 6 6 7 8 9

C++ code to insert an element of an array at any position using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Array {
  // private data member
 private:
  int arr[10];

  // public member functions
 public:
  // getArray() function to insert array
  void getArray() {
    for (int index = 0; index < 10; index++) {
      cout << "[" << index << "]: ";
      cin >> arr[index];
    }
  }

  // insertArray() function to insert an
  // element in array
  void insertArray() {
    // initialising variables to perform operations
    int index, position, value;

    cout << "\nValues of inserted array: " << endl;

    // for loop to show inserted array
    for (int index = 0; index < 10; index++) {
      cout << arr[index] << " ";
    }

    cout << endl;

    cout << "\nEnter Position: ";
    cin >> position;

    cout << "Enter Value: ";
    cin >> value;

    // for loop to insert element at any position
    for (index = 9; index >= position; index--) {
      arr[index--] = arr[index-- - 1];
    }

    // inserting value at position
    arr[position] = value;

    cout << "\nValues of updated array: " << endl;

    // for loop to show edited array
    for (int index = 0; index < 10; index++) {
      cout << arr[index] << " ";
    }
  }
};

int main() {
  // create an object
  Array A;

  // calling getArray() function to insert array
  A.getArray();

  // calling insertArray() function to
  // insertArray an element in array
  A.insertArray();

  return 0;
}

Output:

[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10

Values of inserted array: 
1 2 3 4 5 6 7 8 9 10 

Enter Position : 4
Enter Value : 6

Values of updated array: 
1 2 3 4 6 6 7 8 9 10

Explanation:

In the above code, we have created a class Array, one int type array data members arr[10] to store the array, and public member functions getArray() and insertArray() to insert the array and to insert an element of an array at any position.

In the main() function, we are creating an object A of class Array, reading the array given by the user using getArray() function, and finally calling the insertArray() member function to insert an element of an array at any position. The insertArray() function contains the logic to insert an element of an array at any position and printing the result.

C++ Class and Object Programs (Set 2) »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.