MCS-011 Problem Solving and Programming

Admin | First year, Semester1

Chapters

Newsletter

Declaration of Structures

A structure (or struct) is a user-defined data type that allows you to combine different data types into a single unit. Structures are used to represent a record or a collection of related data items.

The struct keyword is used to define a structure. Here's the general syntax:

struct structure_name {
data_type member1; data_type member2; ... data_type memberN; };

Example

Let's say we want to create a structure to represent a student with the following attributes:

Name, Age, GPA

Here's how we can declare this structure in C:

#include
#include // Declaration of the structure struct Student { char name[50]; int age; float gpa; }; int main() { // Declaration of a structure variable struct Student student1; // Assigning values to the structure members strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8; // Printing the structure members printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa); return 0; }


Explanation

Structure Declaration:

struct Student {
char name[50]; int age; float gpa; };

This declares a new structure type named Student with three members: name (a character array of size 50), age (an integer), and gpa (a float).


Structure Variable Declaration:

struct Student student1;

This creates a variable student1 of type struct Student.


Assigning Values:

strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8;

The strcpy function is used to copy the string "John Doe" into the name member of student1. The age and gpa members are assigned values directly.


Accessing Structure Members:

printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa);

The members of the structure are accessed using the dot (.) operator.


typedef keyword

In C programming, typedef is a keyword used to create an alias or a new name for an existing data type. This can simplify code and improve readability, especially when dealing with complex data types such as structures, pointers, and arrays.

The general syntax for typedef is:

typedef existing_type new_type_name;

Example with Basic Data Types

#include
typedef unsigned long ulong; int main() { ulong a = 1000; printf("%lu\n", a); return 0; }

In this example, unsigned long is given a new name ulong. Now, you can use ulong as an alias for unsigned long.


Example with Structures

Using typedef with structures is very common and useful. Here's an example:

Without typedef:

#include
#include struct Student { char name[50]; int age; float gpa; }; int main() { struct Student student1; strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8; printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa); return 0; }

With typedef:

#include
#include typedef struct { char name[50]; int age; float gpa; } Student; int main() { Student student1; strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8; printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa); return 0; }


Explanation

  1. Without typedef:

    struct Student {
    char name[50]; int age; float gpa; };

    You have to use the struct keyword every time you declare a variable of this type:

    struct Student student1;
  2. With typedef:

    typedef struct {
    char name[50]; int age; float gpa; } Student;

    The typedef keyword creates an alias Student for the structure type. Now you can declare variables without using the struct keyword:

    Student student1;


Benefits of typedef

  1. Simplifies the syntax and makes the code easier to read.
  2. If the underlying data type changes, you only need to update the typedef definition.
  3. Improves code portability by allowing you to define platform-specific types.


Declaration of Structures

A structure (or struct) is a user-defined data type that allows you to combine different data types into a single unit. Structures are used to represent a record or a collection of related data items.

The struct keyword is used to define a structure. Here's the general syntax:

struct structure_name {
data_type member1; data_type member2; ... data_type memberN; };

Example

Let's say we want to create a structure to represent a student with the following attributes:

Name, Age, GPA

Here's how we can declare this structure in C:

#include
#include // Declaration of the structure struct Student { char name[50]; int age; float gpa; }; int main() { // Declaration of a structure variable struct Student student1; // Assigning values to the structure members strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8; // Printing the structure members printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa); return 0; }


Explanation

Structure Declaration:

struct Student {
char name[50]; int age; float gpa; };

This declares a new structure type named Student with three members: name (a character array of size 50), age (an integer), and gpa (a float).


Structure Variable Declaration:

struct Student student1;

This creates a variable student1 of type struct Student.


Assigning Values:

strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8;

The strcpy function is used to copy the string "John Doe" into the name member of student1. The age and gpa members are assigned values directly.


Accessing Structure Members:

printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa);

The members of the structure are accessed using the dot (.) operator.


typedef keyword

In C programming, typedef is a keyword used to create an alias or a new name for an existing data type. This can simplify code and improve readability, especially when dealing with complex data types such as structures, pointers, and arrays.

The general syntax for typedef is:

typedef existing_type new_type_name;

Example with Basic Data Types

#include
typedef unsigned long ulong; int main() { ulong a = 1000; printf("%lu\n", a); return 0; }

In this example, unsigned long is given a new name ulong. Now, you can use ulong as an alias for unsigned long.


