Saturday, January 17, 2009

Structure

Structure is a bunch of variables bundled together and then is named according to the proper abstraction of the creator. Therefore the name of a structure depends on the creator. Of course the name should be meaningful. The variables may be of the different type. In another languange a structure may be called a record. In my opinion, the most important aspect of structure is for abstraction. Compiling attributes that are important for current activities, and forget about the unimportant things. For example I need to model a student, and what matters to me for deciding his final mark are : StudentId, First Name, Last Name, Assignment, MidExam, and FinalExam. In this example the weight for final mark calculation is 30% of assignment, 30% of MidExam, and 40% of FinalExam. The name of the structure is Student. See the example bellow :
#include "stdio.h"

#include "stdlib.h"

typedef struct

{

char StudentId[5];

char FirstName[20];

char LastName[20];

float Assignment;

float MidExam;

float FinalExam;

} Student;

int main(void)

{

Student os;

float final;

printf("Student Id : ");

scanf("%s", os.StudentId);

printf("First Name : ");

scanf("%s", os.FirstName);

printf("Last Name : ");

scanf("%s", os.LastName);

printf("Assignment : ");

scanf("%f", &os.Assignment);

printf("Mid Term Exam : ");

scanf("%f", &os.MidExam);

printf("Final Exam : ");

scanf("%f", &os.FinalExam);

final = 0.3*os.Assignment+ 0.3*os.MidExam+ 0.4*os.FinalExam;

printf("The Grade for : %s %s %s is %f", os.StudentId, os.FirstName, os.LastName, final);

}