Day 11 of Programming in C

Write 5 students record using struct datatype
1. Arrange the record alphabetically
2. Display the record with highest marks
3. Divide the record such that age less 18 and greater than equal to 18 into two segments


#include <stdio.h>
#include <string.h>
struct Student
{
    char name[50];
    int age;
    float marks;
};

void inputStudents(struct Student s[], int n);
void sortAlphabetically(struct Student s[], int n);
void displayHighestMarks(struct Student s[], int n);
void divideByAge(struct Student s[], int n);

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

    inputStudents(students, 5);
    sortAlphabetically(students, 5);

    printf("\n--- Students Sorted Alphabetically ---\n");
    for (int i = 0; i < 5; i++)
    {
        printf("Name: %s | Age: %d | Marks: %.2f\n", students[i].name, students[i].age, students[i].marks);
    }

    displayHighestMarks(students, 5);
    divideByAge(students, 5);

    return 0;
}

void inputStudents(struct Student s[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("Enter details for Student %d\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", s[i].name);
        printf("Age: ");
        scanf("%d", &s[i].age);
        printf("Marks: ");
        scanf("%f", &s[i].marks);
    }
}

void sortAlphabetically(struct Student s[], int n)
{
    struct Student temp;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (strcmp(s[i].name, s[j].name) > 0)
            {
                temp = s[i];
                s[i] = s[j];
                s[j] = temp;
            }
        }
    }
}

void displayHighestMarks(struct Student s[], int n)
{
    int maxIndex = 0;
    for (int i = 1; i < n; i++)
    {
        if (s[i].marks > s[maxIndex].marks)
        {
            maxIndex = i;
        }
    }

    printf("\n--- Student with Highest Marks ---\n");
    printf("Name: %s | Age: %d | Marks: %.2f\n", s[maxIndex].name, s[maxIndex].age, s[maxIndex].marks);
}

void divideByAge(struct Student s[], int n)
{
    printf("\n--- Students with Age < 18 ---\n");
    for (int i = 0; i < n; i++)
    {
        if (s[i].age < 18)
        {
            printf("Name: %s | Age: %d | Marks: %.2f\n", s[i].name, s[i].age, s[i].marks);
        }
    }

    printf("\n--- Students with Age >= 18 ---\n");
    for (int i = 0; i < n; i++)
    {
        if (s[i].age >= 18)
        {
            printf("Name: %s | Age: %d | Marks: %.2f\n", s[i].name, s[i].age, s[i].marks);
        }
    }
}

    

Comments

Popular Posts