Need code for writing a class
Write a class to input the name of student and marks of three subjects, calculate the total marks as well as average marks. Each subject has a maximum of 100 marks.
Write a class to input the name of student and marks of three subjects, calculate the total marks as well as average marks. Each subject has a maximum of 100 marks.
All you have to do is, to ask the user to input the name of a student and all other details. By using class you will do this in the form of functions. Then you need to show the record and before this, you will calculate the total and average.
Guide me about functions in class. And how we will call them in main function? I don’t have any experience of working with classes. Can we define functions in classes simply, as we define in main function? And what will be the code of accession?
Simply we define the class as:
Class Student()
{
Functions of class
}; ending of class
Int main()
{
Student s1;
S1.Showrecord(); //code of accessing the function of class "ShowRecord".
Return 0;
}
This is the simple method of declaring class and accessing functions of a class.
I have read the code in a class, that sometime we declare the function in a class and write the code of that function outside the class. Is it a good programming technique or not? And in this problem, can we use class inside declaration of a function and outside coding?
Both methods can be used in this problem. Because when you declare the function inside the class and write it’s code outside the class. It means you are just making the code separate from the class. It will not affect your program output. You are just making the code more understandable.
#include<iostream.h>
#include<conio.h>
Class std
{
Private:
Char name[15];
Float s1,s2,s3,total,avg;
Public:
Void getRec(void)
{
Cout<<”Enter the name of student”;
Cin>>name;
Cout<<”Enter Marks of First Subject”;
Cin>>s1;
Cout<<”Enter Marks of Second Subject”;
Cin>>s2;
Cout<<”Enter Marks of Third Subject”;
Cin>>s3;
Total=s1+s2+s3;
Avg=total/3.0;
}
Void ShowRec(void)
{
Clrscr();
Cout<<”Name of Student:”<<name<<endl;
Cout<<”Marks of First Subject:”<<s1<<endl;
Cout<<”Marks of Second Subject:”<<s2<<endl;
Cout<<”Marks of Third Subject:”<<s3<<endl;
Cout<<”Total Marks:”<<total<<endl;
Cout<<”Average Marks:”<<avg<<endl;
}
};
Int main()
{
Std abc;
Clrscr;
Abc.getrec(); //calling of get record function
Abc.showrec(); // calling of show record function
Return 0;
}
Try this code for the problem you have mentioned. Here you are defining class, and functions inside class, then calling them from main function. Check the output and tell me if you need more guidelines.
Thanks a lot MRobert and JBond. Your valuable guideline is very helpful for me.