C Structure Test
Syntax
struct structure_name {
data_type1 member_name1;
data_type2 member_name2;
...
data_typeN member_nameN;
};
Example
#include <stdio.h>
#include <string.h>
struct student {
int roll_no;
char name[50];
float percentage;
};
int main() {
struct student s1;
s1.roll_no = 1;
strcpy(s1.name, "John Doe");
s1.percentage = 86.5;
printf("Student Roll Number: %d\n", s1.roll_no);
printf("Student Name: %s\n", s1.name);
printf("Student Percentage: %.2f\n", s1.percentage);
return 0;
}
Output
Student Roll Number: 1
Student Name: John Doe
Student Percentage: 86.50
Explanation
In C programming, a structure is a user-defined data type that groups related data of different data types. A structure is similar to a class in object-oriented programming. It has members that can be of different types, including primitive data types such as int, float, and char, as well as other structures.
Use
C structures are useful in a variety of situations, such as:
- Representation of complex data types that require grouping of data of different types.
- Encapsulation of data and functions as a single entity.
- Passing multiple values to functions as a single parameter.
- Creating custom data types that represent higher-level concepts.
Important Points
- Structures are user-defined data types that group related data members of different data types.
- Structures can be accessed using the dot operator (.) to access individual members.
- Structures can be passed to functions as parameters to consolidate data.
- Structures can be used to represent complex data types and encapsulate data and functions as a single entity.
Summary
C structures are user-defined data types that group related data members of different data types. They can be used to represent complex data types, encapsulate data and functions as a single entity, pass multiple values to functions as a single parameter, and create custom data types. Understanding their syntax and use cases can greatly enhance the functionality of your C programs.