Basic Structure Programs
Question:1
C program to declare a structure named student with attributes as roll, name and per. Take input for the details and display them.
Sol:
#include<stdio.h> struct student { int roll; char name[20]; float per; }; //}s; //struct student s; int main() { struct student s; printf("Enter roll,name and per "); scanf("%d %s %f",&s.roll,s.name,&s.per); printf("Roll no %d Name %s Per %.2f\n",s.roll,s.name,s.per); return(0); }
/* Output */ Enter roll,name and per 101 Amit 96.36 Roll no 101 Name Amit Per 96.36
Note:
1. When the definition of the structure is given outside the definition of the function then it is a global structure.
2. If the structure is global then we can declare global as well as local structure variables.
3. When the definition of the structure is given inside the definition of the function then it is a local structure.
4. If the structure is local then we can only declare local structure variables.
Example:2
Example of local structure
#include<stdio.h> int main() { struct student { int roll; char name[20]; float per; }; struct student s; printf("Enter roll,name and per "); scanf("%d %s %f",&s.roll,s.name,&s.per); printf("Roll no %d Name %s Per %.2f\n",s.roll,s.name,s.per); return(0); }
/* Output */ Enter roll,name and per 102 Sumit 98.63 Roll no 102 Name Sumit Per 98.63
Example:2
C program to Declare a structure named employee with attributes as empno, name and salary. Take input for the details and display them.
Sol:
#include<stdio.h> struct employee { int empno; char name[20]; float sal; }; //}e; //struct employee e; int main() { struct employee e; printf("Enter empno,name and salary "); scanf("%d %s %f",&e.empno,e.name,&e.sal); printf("Empno %d Name %s Salary %.2f\n",e.empno,e.name,e.sal); return(0); }
/* Output */ Enter empno,name and salary 1001 Kapil 54000 Empno 1001 Name Kapil Salary 54000.00
Example:3
C program to Declare a structure named bank with attributes as accno, name, and bal. Take input for the details and display them.
Sol:
#include<stdio.h> struct bank { int accno; char name[20]; float bal; }; //}b; //struct bank b; int main() { struct bank b; printf("Enter accno,name and balance "); scanf("%d %s %f",&b.accno,b.name,&b.bal); printf("Accno %d Name %s Balance %.2f\n",b.accno,b.name,b.bal); return(0); }
/* Output */ Enter accno,name and balance 1005 Kunal 75000 Accno 1005 Name Kunal Balance 75000.00