Example with Structures

Using typedef with structures is very common and useful. Here's an example:

Without typedef:

#include
#include struct Student { char name[50]; int age; float gpa; }; int main() { struct Student student1; strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8; printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa); return 0; }

With typedef:

#include
#include typedef struct { char name[50]; int age; float gpa; } Student; int main() { Student student1; strcpy(student1.name, "John Doe"); student1.age = 20; student1.gpa = 3.8; printf("Name: %s\n", student1.name); printf("Age: %d\n", student1.age); printf("GPA: %.2f\n", student1.gpa); return 0; }


Explanation

  1. Without typedef:

    struct Student {
    char name[50]; int age; float gpa; };

    You have to use the struct keyword every time you declare a variable of this type:

    struct Student student1;
  2. With typedef:

    typedef struct {
    char name[50]; int age; float gpa; } Student;

    The typedef keyword creates an alias Student for the structure type. Now you can declare variables without using the struct keyword:

    Student student1;


Benefits of typedef

  1. Simplifies the syntax and makes the code easier to read.
  2. If the underlying data type changes, you only need to update the typedef definition.
  3. Improves code portability by allowing you to define platform-specific types.


Accessing Structure Members

You can access the members of the structure using the dot operator (.). The general syntax is:

structureVariable.memberName

Here’s how you can assign values to the members of the person1 variable and then access them:

#include <stdio.h>
#include <string.h> struct Person { char name[50]; int age; float height; }; int main() { struct Person person1; // Assigning values to person1's members strcpy(person1.name, "John Doe"); person1.age = 30; person1.height = 5.9; // Accessing and printing the values of person1's members printf("Name: %s\n", person1.name); printf("Age: %d\n", person1.age); printf("Height: %.1f\n", person1.height); return 0; }


person1.name accesses the name member of person1, person1.age accesses the age member, person1.height accesses the height member.


Initializing Structures

Initializing structures in programming involves setting the values of structure members at the time of declaration. This can be done in several ways, depending on the programming language being used. Here's an explanation with examples in C.

Basic Structure Initialization

You can initialize a structure at the time of declaration by providing a list of values in curly braces. The values are assigned to the structure members in the order they are declared.

Example

Consider the Person structure from the previous example:

struct Person {
char name[50]; int age; float height; };

You can initialize an instance of this structure as follows:

struct Person person1 = {"John Doe", 30, 5.9};

here, "John Doe" is assigned to the name member, 30 is assigned to the age member, 5.9 is assigned to the height member.


Newer / Advanced Concepts 

Designated Initializers (C99 and later)

C99 introduced designated initializers, which allow you to specify the values for specific members of the structure. This makes the code more readable and less error-prone, especially when dealing with large structures.

Example

You can use designated initializers like this:

struct Person person2 = {.name = "Jane Smith", .age = 25, .height = 5.7};

In this case, the values are explicitly assigned to the corresponding members, regardless of their order in the structure definition.

Partial Initialization

If you do not provide initializers for all members, the uninitialized members are set to zero (or equivalent for the member type).

Example

struct Person person3 = {"Alice"};

here, name is initialized to "Alice", age is initialized to 0 (default integer value), height is initialized to 0.0 (default float value).


Structure as Function Argument

Using structures as function arguments allows you to pass complex data types to functions in a structured way. You can pass structures to functions either by value or by reference (using pointers). Here’s an explanation with examples in C.

Passing Structures by Value

When a structure is passed by value, a copy of the entire structure is passed to the function. This means changes made to the structure within the function do not affect the original structure.

Example

Consider the Person structure:

struct Person {
char name[50]; int age; float height; };

Here’s how you pass it by value:

#include <stdio.h>
#include <string.h> struct Person { char name[50]; int age; float height; }; void printPerson(struct Person p) { printf("Name: %s\n", p.name); printf("Age: %d\n", p.age); printf("Height: %.1f\n", p.height); } int main() { struct Person person1 = {"John Doe", 30, 5.9}; printPerson(person1); return 0; }

here, printPerson(struct Person p) is a function that takes a Person structure by value and prints its members, In main(), printPerson(person1) is called, passing person1 by value to the function, Inside printPerson, a copy of person1 is used.


Passing Structures by Reference

Passing structures by reference involves passing a pointer to the structure. This allows the function to modify the original structure.

Example

Here’s how you pass a structure by reference:

