C program to demonstrate named initialization in a structure

      Structures are user defined data types which can hold variables of different data types. The variables in a structure are accessed using dot(.) operator i.e., structure_name.variable_name. The same is used for named initialization – initialization of structure variables after accessing them. If variables are not initialized they will take the default value which were defined in the structure definition (name initialization). C program to demonstrate named initialization in a structure

Source Code for named Initialization:

struct traveler             // Step 1
	int class;
	char train_num[40];
	char coach_num[6];
	int seat_num;
	char from[30];
	char to[30];
	char gender[10];
	int age;
	int dep_date[10];
	char name[80];
struct traveler passenger8 =    //Step 2
.name = "JIT SINHA",
.to = "Jaipur",
.from = "Raigarh",
.train_num = "superfast 154",
.dep_date[0] = 30,
.dep_date[1] = 8,
.dep_date[2] = 2010,
.gender = "M",
.age = 28,
.class = 1
int main()
printf("\nenter coach number:");    //Step 3
printf("\nenter seat number:"); 
scanf("%d", &passenger8.seat_num);   //Step 3
printf("\nxxxxxxxxx Ticket xxxxxxxxx");
printf("\n\n\nName of Ticket holder : %s",passenger8.name); //Step 4
printf("\n\nTrain : %s:",passenger8.train_num);             //Step 4
printf("\n\nFrom : %s Date of Departure:",passenger8.from); //Step 4
for(int i=0;i<3;i++)      //Step 4
printf(": %d :",passenger8.dep_date[i]);          
printf("\n\nTo: %s", passenger8.to);
printf("\n\nCoach No.: %s Seat No.:%d",passenger8.coach_num,passenger8.seat_num);
return 0;

Sample Test cases :

    Enter coach number:2
    Enter seat number:5
    xxxxxxxxx Ticket xxxxxxxxx

    Name of Ticket holder : JIT SINHA
    Train : superfast 154:
    From : Raigarh Date of Departure:: 30 :: 8 :: 2010 :
    To: Jaipur
    Coach No.: 2 Seat No.:5


Step 1: The structure ‘traveller’ is defined using the struct keyword.

Step 2: Some of the contents of the variable ‘passenger8’ are intitalized by accesing them with dot(.) operator.

Step 3: The other variables of the passenger8 are aassigned to some value by reading input from the input screen.

Step 4: The contents of a structure variable ‘passenger8’ are printed on the output screen using printf() function.

More Content:Explore More