Structures in C
C gives us option to define our own data type.
This is called as user-defined data type.
We have 3 user defined data types in C:
Structure is collection of elements of same data type.
Syntax:
struct structure_name
{
...
...
};
Note:
In arrays, we can declare multiple variables of only one type but in structure we can create multiple variables of various data types.
Let's see program:
Output:
We have 3 user defined data types in C:
- Structure
- Union
- Enumeration
Structure is collection of elements of same data type.
Syntax:
struct structure_name
{
...
...
};
Note:
- For declaring a structure we use struct keyword.
- Structure ends with a semicolon.
- We can have an array of structures.
- We can have structure inside another structure.
- For accessing any element in structure use dot(.) operator.
- To find out size of structure use sizeof(struct structure_name)
- Order of declaration must be same if structure is directly initialized.
In arrays, we can declare multiple variables of only one type but in structure we can create multiple variables of various data types.
Let's see program:
#include<stdio.h>
void main()
{
int i;
struct student
{
char name[10];
int rno;
float m1,m2,m3;
};
struct student st;
printf("Enter
name: ");
gets(st.name);
printf("Enter
Roll Number: ");
scanf("%d",&st.rno);
printf("Enter
3 marks: ");
scanf("%f%f%f",&st.m1,&st.m2,&st.m3);
printf("\n");
printf("Entered
name: ");
puts(st.name);
printf("Entered
Roll Number: %d",st.rno);
printf("\nEntered
3 marks are: %f %f %f\n",st.m1,st.m2,st.m3);
printf("\n");
}Output:
No comments:
Post a Comment