This blog is all about C, C++,JAVA, and Data structures and RDBMS..
Friday, 16 November 2012
Functions and Structures in C++
Functions and Structures:
Passing by Reference (address):
It is certainly possible to pass structures by value, which passes a copy of the original structure to a function. The disadvantage to this process is evident when dealing with large structures which will increase memory requirements and slow the system down. Consequently, passing by reference is the most economical method of dealing with structures and functions. The function will access the actual address locations of where the structures are stored as opposed to working with copies of the structures.
//Sample Program using STRUCTURES and FUNCTIONS ...
//shows global nature of structure, passed by REFERENCE, use of ARRAY.
# include <iostream.h>
# include "apstring.cpp"
# include <apvector.h>
struct STUDENT_TYPE
{
apstring name, course;
double average, finalExam;
};
//function prototypes
STUDENT_TYPE get_student( );
void print_student(STUDENT_TYPE & pupil);
int main(void)
{
//declare the array of students
apvector <STUDENT_TYPE> list(10);
// input the list of students
for(int i = 0; i < 10; i++)
{
cout<<"Please enter information for student " << i+1 << endl << endl;
list[ i ] = get_student( ); //use function to get individual info
}
// print the array of students one struct at a time
for(int j = 0; j < 10; j++)
{
print_student(list [ j ] );
}
return 0;
}
//function to read in structure information (returns a structure)
STUDENT_TYPE get_student( )
{
STUDENT_TYPE pupil;
apstring dummy;
cout << "Enter the name (last name, first name): ";
getline( cin, pupil.name);
cout << "Enter the course name: ";
getline( cin, pupil.course);
cout << "Enter the course average: ";
cin>>pupil.average;
cout << "Enter the final exam grade: ";
cin>> pupil.finalExam;
getline(cin,dummy);
cout<<endl <<endl;
return pupil;
}
//function to print structure
void print_student(STUDENT_TYPE &pupil)
{
cout << "Name: " <<pupil.name<< endl;
cout << "Course: " <<pupil.course <<endl;
cout << "Average: " << pupil.average << endl;
cout << "Final Exam: " << pupil.finalExam << endl <<endl;
return;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment