C++ Program to Find Sum and Average Using Class





Class is the expanded concept of data structure, instead of holding only data, it holds both data and function.

Following is a sample program to find the average and the sum of ‘n’ numbers using class.

#include<iostream.h>

#include<conio.h>

Class sum

{

Private:

Int n;

Float a [100], sum;

Public:

Void output ()

{

Sum=0;

Cout<<”\n How many numbers?”;

Cin>>n;

Cout<<”\n enter the element:”;

For (i=0; i<n; i++)

{

Cin>>a[i];

Sum=sum+a[i];

}

Average=sum/n;

Cout<<”\n average=”<<average;

}

};

Void main ()

{

Sum obj;

Obj.ouput ();

getch ();

}

The class named “sum” has been declared in the program. There are two access specifiers : Private and public in the program. The objects inside private are used for internal use of class and the objects in public is used for the actual saving and calculations of datas.

Inside the main function an object “Obj’ of class type sum has been declared and the output function inside the class ‘sum’ is called, which gives the output.



Related posts:

  1. Class In C++ Class in c++ Class is a group of similar object....
  2. Class Template Class Template A class template is a class definition that...
  3. Array of class objects Array of class objects and single inheritance A program consisting...
  4. Class Hierarchies Class Hierarchies The relationship between a base ad derived classes...
  5. Array Of Class Object Array of class objects Array is a collection of similar...