Code Snippets
C/C++ Code Snippets
C++ - Program to demonstrate example of Passing Structure within a function.
By: IncludeHelp, On 30 SEP 2016
In this example we will learn how we can pass a structure within a function?
Here we will pass a structure into the function and access function (function calling) as call by reference, using call by reference we can get changes made inside the function with structure.
In this example there is a structure named student with two variables name and rollNumber, we will read number of students to read.
We will read N student’s record through read() function and print entered value trough print() function; in both functions structure variables will be passed as call by reference.
C++ program - Demonstrate Example of Passing Structure within a Function
/*C++ - Program to demonstrate example of Passing
Structure within a function.*/
#include <iostream>
#include <iomanip>
using namespace std;
#define MAX 100
struct student{
char name[30];
int rollNumber;
};
void read(struct student &s)
{
cout<<"Enter name:";
cin.ignore(1);
cin.getline(s.name,30);
cout<<"Enter roll number:";
cin>>s.rollNumber;
}
void display (struct student s)
{
cout<<setw(30)<<s.name<<setw(10)<<s.rollNumber<<endl;
}
int main(){
struct student std[MAX];
int n,loop;
cout<<"Enter total number of students: ";
cin>>n;
//read n records
for(loop=0; loop<n; loop++){
read(std[loop]);
}
//print all records
cout<<"Entered records are:"<<endl;
cout<<setw(30)<<"Name"<<setw(20)<<"Roll Number"<<endl;
for(loop=0;loop<n;loop++){
display(std[loop]);
}
return 0;
}
Enter total number of students: 2
Enter name:Mike
Enter roll number:101
Enter name:Monty
Enter roll number:102
Entered records are:
Name Roll Number
Mike 101
Monty 102