360 likes | 476 Views
Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lectures 16, 17 Structure and Union, Miscellaneous topics Thursday 8 July 2010. Two-week ISTE workshop on Effective teaching/learning of computer programming. Overview.
E N D
Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lectures 16, 17 Structure and Union, Miscellaneous topics Thursday 8 July 2010 Two-week ISTE workshop onEffective teaching/learning of computer programming
Overview • Struct data type in C • Notion of an abstract data type • More examples of Struct variables/arrays • Another sample problem • Unions • Miscellaneous topics • Answers to queries • Announcements • Interaction
Structures in C • A struct definition DOES NOT define any variable nor any storage is allocated • Rather, it defines a new ‘type’ which can then be used, just as we use all native types in C • To appreciate this, let us revisit some well known terms • What does the word ‘float’ convey to us? • This word conveys the way a structure of four bytes will look like, and the kind of value that can be stored in a location declared to be of type float
What does word ‘float’ mean … Any variable of this type will have to be allocated 4 bytes of memory The internal representation will have mantissa and exponent I will have to do arithmetic operations on values of such variables float
Declaration of variables of type float • When we declare variables as follows: float x, y = 23.14; • It is at that time the locations for each of these two variable are actually allocated
Declaration … Any variable of this type will have to be allocated 4 bytes of memory The internal representation will have mantissa and exponent I will have to do arithmetic operations on values of such variables ? ? x float .2314E .2314E2 y float x, y=23.14
Struct definition • In exactly an analogous manner, when we say stuct newtype{ int a; float y; char ch; }; • This means that a ‘new’ type is being defined • This type has three members, one int type, second float type, and third char type • If variables are declared to be of this newtype, allocation will have to be made for each of the three components, a total of 17 (4 + 4 + 1) bytes
What does words ‘struct newtype’ mean? Any variable of this type will have to be allocated 17 bytes of memory There will be 3 components, each of the indicated standard type I will have to do appropriate operations on each of these components Struct newtype { … }
Declaration of variable of type ‘struct newtype’ stuct newtype{ int a; float y; char ch; } struct newtype var;
Declaration … Any variable of this type will have to be allocated 17 bytes of memory There will be 3 components, each of the indicated standard type I will have to do appropriate operations on each of these components ? var.a struct newtype { … } ? var.y ? Struct newtype var; ? var.ch
Assignment operations …. var.a = 58; var.y = 23.14; var.ch = ‘W’;
Declaration … Any variable of this type will have to be allocated 17 bytes of memory There will be 3 components, each of the indicated standard type I will have to do appropriate operations on each of these components 58 var.a struct newtype { … } ? .2314E2 var.y var.a = 58; var.y = 23.14; var.ch = ‘W’; W var.ch
Structure definition of studentinfotype #include<stdio.h> int main(){ struct studentinfotype { char name[31]; char roll[9]; int hostel; float marks[5]; char grade[3]; }; struct studentinfotype s, slist[1000]; struct studentinfotype *p;
Operations on members of structure variables s.name[0] = 'N'; s.hostel = 12; p = &s; printf (" hostel number is %d\n", p->hostel); printf("Size of s is: %d\n",(sizeof(s))); printf("Size of marks i%d\n",(sizeof(s.marks))); printf("Size of grade is: %d\n",(sizeof(s.grade))); printf("Size of p is: %d\n",(sizeof(p))); return 0; }
Structure and structure pointers • While referring to any member of a structure s, we use ‘dot’ (‘.’) s.member • While referring to that member using a structure pointer, we use a hyphen followed by greater than sign (‘->’) p -> member
Student database problem revisited • Some students have registered for an elective subject. We are given following data for registered students, entered into a text file “BatchInputFile.txt”, containing name, roll number, and hostel for each student 6 Milind 10105003 1 Sohoni 10000000 3 Ranjit 11010101 4 Ashank 10101010 3 Ashita 11111111 11 Vinita 22222222 10
Student data ... • The teacher will be conducting 5 different types of evaluations. Based on the marks, a letter grade such as “AA”, AB” “BB” etc, will be awarded to each student • Teacher wants to create a file in which to store relevant data for students such as roll number, name, hostel, marks in each of the 5 evaluations, and the final grade awarded • Initially, the marks and grade information will not be available (does not exist)
Student data ... • Teacher wishes to get a set of program which will do the following: • A database file is created which can hold all the relevant information. • At the beginning of the semester, records for students are created with information available at that time • Subsequently , whenever a test is conducted for a student, teacher should be able to update the record for that student by inserting the evaluated marks for that test
Student data … • The program is required to be able to directly read the data for a student and update that record. • It is pointed out that a direct access to a record is possible only if the position of that record relative to the beginning of the file is known. If a roll number is supplied, the program will not know where that student’s record is stored • Teacher agrees to allocate an artificial serial number to each student, using which his or her record should be fetched from the database file
Student data ... • We decide to write two programs • The first program will create the database file and will also store the available information for each registered student in that file • A second program will update a record of given student (who will be identified by a unique serial number) • Since sensitive data values like marks and grades are involved, programs will provide output for verification at each stage. So we will write a function to read and print data of any student
Program for initial database creation /* Program to create a file holding data for students */ #include <stdio.h> struct studentinfo { char name[31]; char roll[9]; int hostel; float marks[5]; char grade[3]; };
Program ... /* Function to print information about a sdudent given his/her serial number, and the structure variable holding the corresponding data */ void printstudent(struct studentinfo s, int sno) { int i; printf("%d ", sno); printf("%s %s %d ", s.name, s.roll, s.hostel); for (i=0; i<5; i++){ printf("%f ", s.marks[i]); } printf("%s\n", s.grade); //printf("%c%c\n", s.grade[0], s.grade[1]); }
Program ... int main() { struct studentinfo s; struct studentinfo studentlist[100]; long int DBfilepos; char option; char *n; char *r; int i,j,N; int RecSize; char filename[]="BatchInputFile.txt"; char dbfile[]="StudentDB.bin"; RecSize = sizeof(s); FILE *fp=fopen(filename,"rs");
Program … fscanf(fp, "%d",&N); printf("Data of %d students in this batch file\n",N); if (fp != NULL ){ for (i=0;i<N;i=i+1) { fscanf(fp,"%s %s %d",(char *)s.name,(char *)s.roll, &s.hostel); for (j=0; j<5; j++) s.marks[j]=0; s.grade[0]='*'; s.grade[1]='*'; s.grade[2]='\0'; printstudent(s, i); studentlist[i] = s; } fclose ( fp ); }
Program ... else perror ( filename ); printf("data has been read from batch file\n"); printf("An output Binary Database file will be created \n\n"); printf("Size of each record is: %d\n",RecSize); //----------Create DB file ----------- FILE *db = fopen(dbfile,"wb"); for (i=0; i<N; i++){ s = studentlist[i]; fwrite(&s,sizeof(struct studentinfo),1,db); // fwrite(&s,RecSize,1,db); } }
Program … What is missing ? • We have forgotten to close the files • All open files are automatically closed upon normal termination • We had a variable declared called ‘option’ which is not used anywhere in the program
Database update program #include <stdio.h> struct studentinfo ---- //print a student record void printstudent(struct studentinfo s, int sno) { int i; ----
Update program ... int main() { struct studentinfo s; long int DBfilepos; int i, sno, RecSize, testno; float testmarks; char dbfile[]="StudentDB.bin"; RecSize = sizeof(s); printf("Give key value for student: \n"); scanf("%d",&sno); printf("Give testno and testmarks to be updated\n"); scanf("%d %f",&testno,&testmarks);
Update Program … FILE *fp=fopen(dbfile,"rb+"); //read student's record DBfilepos = sizeof(struct studentinfo)*sno; fseek(fp, DBfilepos ,SEEK_SET); fread(&s,sizeof(struct studentinfo),1,fp); printstudent(s, sno); //change test marks s.marks[testno-1]=testmarks; fseek(fp,DBfilepos,SEEK_SET); fwrite(&s,sizeof(struct studentinfo),1,fp);
Update program ... //confirm changes in the file fseek(fp, DBfilepos ,SEEK_SET); fread(&s,sizeof(struct studentinfo),1,fp); printstudent(s,sno); fclose(fp); printf("\nFile StudentDB.Bin updated\n"); fp=fopen(dbfile,"r"); //read all the records for (i=0;i<6; i++) { fread(&s, sizeof(struct studentinfo),1,fp); printstudent(s,i); } fclose(fp); }
Union • Union is a special structure which permits the programmer to keep different types of data values in the same location, (obviously at different times). • This essentially means that your program is able to re-interpret the contents of same set of memory locations, depending upon what is the ‘context’ (what is currently stored there • Union and structs are NOT comparable at all, particularly, there is no sense in comparing how much memory each occupies
Union example • Suppose we wish to prepare a text data file containing the names and details of our remote centres, and for each centre, the names and details of the participants • We may have our data ‘records’ such as: 1 Ahmedabad 30 2 174 Anita 2 392 Chirag 2 ... (such 30 records) 1 Amravati 32 • 831 Abhijit 2 217 Amol ... (such 32 records)
Possible use of union Here we have two types of records whose structures are struct centrerec{ char rectype; // value ‘1’ char cname[40]; int cnumparticipants; } struct participantrec{ char rectype; //value ‘2’ int serialno; char pname[40]; }
Quiz Q. While teaching basic I-O to first year students, my preferred approach will be: • To use scanf and printf, but to use only simple formats. • To use simplified functions through # defines as was shown in some of the workshop examples. • To use CIN and COUT in the initial lectures. • Explain the complete scanf, printf functionality and use these from the beginning.