Array of structures

In C, an array of structures allows us to store multiple instances of a structure in one collection, making it convenient to handle related data sets (like student records, employee information, etc.) where each entry has the same structure. Let's go through how to use an array of structures step-by-step.

Define the Structure

Let's start by defining a structure to represent a student with name, rollNumber, and marks.

struct Student {
char name[50];
int rollNumber;
float marks;
};

Here:

  • name is an array to hold the student's name.
  • rollNumber is an integer to store the student's roll number.
  • marks is a floating-point number for the student's score.

Declare an Array of Structures

To store multiple students, we declare an array of struct Student. For example:

#include <stdio.h>
#include <string.h>

#define NUM_STUDENTS 5 // Define the number of students

struct Student {
char name[50];
int rollNumber;
float marks;
};

int main() {

    struct Student students[NUM_STUDENTS]; // Array of Student structures

    // Input student data and print it

    for (int i = 0; i < NUM_STUDENTS; i++) {

    printf("Enter details for student %d:\n", i + 1);
    printf("Name: ");
    fgets(students[i].name,50,stdin);

    printf("Roll Number: ");
    scanf("%d", &students[i].rollNumber);

    printf("Marks: ");
    scanf("%f", &students[i].marks);
    getchar();
    }

// Display student data

printf("\nStudent Information:\n");

for (int i = 0; i < NUM_STUDENTS; i++) {
printf("Student %d: Name = %s, Roll Number = %d, Marks = %.2f\n", i + 1, students[i].name, students[i].rollNumber, students[i].marks);

}
return 0;
}

In this code:

  • students is an array of struct Student with NUM_STUDENTS elements.
  • We use a for loop to input data for each student. Each students[i] is an individual Student structure where we can access fields using dot notation, such as students[i].name.
  • Another loop displays the information for each student.

Sorting Array of Structures (Example)

Let’s expand on this example by sorting the students based on their marks.

#include <stdio.h>
#include <string.h>

struct Student {
    char name[50];
    int rollNumber;
    float marks;
};

#define NUM_STUDENTS 3

void sortStudentsByMarks(struct Student students[], int size) {
    struct Student temp;

    for (int i = 0; i < size - 1; i++) {
        for (int j = i + 1; j < size; j++) {
            if (students[i].marks < students[j].marks) { // Descending order
                temp = students[i];
                students[i] = students[j];
                students[j] = temp;
            }
        }
    }
}

int main() {
    struct Student students[NUM_STUDENTS];

    // Input student data
    for (int i = 0; i < NUM_STUDENTS; i++) {
        printf("Enter details for student %d:\n", i + 1);
        printf("Name: ");
        fgets(students[i].name,50,stdin);
        printf("Roll Number: ");
        scanf("%d", &students[i].rollNumber);
        printf("Marks: ");
        scanf("%f", &students[i].marks);
        getchar();
    }

    // Sort students by marks
    sortStudentsByMarks(students, NUM_STUDENTS);

    // Display sorted student data
    printf("\nSorted Student Information by Marks (Descending):\n");
    for (int i = 0; i < NUM_STUDENTS; i++) {
        printf("Name = %s, Roll Number = %d, Marks = %.2f\n",
               students[i].name, students[i].rollNumber, students[i].marks);
    }

    return 0;
}

In this code:

  • We define a function sortStudentsByMarks that takes the students array and its size as parameters.
  • Using a nested loop, we sort the students based on their marks in descending order. We swap structures using a temporary Student variable.

Summary

  • An array of structures allows us to manage multiple records with a consistent format.
  • We can access each structure's members using dot notation (e.g., students[i].name).
  • Using loops, we can easily sort or process each element in the array of structures.

This approach is beneficial when working with collections of structured data

Example Programs

Define a structure named Vehicle with members model (character array), year (integer), and price (float). Create an array of 10 Vehicle structures and write a function to accept user input for each vehicle's details and Sort the array in descending order based on price.(University Question)
#include <stdio.h>
#include <string.h>

// Define the structure

struct Vehicle {

    char model[50];
    int year;
    float price;};

// Function to accept input for vehicles

void inputVehicles(struct Vehicle v[], int n) {

    for (int i = 0; i < n; i++) {

    printf("\nEnter details of vehicle %d:\n", i + 1);
    printf("Model: ");
    scanf(" %[^\n]", v[i].model); // read string with spaces
    printf("Year: ");
    scanf("%d", &v[i].year);
    printf("Price: ");
    scanf("%f", &v[i].price);

  }
}

// Function to sort vehicles in descending order based on price

void sortByPriceDescending(struct Vehicle v[], int n) {

    struct Vehicle temp;

  for (int i = 0; i < n - 1; i++) {
   for (int j = i + 1; j < n; j++) {
    if (v[i].price < v[j].price) {

               temp = v[i];
               v[i] = v[j];
               v[j] = temp;

           }
        }
    }
}

// Function to display vehicles

void displayVehicles(struct Vehicle v[], int n) {

  printf("\n%-20s %-10s %-10s\n", "Model", "Year", "Price");
  printf("---------------------------------------------\n");

   for (int i = 0; i < n; i++) {
    printf("%-20s %-10d %-10.2f\n", v[i].model, v[i].year, v[i].price);
    }
 }

int main() {

  struct Vehicle vehicles[10];
  inputVehicles(vehicles, 10);
  sortByPriceDescending(vehicles, 10);
  printf("\nVehicles sorted in descending order by price:\n");
  displayVehicles(vehicles, 10);

return 0;

}

