Skip to main content

ProwessApps

Learn · Practice · Excel

Define a class Student with following details .
private members :- regno, name, marks and average marks of a class.
public -
input() - to accept all the values
display() - to display all data members on the screen
findavg() - to calculate average of class
showavg() - static function to display the average marks of class
Input details of 3 student , find their average marks and display it.

C++ Code Example — Miscellaneous Programs

ADVERTISEMENT

Define a class Student with following details .
private members :- regno, name, marks and average marks of a class.
public -
input() - to accept all the values
display() - to display all data members on the screen
findavg() - to calculate average of class
showavg() - static function to display the average marks of class
Input details of 3 student , find their average marks and display it.

Objective

Write a C++ program to calculate the average marks of a class using Static Variables and Static Functions.

Algorithm / Approach

  1. Define a class Student with a static int avg variable.
  2. Define a static void showAvg() function to print the average.
  3. Outside the class, explicitly initialize the static variable: int Student::avg = 0;.
  4. In main(), read 3 students into an array, calculate their average, and assign it to avg.
  5. Call the static function directly on the class: Student::showAvg().
main.cpp
#include<iostream>
using namespace std;
class Student {
 string name;
 int regno;
 int mark;
 static int avg;
 public :
 void input(){
  cout<<"Enter the name ";
  getline(cin,name);
  cout<<"Enter the reg no ";
  cin>>regno;
  cout<<"Enter the marks ";
  cin>>mark;
  cin.ignore(1,'\n');
 }
 void display(){
  cout<< name<<"\t"<< regno;
  cout<<"\t"<< mark<< endl;
 }
 void findAvg(Student a[]) {
  int sum = 0;
  for(int i = 0; i<3; i++) {
   sum = sum+a[i].mark;
  }
  avg = sum/3;
 }
 static void showAvg() {
 cout<<"Avg = "<< avg<< endl;;
 }
};
int Student::avg = 0;
int main() {
 Student s[3];
 for(int i =0; i<3; i++) {
  s[i].input();
 }
 for(int i =0; i<3; i++) {
  s[i].display();
 }
 s[0].findAvg(s);
 Student::showAvg();
 return 0;
}

Expected Output

Enter the name Alok 
Enter the reg no 12
Enter the marks 85
Enter the name Deepu
Enter the reg no 13
Enter the marks 90
Enter the name Ayan
Enter the reg no 11
Enter the marks 95
Alok	12	85
Deepu	13	90
Ayan	11	95
Avg = 90

Explanation of the Program

  • Normally, every object you create gets its own personal copy of the class variables. A static variable is completely different: there is only ONE copy of it shared across all objects of the class.
  • Similarly, a static function belongs to the class itself, not to any individual object. This is why we can call it using Student::showAvg() without needing a specific student object to call it on.

Complexity

Time Complexity O(n) - Where n is the number of students.
Space Complexity O(n) - To store the student objects.
ADVERTISEMENT