Chapter 9: Structures

Structures are a powerful feature in C programming that allow you to create custom data types by grouping related variables together. In this chapter, we'll delve into structures and understand their concept and usage. You'll learn how to define and initialize structures, access their members, and use structures in functions and arrays. Real-world examples will illustrate the practical applications of structures in organizing and manipulating complex data.

Example:

#include <stdio.h>


// Define a structure for a person

struct Person {

   char name[50];

   int age;

};


int main() {

   // Declare a structure variable

   struct Person person1;


   // Initialize structure members

   strcpy(person1.name, "John Doe");

   person1.age = 25;


   // Access and print structure members

   printf("Name: %s\n", person1.name);

   printf("Age: %d\n", person1.age);


   return 0;

}

Explanation:

We define a structure called Person that consists of two members: name (a character array) and age (an integer). We declare a structure variable called person1. We initialize the structure members using the strcpy() function to copy the name and direct assignment for the age. Using printf(), we display the values of the structure members.

To compile and run the program, follow the same steps as in the previous chapters.

In the next chapter, we'll explore file handling, which is essential for reading from and writing to files in C programming. 

No comments:

Post a Comment

Chapter 10: File Handling

  File handling is crucial for reading from and writing to files in C programming. In this chapter, we'll dive into file handling and un...