Define a structure that can describe a hotel with the following members: name, address, grade, average room charge, and number of rooms. Write a function to print out hotels of a given grade, sorted in order of their average room charges. ( University Question)

#include <stdio.h>
#include <string.h>

// Define the hotel structure
struct Hotel {
    char name[100];
    char address[200];
    char grade;
    float avg_room_charge;
    int num_rooms;
};

// Function to input hotel details
void inputHotels(struct Hotel h[], int n) {
    for (int i = 0; i < n; i++) {
        printf("\nEnter details of hotel %d:\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", h[i].name);
        printf("Address: ");
        scanf(" %[^\n]", h[i].address);
        printf("Grade (A/B/C): ");
        scanf(" %c", &h[i].grade);
        printf("Average Room Charge: ");
        scanf("%f", &h[i].avg_room_charge);
        printf("Number of Rooms: ");
        scanf("%d", &h[i].num_rooms);
    }
}

// Function to print hotels of a given grade, sorted by room charge
void printHotelsByGradeSorted(struct Hotel h[], int n, char targetGrade) {
    struct Hotel filtered[100];
    int count = 0;

    // Filter hotels by grade
    for (int i = 0; i < n; i++) {
        if (h[i].grade == targetGrade) {
            filtered[count++] = h[i];
        }
    }

    // Sort filtered hotels by average room charge (ascending)
    for (int i = 0; i < count - 1; i++) {
        for (int j = i + 1; j < count; j++) {
            if (filtered[i].avg_room_charge > filtered[j].avg_room_charge) {
                struct Hotel temp = filtered[i];
                filtered[i] = filtered[j];
                filtered[j] = temp;
            }
        }
    }

    // Print result
    if (count == 0) {
        printf("\nNo hotels found with grade %c.\n", targetGrade);
        return;
    }

    printf("\nHotels of grade %c sorted by average room charge:\n", targetGrade);
    printf("%-20s %-25s %-10s %-10s\n", "Name", "Address", "Charge", "Rooms");
    printf("--------------------------------------------------------------\n");
    for (int i = 0; i < count; i++) {
        printf("%-20s %-25s %-10.2f %-10d\n", 
               filtered[i].name, 
               filtered[i].address, 
               filtered[i].avg_room_charge, 
               filtered[i].num_rooms);
    }
}

int main() {
    int n;
    char grade;
    struct Hotel hotels[100];

    printf("Enter number of hotels: ");
    scanf("%d", &n);

    inputHotels(hotels, n);

    printf("\nEnter the grade of hotel to search (A/B/C): ");
    scanf(" %c", &grade);

    printHotelsByGradeSorted(hotels, n, grade);

    return 0;
}

Write a function to print out hotels with an average room charge less than a specified value in the above problem.(University Question)

void printHotelsBelowCharge(struct Hotel h[], int n, float chargeLimit) {
    int found = 0;

    printf("\nHotels with average room charge less than %.2f:\n", chargeLimit);
    printf("%-20s %-25s %-10s %-10s %-10s\n", "Name", "Address", "Grade", "Charge", "Rooms");
    printf("--------------------------------------------------------------------------\n");

    for (int i = 0; i < n; i++) {
        if (h[i].avg_room_charge < chargeLimit) {
            printf("%-20s %-25s %-10c %-10.2f %-10d\n",
                   h[i].name, h[i].address, h[i].grade,
                   h[i].avg_room_charge, h[i].num_rooms);
            found = 1;
        }
    }

    if (!found) {
        printf("No hotels found with average room charge less than %.2f\n", chargeLimit);
    }
}

Given a list of cities, their literacy level, and the population, write a program to print the list cities sorted lexico graphically. Assume duplication in city names.. Break theties with the value of literacy level, and then the population. ( University Question)

#include <stdio.h>
#include <string.h>

#define MAX 100

struct City {
    char name[50];
    float literacy;
    int population;
};

// Function to swap two City structures
void swap(struct City *a, struct City *b) {
    struct City temp = *a;
    *a = *b;
    *b = temp;
}

// Custom comparison logic
int compare(struct City a, struct City b) {
    int name_cmp = strcmp(a.name, b.name);

    if (name_cmp < 0)
        return -1;
    else if (name_cmp > 0)
        return 1;
    else {
        // Same name, check literacy (higher first)
        if (a.literacy < b.literacy)
            return 1;
        else if (a.literacy > b.literacy)
            return -1;
        else {
            // Same literacy, check population (higher first)
            if (a.population < b.population)
                return 1;
            else if (a.population > b.population)
                return -1;
            else
                return 0;
        }
    }
}

int main() {
    struct City cities[MAX];
    int n;

    printf("Enter number of cities: ");
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        printf("\nCity %d:\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", cities[i].name);
        printf("Literacy Level: ");
        scanf("%f", &cities[i].literacy);
        printf("Population: ");
        scanf("%d", &cities[i].population);
    }

    // Bubble sort
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (compare(cities[j], cities[j + 1]) > 0) {
                swap(&cities[j], &cities[j + 1]);
            }
        }
    }

    printf("\nSorted list of cities:\n");
    printf("%-20s %-15s %-10s\n", "City", "Literacy", "Population");
    for (int i = 0; i < n; i++) {
        printf("%-20s %-15.2f %-10d\n", cities[i].name, cities[i].literacy, cities[i].population);
    }

    return 0;
}

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays