Array in Class

/* Sum of array elements with class */
#include<iostream>
using namespace std;

class arrayElementSum {

	/* Declearation of array */
	int array[5];
	public:
		int sum;
	
		arrayElementSum(void) {
			cout << "Enter data for array:" << endl;

			/* '(sizeof(array)/sizeof(*array))' use to get length of the array */
			for(int i=0; i < (sizeof(array)/sizeof(*array)); i++)
				cin >> array[i];
				
		}

		void calculation() {
			for(int i=0; i< (sizeof(array)/sizeof(*array)); i++)
				sum += array[i];
		}
};

int main() {
	arrayElementSum arrayEsum = arrayElementSum();
	arrayEsum.calculation();
	
	/* Access public member variable 'sum' */
	cout << "Sum of array elements: " << arrayEsum.sum << endl;
	return 0;
}


/* Output */
Enter data for array:
1
2
3
4
5

Sum of array elements: 15

Comments (0)

  • To add your comment please or

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.

Got It!