CPP Arrays within a Class

Arrays within a Class

  • Arrays can be declared as the members of a class.
  • The arrays can be declared as private, public or protected members of the class.
  • To understand the concept of arrays as members of a class, consider this example.

A program to demonstrate the concept of arrays as class members

Example:

#include<iostream>

const int size=5;

class student

{

int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
} ;

void student :: getdata ()
{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}

void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}

void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}

Output:

Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343

Share This Page to Download:

Share to Download

Share This Page on:


Ask Question