Advance Use of Structures

Slides:



Advertisements
Similar presentations
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Advertisements

Programming in C Chapter 10 Structures and Unions
Sort the given string, without using string handling functions.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Advance Use of Structures CHAPTER 5. C.10 1 Using Structures with Functions » A function can return only one value back. » Some of the processes may yield.
5/3/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures Lecture
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
Passing Structure to function.  structure to function structure to function  Passing structure to function in C Passing structure to function in C 
11/5/2016CS150 Introduction to Computer Science 1 Announcements  Assignment 6 due on Wednesday, December 3, 2003  Final Exam on Tuesday, December 9,
User Defined Data Types - Structures in C CHAPTER 4.
BY ILTAF MEHDI (MCS, MCSE, CCNA)1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI (MCS, MCSE, CCNA)2 Chapter No: 04 “Loops”
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Structured Data Objects (Structs). array Recall our definition of an array: fixedcontiguousall of the same data type an array is a fixed number of contiguous.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Structs Structured Data Objects (Structs) Chapter 7.
Chapter 2 Array and String. Array Definition of Array : An array is a sequence or collection of the related data items that share a common name. Purpose.
P-1 5/18/98 CSE / ENGR 142 Programming I Arrays of Structures © 1998 UW CSE.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
Test 2 Review Outline.
Structured Programming II
Linked List :: Basic Concepts
A bit of C programming Lecture 3 Uli Raich.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
C Programming Tutorial – Part I
Programming Languages and Paradigms
User Defined Data Types - Structures in C
Quiz 11/15/16 – C functions, arrays and strings
Lecture-5 Arrays.
CSE 303 Concepts and Tools for Software Development
Programming Paradigms
Visit for more Learning Resources
Command-Line Arguments
Computer Science 210 Computer Organization
Arrays in C.
Visit for more Learning Resources
Buy book Online -
Buy book Online -
Computer Science 210 Computer Organization
FUNCTIONS WITH ARGUMENTS
Arrays, Part 1 of 2 Topics Definition of a Data Structure
S. Kiran, PGT (CS) KV, Malleswaram
Linked Lists Chapter 10.
Selection Sort Find the smallest value in the array. Put it in location zero. Find the second smallest value in the array and put it in location 1. Find.
Array of Structures A structure holds only one record But a record
Engr 0012 (04-1) LecNotes
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
Strings A collection of characters taken as a set:
FILE HANDLING IN C.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Functions with arrays.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Homework Starting K&R Chapter 5 Good tutorial on pointers
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Engineering Problem Solving with C++, Etter
Pointers Pointers are variables that contain memory addresses as their values. A variable name refers to a specific value. A pointer contains an address.
CS150 Introduction to Computer Science 1
1-6 Midterm Review.
Arrays.
Chapter 9: Pointers and String
Chapter 9: Pointers and String
The Pointers of Structures
Programming Languages and Paradigms
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Course Outcomes of Programming In C (PIC) (17212, C203):
ARRAYS ..
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Introduction to Problem Solving and Programming
Presentation transcript:

Advance Use of Structures CHAPTER 5

Using Structures with Functions A function can return only one value back. Some of the processes may yield more then one value as a result. How do we return them back from the function? You can declare a composite data type with structure, that is including the set of values of process result. So, you may return these values as a single variable from your function.

Using Structures with Functions You can pass a local variable of “Structure tag” into a function as an argument. Also, you can return a value in “structure tag” data type from a function. So the declaration (prototype) of a function can be: structure std_rec calculate_grade( structure std_rec ); And, the definition of the same function can be: structure std_rec calculate_grade( structure std_rec student ) { … } Finally we can use this function as: c213[i] = calculate_grade( c213[i] );

# include <stdio.h> # include <conio.h> struct std_rec{ char stdno[7], char name[21]; int mt, final, quiz; float grd; }; struct std_rec calc_grd( struct std_rec student) { student.grd = 0.3* student.mt +0.5* student.final + 0.2* student.quiz; return student; } void main() clrscr(); struct std_rec c213; printf("\n Student no :"); gets(c213.stdno); printf("\n Student name :"); gets(c213.stdno); printf("\n Student mt :"); scanf("%d",&c213.mt); printf("\n Student final:"); scanf("%d",&c213.final); printf("\n Student quiz :"); scanf("%d",&c213.quiz); c213 = calc_grd(c213); printf("\n Grade : %5.2f", c213.grd); getch(); } /* The end of main() */

