Pr.Pg Next Pg

Declare and Initialize Structure Variables

 

 

Example: Program to demonstrate declaring and initializing structure variables in C

 Sam Madam

// Program to demonstrate declaring and initializing structure variables in C

#include<stdio.h>

struct student

{

int rollno;

char name[20];

float percent;

}s1={101,"SAM",80.75}; // declare and initialize s1 variable

 

void main()

{

struct student s2,s3,s4={104,"John",75.00}; // declare s2,s3,s4 variables and initialize s4

 

printf("Enter Roll no of student :");

scanf("%d",&s2.rollno);

printf("Enter name of student :");

scanf("%s",&s2.name);

printf("Enter Percentage :");

scanf("%f",&s2.percent);

s3=s2; // copy s2 into s3

printf("%d %s %f\n",s1.rollno,s1.name,s1.percent);

printf("%d %s %f\n",s2.rollno,s2.name,s2.percent);

printf("%d %s %f\n",s3.rollno,s3.name,s3.percent);

printf("%d %s %f\n",s4.rollno,s4.name,s4.percent);

}

Output

Enter Roll no of student :50

Enter name of student :Jack

Enter Percentage :65.50

101 SAM 80.750000

50 Jack 65.500000

50 Jack 65.500000

104 John 75.000000

  • In above program s1 variable is declared and initialize along with structure declaration.

  • Variable s2,s3 and s4 are declared using struct statement and at same time, variable s4 is initialize.

  • In variable s2 we are entering data using regular scanf input method.

  • Member of s2 structure variables are copied to s3


Pr.Pg border                                              Next Pg