Program – 1
Objective: Write a program that uses a class where member functions are defined inside the
class.
Program:
#include<iostream>
#include<math.h>
using namespace std;
class studentInfo{
// Member variables
string rollNo;
string name;
float marks;
public:
//Member Functions
void getInfo(studentInfo st[], int size){
for(int i=0; i<size; i++){
cout<<"Enter roll no: ";
cin>>st[i].rollNo;
cin.ignore();
cout<<"Enter name: ";
getline(cin, st[i].name);
cout<<"Enter marks obtained: ";
cin>>st[i].marks;
cin.ignore();
cout<<endl;
}
}
void displayStudent(studentInfo st[], int size){
cout<<"Student details"<<endl;
for(int i=0; i<size; i++){
cout<<"Roll no: "<<st[i].rollNo<<endl;
cout<<"Name: "<<st[i].name<<endl;
cout<<"Marks: "<<st[i].marks<<endl<<endl;
}
}
int avgMarks(studentInfo st[], int size){
int totalMarks = 0;
for(int i=0; i<size; i++){
totalMarks += st[i].marks;
}
int avgMarks = totalMarks/size;
return avgMarks;
}
};
int main(){
cout<<"Enter number of students: ";
int size;
cin>>size;
studentInfo st[size];
//Creating an object of class
studentInfo obj;
obj.getInfo(st, size);
cout<<endl;
obj.displayStudent(st, size);
cout<<endl;
int avMarks = obj.avgMarks(st, size);
cout<<"Average marks: "<<avMarks<<endl<<endl;
return 0;
}
Output:
Program – 2
Objective: Write a program that uses a class where member functions are defined outside the
class.
Program:
#include<iostream>
using namespace std;
class mathsFunction{
public:
//Declaring Function
void fact(int n);
};
//Defining Function using scope resolution variable - ::
void mathsFunction :: fact(int num){
int fact=1;
for(int i=1; i<=num; i++){
fact=fact*i;
}
cout<<"Factorial of "<<num<<" is "<<fact<<endl;
}
int main(){
mathsFunction obj;
obj.fact(7);
}
Output:
Program – 3
Objective: Write a program that demonstrates the use of zero argument and parameterized
argument.
Program:
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
public:
Student() {
name = "not known";
age = 0;
cout << "Zero-argument constructor called." <<endl;
}
Student(string n, int a) {
name = n;
age = a;
cout << "Parameterized constructor called." << endl;
}
void displayDetails() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Student s1;
s1.displayDetails();
Student s2("shashank bhadoriya", 18);
s2.displayDetails();
return 0;
}
Output: