Загрузка...

Structures and Functions|| Data Structures and Algorithms || Saral Bhasha me

Structures and Functions|| Data Structures and Algorithms || Saral Bhasha me

#structure #functions #datastructures #Clanguage #C++ #aktu #akturesults #ugc #algorithms

Structure and Function in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++

In this previous tutorial we learnt about structures, the compound data type that groups different types of variables. In this tutorial, we will learn how to pass structures as an argument to the function and how to return the structure from the function.

How to pass structure as an argument to function
Here we have a function printStudentInfo() which takes structure Student as an argument and prints the details of student using structure varaible. The important point to note here is that you should always declare the structure before function declarations, otherwise you will get compilation error.

#include iostream
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
void printStudentInfo(Student);
int main(){
Student s;
cout"Enter Student Name: ";
cin.getline(s.stuName, 30);
coutEnter Student Roll No: ";
cins.stuRollNo;
cout"Enter Student Age: ";
cins.stuAge;
printStudentInfo(s);
return 0;
}
void printStudentInfo(Student s){
coutStudent Record:endl;
cout"Name: "s.stuNameendl;
cout"Roll No: "s.stuRollNoendl;
cout"Age: "s.stuAge;
}
Output:

Enter Student Name: Rick
Enter Student Roll No: 666123
Enter Student Age: 19
Student Record:
Name: Rick
Roll No: 666123
Age: 19
How to return the Structure from a Function
In this example we have two functions one gets the values from user, assign them to structure members and returns the structure and the other function takes that structure as argument and print the details.

#include iostream
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
Student getStudentInfo();
void printStudentInfo(Student);
int main(){
Student s;
s = getStudentInfo();
printStudentInfo(s);
return 0;
}
/* This function prompt the user to input student
* details, stores them in structure members
* and returns the structure
*/
Student getStudentInfo(){
Student s;
cout"Enter Student Name: ";
cin.getline(s.stuName, 30);
coutEnter Student Roll No: ";
cins.stuRollNo;
coutEnter Student Age: ";
cins.stuAge;
return s;
}
void printStudentInfo(Student s){
coutStudent Record:"endl;
cout"Name: "s.stuNameendl;
coutRoll No: "s.stuRollNendl;
cout"Age: "s.stuAge;
}
Output:

Enter Student Name: Tyrion lannister
Enter Student Roll No: 333901
Enter Student Age: 39
Student Record:
Name: Tyrion lannister
Roll No: 333901
Age: 39

Видео Structures and Functions|| Data Structures and Algorithms || Saral Bhasha me канала Codemasters
Яндекс.Метрика

На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.

Об использовании CookiesПринять