C Online Compiler
Example: Structure Definition and Initialization in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Structure Definition and Initialization #include <stdio.h> #include <string.h> // For strcpy int main() { // Step 1: Define the structure for a student struct Student { int studentID; char name[50]; char major[30]; float gpa; }; // Step 2: Declare variables of type struct Student struct Student s1; struct Student s2; // Step 3: Initialize members of s1 s1.studentID = 1001; strcpy(s1.name, "John Doe"); strcpy(s1.major, "Computer Science"); s1.gpa = 3.85; // Step 4: Initialize members of s2 using initializer list (C99 and later) struct Student s3 = {1002, "Jane Smith", "Biology", 3.92}; // Step 5: Print details of s1 printf("--- Student 1 Details ---\n"); printf("ID: %d\n", s1.studentID); printf("Name: %s\n", s1.name); printf("Major: %s\n", s1.major); printf("GPA: %.2f\n\n", s1.gpa); // Step 6: Print details of s3 printf("--- Student 3 Details ---\n"); printf("ID: %d\n", s3.studentID); printf("Name: %s\n", s3.name); printf("Major: %s\n", s3.major); printf("GPA: %.2f\n", s3.gpa); return 0; }
Output
Clear
ADVERTISEMENTS