×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to add two arrays using class

Submitted by Shubh Pachori, on September 15, 2022

Problem statement

Given two arrays of integers, we to add them using the class and object approach.

Example:

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

Input 2nd Array :
[0]: 1
[1]: 3
[2]: 5
[3]: 7
[4]: 9
[5]: 11
[6]: 1
[7]: 2
[8]: 3
[9]: 4
Output: 
Added Array:
3 7 11 15 19 12 3 5 7 9

C++ code to add two arrays using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Array {
  // private data members
 private:
  int arr1[10];
  int arr2[10];

  // public member functions
 public:
  // getArray() function to insert arrays
  void getArray() {
    cout << "Input 1st Array :" << endl;

    for (int index = 0; index < 10; index++) {
      cout << "[" << index << "]: ";
      cin >> arr1[index];
    }

    cout << "\nInput 2nd Array :" << endl;

    for (int index = 0; index < 10; index++) {
      cout << "[" << index << "]: ";
      cin >> arr2[index];
    }
  }
  // addArray() function to add two arrays
  void addArray() {
    // initialising variables to perform operations
    int temp[10], index;

    // for loop to add both the arrays
    for (index = 0; index < 10; index++) {
      temp[index] = arr1[index] + arr2[index];
    }

    cout << "\nAdded Array:" << endl;

    // for loop to print the resulted array
    for (index = 0; index < 10; index++) {
      cout << temp[index] << " ";
    }
  }
};

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

  // calling getArray() function to 
  // insert the arrays
  A.getArray();

  // calling addArray() function to 
  // add two arrays
  A.addArray();

  return 0;
}

Output

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

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

Added Array:
2 4 6 8 10 12 14 16 18 20

Explanation

In the above code, we have created a class Array, two int type array data members arr1[10] and arr2[10] to store the elements of the array, and public member functions getArray() and addArray() to store the array elements and to add two arrays.

In the main() function, we are creating an object A of class Array, reading the inputted array by the user using getArray() function, and finally calling the addArray() member function to add two arrays. The addArray() function contains the logic to add two arrays and printing the result.

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

Comments and Discussions!

Load comments ↻





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