#include <stdio.h>
#include <string.h> struct Person { char name[50]; int age; float height; }; void updatePerson(struct Person *p) { p->age += 1; p->height += 0.1; } void printPerson(struct Person p) { printf("Name: %s\n", p.name); printf("Age: %d\n", p.age); printf("Height: %.1f\n", p.height); } int main() { struct Person person1 = {"John Doe", 30, 5.9}; updatePerson(&person1); // Pass by reference printPerson(person1); return 0; }


here, updatePerson(struct Person *p) is a function that takes a pointer to a Person structure,

p->age += 1; increments the age member by 1 and, 

p->height += 0.1; increments the height member by 0.1.


in main(), updatePerson(&person1) is called, passing a pointer to person1 using the & operator, printPerson(person1) is then called to print the updated person1.


Using structures as function arguments helps manage complex data more effectively and allows for cleaner, more modular code.

Difference between Structures and Arrays

Structures and arrays are both used to group multiple pieces of data, but they serve different purposes and have distinct characteristics. Here’s a detailed comparison with examples:

Definitions

  1. Array: A collection of elements of the same data type stored in contiguous memory locations.
  2. Structure: A user-defined data type in C/C++ that groups variables of different data types under a single name.


Differences


ArraysStructure
Data Type Consistency
All elements must be of the same type.
Members can be of different types.
Memory Layout
Elements are stored in contiguous memory locations.
Members may not be stored contiguously due to padding for alignment.
Accessing Elements
Access elements using an index.
Access members using the dot operator (.).
Usage
Suitable for lists of similar items (e.g., a list of integers).
Suitable for grouping related but different items (e.g., a person's information).
Example
#include <stdio.h>
int main() { // Define an array of integers int numbers[5] = {1, 2, 3, 4, 5}; // Access and print array elements for(int i = 0; i < 5; i++) { printf("Element %d: %d\n", i, numbers[i]); } return 0; }
#include <stdio.h> #include <string.h> // Define a structure for a Person struct Person { char name[50]; int age; float height; }; int main() { // Declare and initialize a structure variable struct Person person1; strcpy(person1.name, "John Doe"); person1.age = 30; person1.height = 5.9; // Access and print structure members printf("Name: %s\n", person1.name); printf("Age: %d\n", person1.age); printf("Height: %.1f\n", person1.height); return 0; }


Unions

A union is a special data type in C and C++ that allows you to store different data types in the same memory location. Unlike structures, where each member has its own memory location, a union uses a single memory location for all its members. This means that only one member of the union can be accessed at any time.

Defining a Union

A union is defined similarly to a structure, but with the keyword union. Here’s a basic example:

#include <stdio.h>
union Data { int intValue; float floatValue; char charValue; };

In this example, union Data can hold an integer, a float, or a character, but only one of these types can be used at a time.

Initializing a Union

When initializing a union, you specify the initial value for one of its members. The other members will not have a meaningful value until they are assigned.

Example

#include <stdio.h>
union Data { int intValue; float floatValue; char charValue; }; int main() { // Initialize union union Data data; data.intValue = 10; // Only intValue is initialized printf("Integer value: %d\n", data.intValue); // Changing the value to float data.floatValue = 3.14; printf("Float value: %.2f\n", data.floatValue); // Changing the value to char data.charValue = 'A'; printf("Char value: %c\n", data.charValue); // Printing all members to show the overlap printf("Integer value after char assignment: %d\n", data.intValue); printf("Float value after char assignment: %.2f\n", data.floatValue); return 0; }

Accessing Union Members

Since a union shares the same memory for all its members, writing to one member affects the value of all other members due to memory overlap.


  1. Initialization: data.intValue = 10; initializes the intValue member, When data.intValue is printed, it shows 10.
  2. Reassigning: data.floatValue = 3.14; changes the value of floatValue, when data.floatValue is printed, it shows 3.14. The intValue may show a different value because the memory used for floatValue overlaps with intValue.
  3. Further Reassignment: data.charValue = 'A'; changes the value of charValue, whendata.charValue is printed, it shows 'A'. The intValue and floatValue will now show values affected by this assignment due to overlapping memory.


Unions are useful for saving memory when you need to store different types of data but only one type at a time. They are particularly useful in low-level programming and embedded systems.

About John Doe

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Report an issue

Related Posts

3 Comments

John Doe

5 min ago

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Reply

John Doe

5 min ago

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Reply