Thursday, November 28, 2019

Structs 1

The following code would introduce to structs.



#include <iostream>
using namespace std;

struct student //this is a struct named student
{
 int id;
 string name;
 int age;
 int grade;
};

void showinfo(int id, string name, int age, int grade) //passing all the struct variables
{
cout <<"Id: "<<id<<endl;
cout <<"Name: "<<name<<endl;
cout <<"Age: "<<age<<endl;
cout <<"Grade: "<<grade<<endl;
}

void showinfo2(student n)//passing the whole struct
{
cout <<"Id: "<<n.id<<endl;
cout <<"Name: "<<n.name<<endl;
cout <<"Age: "<<n.age<<endl;
cout <<"Grade: "<<n.grade<<endl;
}

// Using value parameter for structure can
// slow down a program, waste space
// Using a reference parameter will speed up
// program, but function may change data in
// structure
// Using a const reference parameter allows
// read-only access to reference parameter,
// does not waste space, speed

void showinfo3(const student &n)//passing the whole struct
{
cout <<"Id: "<<n.id<<endl;
cout <<"Name: "<<n.name<<endl;
cout <<"Age: "<<n.age<<endl;
cout <<"Grade: "<<n.grade<<endl;
}



int main()
{
//
student student1;
cout << "Enter student's name: ";
cin >> student1.name;
cout << "\n";
cout << "Enter student's age: ";
cin >> student1.age;
cout << "\n";
cout << "Enter student's id: ";
cin >> student1.id;
cout << "\n";
cout << "Enter student's grade: ";
cin >> student1.grade;
cout << "\n";
cout << "\n";
cout << "Here's student1's info:\n";
showinfo(student1.id,student1.name,student1.age,student1.grade);
cout << "\n";
cout << "\n";
student student2={470175,"Pazi",9,10}; //this is how a structure is initialized in a single line
cout << "Here's student2's info:\n";
showinfo(student2.id,student2.name,student2.age,student2.grade);
cout << "\n";
cout << "\n";
student student3={470165,"Nazi",9,10};
showinfo2(student3);
cout << "\n";
cout << "\n";
showinfo3(student3);
}

Ashikur Rahman

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.

0 comments:

Post a Comment

 

Copyright @ 2017 Codename: CPlusPlus.

Designed by Templateiy