Why Learn?
Suppose there is a structure called Student which contains the student’s name, role, marks etc. You want to pass marks to a function and get the grade. In that case you can pass only the marks member instead of passing your entire structure. This reduces memory consumption and makes the code readable.
Example
I created a structure called Student and passed the marks and name as arguments to separate functions.
#include
#include
//Defome a structure named student
struct Student{
char name[50];
int roll;
float marks;
};
//Function to calculate grade based on marks
//It takes a single float argument (the marks)
void calculationGrade(float marks){
printf("Marks: %.2f\n",marks);
if(marks >= 80){
printf("Grade: A+\n");
}else if(marks >= 70){
printf("Grade: A\n");
}else if(marks >= 60){
printf("Grade: B\n");
}else{
printf("Grade: F\n");
}
}
//Function to print the student's name in a fancy way
//It takes a single string (char array) argument
void printName(char name[]){
printf("Student Name: %s\n",name);
}
int main(){
//Create a structure variable
struct Student student1;
//Assign values to the structure members
strcpy(student1.name, "Tapas Mondal");
student1.roll = 136;
student1.marks = 85.5;
//print the student's name by passing only the'name' member
printf("---Name Print Function---\n");
printName(student1.name); //Passing structure member 'name'
//Calculate grade by passing only the 'marks' member
printf("\n---Grade Calculation---\n");
calculationGrade(student1.marks);//passing structure member 'marks'
return 0;
}
Output:
---Name Print Function---
Student Name: Tapas Mondal
---Grade Calculation---
Marks: 85.50
Grade: A+
1. Structure Declaration
struct Student{
char name[50];
int roll;
float marks;
}
Here we have created a structure called Student which has 3 members: name (string), roll (integer number) and marks (float number).
2. Grade Calculation Function
void calculationGrade(float marks){
//...grade logic...
}
3. Grade Calculation Function
void printName(char name[]){
printf("Student Name: %s\n", name);
}
This function takes a character array and prints the name.
4. Used Main Function
int main(){
struct Student student1;
strcpy(student1.name, "Tapas Mondal");
student1.roll = 136;
student1.marks = 85.5;
printf("---Name Print Function---\n");
printName(student1.name); //Only Pass name
printf("\n---Grade Calculation---\n");
calculationGrade(student1.marks);//only pass marks
return 0;
}
- Creating a structure variable named Student1 and assigning a value to it
-
printName(Student1.name);The name member of theStudent1object is passed as an argument to theprintNamefunction in the statement calculateGrade(student1.marks);The statement marks member is passed to thecalculateGradefunction.
Output:
---Name Print Function---
Student Name: Tapas Mondal
---Grade Calculation---
Marks: 85.50
Grade: A+
