How to Use Structs in C : complete guide
How to Use Structs in C: Get and Print Structure Variable Values
Structs are a powerful feature in C programming that allow you to group variables of different data types under a single name. This makes handling related data more efficient and organized. In this tutorial, we will learn how to create a structure, input its values, and display them with a practical example. This tutorial is beginner-friendly and uses easy-to-understand concepts.
What is a Struct in C?
A struct (short for structure) is a user-defined data type that groups related variables under one name. These variables, known as members, can have different data types. Structs are widely used in C for organizing complex data and simplifying operations.
Key Features of Structs:
- Enables grouping of variables with different types.
- Uses a single memory block for all members.
- Allows easy access to members via the struct's name or pointers.
Example: Program to Input and Print Struct Values
In this example, we define a struct called student with attributes for student number, name, marks, and percentage. We'll input the values for two student records and print them.
Code:
#include <stdio.h>
struct student {
int sno, m;
char sname[20];
float per;
};
void main() {
struct student s1, s2;
printf("\nEnter sno, marks, and name for student 1: ");
scanf("%d %d %s", &s1.sno, &s1.m, s1.sname);
s1.per = s1.m / 3.0;
printf("\nEnter sno, marks, and name for student 2: ");
scanf("%d %d %s", &s2.sno, &s2.m, s2.sname);
s2.per = s2.m / 3.0;
printf("\nStudent 1: %d %d %s %.2f", s1.sno, s1.m, s1.sname, s1.per);
printf("\nStudent 2: %d %d %s %.2f", s2.sno, s2.m, s2.sname, s2.per);
}
Pseudocode: Student Structure Program
Step 1: Start the program
Step 2: Define a structure student with:
-
Integer sno (student number)
-
Integer m (marks)
-
Character array sname
-
Float per (percentage)
Integer sno (student number)
Integer m (marks)
Character array sname
Float per (percentage)
Step 3: Declare two variables:
-
s1 and s2 of type student
s1 and s2 of type student
Step 4: Input details of Student 1
-
Read sno, marks, and name
-
Calculate percentage
Read sno, marks, and name
Calculate percentage
Step 5: Input details of Student 2
-
Read sno, marks, and name
-
Calculate percentage
Read sno, marks, and name
Calculate percentage
Step 6: Display Student 1 details
-
Student Number
-
Marks
-
Name
-
Percentage
Student Number
Marks
Name
Percentage
Step 7: Display Student 2 details
-
Student Number
-
Marks
-
Name
-
Percentage
Student Number
Marks
Name
Percentage
Step 8: End the program
Conclusion
About the Author
I am a Data Science Engineer specializing in Machine Learning, Generative AI, Cloud Computing, Hadoop, Scala, Java, and Python. With expertise in cutting-edge technologies, I share valuable insights, blogging tips, and tech tutorials on DeveloperIndian.com, helping developers and data enthusiasts stay ahead in the industry.
Comments
Post a Comment