Using Structures with Functions Example 1: (A function to read the date) struct date read _ date( struct date argdate) { printf(“\n Enter the date (dd/mm/yyyy) :”); scanf(“%d/%d/%d”, &argdate.day, &argdate.month, &argdate.year); return argdate; } Example 2:(A function to read the inform. of a student) int read_student(void) { struct student_rec temp; printf(“\n Enter the student no:”); gets(temp.stdno); printf(“\n Enter the name :”); gets(temp.name); printf(“\n Enter the Midterm :”); scanf(“%d”,&temp.mt); printf(“\n Enter the Final :”); scanf(“%d”,&temp.final); printf(“\n Enter the Quiz :”); scanf(“%d”,&temp.quiz); temp.grd = 0.3 * temp.mt + 0.5 * temp.final + 0.2 * temp.quiz; return temp;

Using Structures with Functions An array of structure can be an argument of a function as a simple array: void class_list( struct student_rec [ ], int); // Prototype of the function void class_list( struct student_rec temp[ ], int size) // Definition of the function { int cnt; printf(“\n The Class List \n”); printf(“\n Std-no Name Mt Fin Qui Grd”); printf(“\n ******************************************”); for (cnt = 0; cnt< size; cnt++) printf(“ %7s %21s %3d %3d %3d %5.2f”, temp.stdno, temp.name, temp.mt, temp.final, temp.quiz, temp.grd); }

Using Structures with Functions An array of structure also can be returned from a function as a simple array: struct student_rec read_students( void); // Prototype of the function struct student_rec read_students( void) // Definition of the function { int cnt; struct student_rec temp[35]; for (cnt = 0; cnt< 35; cnt++) { clrscr(); printf(“\n Student %d”, cnt+1); printf(“\n Enter the student no:”); gets(temp[cnt].stdno); printf(“\n Enter the name :”); gets(temp[cnt].name); printf(“\n Enter the Midterm :”); scanf(“%d”,&temp[cnt].mt); printf(“\n Enter the Final :”); scanf(“%d”,&temp[cnt].final); printf(“\n Enter the Quiz :”); scanf(“%d”,&temp[cnt].quiz); temp[cnt].grd = 0.3 * temp[cnt].mt + 0.5 * temp[cnt].final + 0.2 * temp[cnt].quiz; } return temp; // The first element address of the array is returning back

Sorting an Array of Structure Question: Write the required functions to sort the array of students with respect to their grades. (from biggest to smallest) struct student_rec { char stdno[7]; char name[21]; int mt, final, quiz; float avg; } c213[35]; // c213 is an array of structure student_rec with 35 elements

int findmax(void) { float max = -1.0; int cnt, pos; for (cnt=0; cnt<35; cnt++) if (c213[cnt].grd > max) max = c213[cnt].grd; pos = cnt; } return pos; void sort_grd(void) struct student_ rec temp[35]; int cnt, pos; pos = findmax(); temp[cnt]= c213[pos]; c213[pos].grd = -1000.0; // Blockade the position with a very small num. c213[cnt]= temp[cnt]; // Rewrite the sorted elements into c213

Sorting an Array of Structure Question: Write the required functions to sort the array of students with respect to their names. In order to sort an array of strings, first you have to have the following functions: String Compare (strcmp), that is comparing two strings and returning a result value as : 0 : Two strings are same 1 : The first string is bigger (or coming after in an alphabetic order) -1 : The second string is bigger String Copy (strcpy), copy a string from an array to another.

int strcomp( char str1[], char str2[]) { int cnt=0, big=0; for(;;) { if ( ((*(str1+cnt))!='\0') && ((*(str2+cnt))!='\0') && (cnt< 21)) { if ((*(str1+cnt)) > (*(str2+cnt))) big = 1; break; } if ((*(str1+cnt)) < (*(str2+cnt))) big = 2; break; cnt ++; else break; // a “\0” is found. } // To evaluate two strings like ‘cem’ and ‘cemal’ if ((big == 0) && (*(str1+cnt)!= '\0')) big = 1; if ((big == 0) && (*(str2+cnt)!= '\0')) big = 2; return big;

We will write those functions: min_name sortname void strcpy( char str1[], char str2[]) { int cnt=0; while (*(str1+cnt)!='\0') { *(str2+cnt) = *(str1+cnt); cnt++; } *(str2+cnt)='\0'; Now, we can start to write the program that is asked to sort the array of students on their name field. We will write those functions: min_name sortname

int min_name(void) { int cnt, pos; char tstr[21]=“zzzzzzzzzzzzzzzzzzzz”; for (cnt=0; cnt<35; cnt++) { if (strcmp(c213[cnt].name, tstr)= = -1) // is it smallerthen tstr ? strcpy(c213[cnt].name, tstr); pos=cnt; } return pos; void sortname(void) struct student_rec temp; int cnt, pos; char dummy[21] = “zzzzzzzzzzzzzzzzzzzz”; pos = min_name(); temp[cnt] = c213[pos]; strcpy(c213[pos].name, dummy); c213[cnt] = temp[cnt] ;

Searching an Array of Structure Question: Write a functions to search a student record within an array of structures. The student number (string) has to be given as an argument to the function and it will return either : –1 : If student is not found n : the offset of the array element (if the student is found).

Searching An Array of Structure int find_name(char target[21]) { int cnt, pos= -1; for (cnt=0; cnt<35; cnt++) { if (strcmp(c213[cnt].stdno, target)==0) // are they equal ? pos=cnt; // Get the position of the found student break; // Stop the search (break the for loop) } return pos; // Return the position of the student

Files with Array of Structures The content of an array is kept in RAM (Primary Memory). What you write in an arrays is not durable. The content of an array is lost, when the program is stopped. You have to save the content of the array into a file which uses the SECONDARY STORAGE. On the next run, the content of the file can be re-load into the array to be processed.

Files with Array of Structures Question : Write a function to save the records of students from the array c213 to the file “C213.TXT”. void std_save(void) { int cnt; FILE *fp; fp = fopen(“C213.TXT”,”w”); for (cnt=0; cnt<35; cnt++) { fprintf(fp,“%s\n”,c213[cnt].stdno); fprintf(fp,“%s\n”,c213[cnt].name); fprintf(fp,“%d\n”,c213[cnt].mt); fprintf(fp,“%d\n”,c213[cnt].final); fprintf(fp,“%d\n”,c213[cnt].quiz); fprintf(fp,“%f”,c213[cnt].grd); } fclose(fp);

Files with Array of Structures Question : Write a function to read the content of the file “C213.TXT” into the array of structure c213. void std_restore(void) { int cnt; FILE *fp; fp = fopen(“C213.TXT”,”r”); for (cnt=0; cnt<35; cnt++) { fgets(c213[cnt].stdno , 7, fp); fgets(c213[cnt].name , 21, fp); fscanf(fp, “%d”&,c213[cnt].mt); fscanf(fp, “%d”&,c213[cnt].final); fscanf(fp, “%d”&,c213[cnt].quiz); fscanf(fp, “%f”&,c213[cnt].grd); } fclose(fp);