Structures in C Language

C Programming Structure

In this article you will learn about structures in C language.What is it, how to define it and use it in your program.


structure: It is a Collection of variables of different types under a single name.

                             
 struct student{
 char name[50];
 int age; float percentage; };

Here Struct is the keyword used to define structure and student is the name of the structure.

Creating Structure Variable: 

 struct student{             
 char name[50];
 int age;
 float percentage;
 }struct student s1,s2,s3;
Here S1,S2,S3 are the structure variables.We can access the members of the structures using these variables. 

There are two types of operators used for accessing members of a structure.
Member operator(.)
Structure pointer operator(->)

program representing array of structures

#include<stdio.h>
#include<string.h>
#define MAX 2
#define SUBJECTS 2

struct student{
char name[20];
int roll_no;
float marks[SUBJECTS];
};
int main()
{
       struct student arr_student[MAX];
       int i,j;
       float sum = 0;
       for(i=0;i<MAX;i++)
       {
             printf("\nEnter the details of student%d\n",i+1);
             printf("Enter Name: ");
             scanf("%d",&arr_student[i].name);
             printf("Enter roll_no: ");
             scanf("%d",&arr_student[i].roll_no);
                 for(j=0;j<SUBJECTS;j++)
                  {
                          printf("Enter marks: ");
                          scanf("%d",&arr_student[i].marks[j]);
                   }
       }
        printf("\n");
        printf("Name\troll_no\taverage\n\n");
       for(i = 0; i < MAX; i++ )
    {
        sum = 0;
        for(j = 0; j < SUBJECTS; j++)
        {
            sum = sum+ arr_student[i].marks[j];
        }
        printf("%s\t%d\t%.2f\n",arr_student[i].name, arr_student[i].roll_no, sum/SUBJECTS);
    }
 return 0;
}


Comments

Popular posts from this blog

Finding the second largest in an array