பாடம் 4 / 6 · Strings, Structs, Files · படிக்க 3 min · புதுப்பிக்கப்பட்டது

Structures-ஓட array

ஒரு முழு class-ஓட student records ஒரே array-ல: சேமிக்கிறது, print பண்றது, சராசரி, topper-ஐ கண்டுபிடிக்கிறது, sort பண்றது.

ஒரு struct Student ஒரு மாணவரை வெச்சிருக்கும். Structures-ஓட array ஒரு முழு class-ஐ வெச்சிருக்கும்: cls[i] i-வது மாணவர், cls[i].marks அந்த மாணவரோட marks. நிஜ programs records-ஓட lists-ஐ இப்படித்தான் வெச்சிருக்கும்.

c
#include <stdio.h>

struct Student {
    char name[20];
    int roll;
    float marks;
};

int main(void)
{
    struct Student cls[3] = {
        {"Priya", 101, 87.5f},
        {"Arun", 102, 73.0f},
        {"Meena", 103, 94.5f},
    };

    int top = 0;
    float total = 0;

    for (int i = 0; i < 3; i++) {
        printf("%-6s %d  %.1f\n", cls[i].name, cls[i].roll, cls[i].marks);
        total += cls[i].marks;
        if (cls[i].marks > cls[top].marks) {
            top = i;
        }
    }
    printf("Average: %.2f\n", total / 3);
    printf("Topper: %s\n", cls[top].name);
    return 0;
}
Output
Priya  101  87.5
Arun   102  73.0
Meena  103  94.5
Average: 85.00
Topper: Meena

Records-ஐ marks வெச்சு sort பண்றது

c
#include <stdio.h>

struct Student {
    char name[20];
    float marks;
};

int main(void)
{
    struct Student cls[4] = {
        {"Priya", 87.5f}, {"Arun", 73.0f}, {"Meena", 94.5f}, {"Ravi", 66.0f},
    };
    int n = 4;

    /* Bubble sort, highest marks first. The whole struct is swapped. */
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (cls[j].marks < cls[j + 1].marks) {
                struct Student t = cls[j];
                cls[j] = cls[j + 1];
                cls[j + 1] = t;
            }
        }
    }

    for (int i = 0; i < n; i++) {
        printf("%d. %-6s %.1f\n", i + 1, cls[i].name, cls[i].marks);
    }
    return 0;
}
Output
1. Meena  94.5
2. Priya  87.5
3. Arun   73.0
4. Ravi   66.0

Structs-ஐ ஒரே தடவையில assign பண்ணலாம் — struct Student t = cls[j]; பேர் உட்பட எல்லா fields-ஐயும் copy பண்ணும். அதனால records-ஐ sort பண்றதும் numbers-க்கான அதே bubble sort தான்; compare மட்டும் struct-க்குள்ள பார்க்கும்.

Note

%-6s பேரை 6 இடத்துல இடது பக்கம் சீரா print பண்ணும், columns ஒழுங்கா இருக்கும். ஒரு struct-க்குள்ளயே array இருக்கலாம் — அஞ்சு subjects-க்கு float marks[5]; — அப்போ cls[i].marks[j] கிடைக்கும்.

struct Student cls[10]-ல மூணாவது மாணவரோட roll number-ஐ எப்படி படிக்கணும்?

இப்போ இதை செஞ்சு பாருங்க

  1. scanf வெச்சு 5 மாணவர்களோட பேர், marks-ஐ படிச்சு, class சராசரியை விட அதிகம் எடுத்த எல்லாரையும் print பண்ணுங்க.
  2. Struct-ல மூணு subjects-க்கு float marks[3] சேர்த்து, ஒவ்வொரு மாணவரோட total, grade-ஐ print பண்ணுங்க.
  3. User type பண்ற roll number-ஐ array-ல தேடி, அந்த மாணவரை print பண்ணுங்க, இல்லன்னா "Not found".

Create a free account to save your progress, or sign in.