c-structures-examples-get-value-of-structure-variable-and-print-it
admin
#c-structures-examples-get-value-of-structure-variable--print-it
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.
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.
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.
#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);
}
Enter sno, marks, and name for student 1:
101 270 Alice
Enter sno, marks, and name for student 2:
102 300 Bob
Student 1: 101 270 Alice 90.00
Student 2: 102 300 Bob 100.00
struct student
is declared with members sno
, m
, sname
, and per
.scanf
to input values for student number, marks, and name.printf
.
In this tutorial, we defined a student
struct, input values for two records, and printed them. Structs are a fundamental part of C programming, enabling developers to handle complex data efficiently. Mastering structs will improve your ability to write clean and maintainable code. Try implementing more examples to strengthen your understanding of this powerful feature.