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.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Numerical Recipes The Art of Scientific Computing (with some applications in computational physics)
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Programming in C Chapter 10 Structures and Unions
Lectures 10 & 11.
The University of Adelaide, School of Computer Science
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Programming Languages and Paradigms The C Programming Language.
Structures Spring 2013Programming and Data Structure1.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
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.
1 Review of Chapter 10: String and Pointers. 2 Outline  String:  Representation of a string: \0  Using scanf to read in string  Initilization of strings.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Chapter 9: Arrays and Strings
Computer Science 210 Computer Organization Strings in C.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
'C' Programming With Structure Records Purpose of structures Coding a structure template Defining a new data type Functions which communicate using structures.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
CECS 121 EXAM 2.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data type.
Review C Language Features –control flow –C operators –program structure –data types –I/O and files Problem Solving Abilities.
Topics to be covered  Introduction to array Introduction to array  Types of array Types of array  One dimensional array One dimensional array  Declaration.
Computer Science 210 Computer Organization Arrays.
5/3/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures Lecture
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
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 
EXERCISE Arrays, structs and file processing. Question You own a pet store. You want to keep an inventory of all the pets that you have. Pets available.
1 Homework HW4 due today HW5 is on-line Starting K&R Chapter 5 –Skipping sections for now –Not covering section 5.12.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
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.
Strings program. C Program to Check if a given String is Palindrome #include void main() { char string[25], reverse_string[25] = {'\0'}; int i, length.
1 Object-Oriented Programming Using C++ A tutorial for pointers.
Chapter 1 Basic C Programming
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.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
CS 1430: Programming in C++ 1. Test 2 Friday Functions Arrays For Loops Understand Concepts and Rules Memorize Concepts and Rules Apply Concepts and Rules.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Scis.regis.edu ● CS-362: Data Structures Week 4 Dr. Jesús Borrego Lead Faculty, COS Regis University 1.
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.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
P-1 5/18/98 CSE / ENGR 142 Programming I Arrays of Structures © 1998 UW CSE.
Advance Use of Structures
User Defined Data Types - Structures in C
CSE 303 Concepts and Tools for Software Development
Arrays in C.
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.
Engr 0012 (04-1) LecNotes
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
FILE HANDLING IN C.
CS150 Introduction to Computer Science 1
Arrays.
Chapter 9: Pointers and String
Chapter 9: Pointers and String
The Pointers of Structures
Presentation transcript:

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 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.

C.10 2 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] );

C.10 3 # include 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() */

C.10 4 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 * temp.final * temp.quiz; return temp; }

C.10 5 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); printf(“\n ******************************************”); }

C.10 6 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 * temp[cnt].final * temp[cnt].quiz; } return temp; // The first element address of the array is returning back }

C.10 7 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

C.10 8 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; for (cnt=0; cnt<35; cnt++) { pos = findmax(); temp[cnt]= c213[pos]; c213[pos].grd = ; // Blockade the position with a very small num. } for (cnt=0; cnt<35; cnt++) c213[cnt]= temp[cnt]; // Rewrite the sorted elements into c213 }

C.10 9 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 (or coming after in an alphabetic order) » String Copy (strcpy), copy a string from an array to another.

C 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; }

C 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

C 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”; for (cnt=0; cnt<35; cnt++) { pos = min_name(); temp[cnt] = c213[pos]; strcpy(c213[pos].name, dummy); } for (cnt=0; cnt<35; cnt++) c213[cnt] = temp[cnt] ; }

C 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).

C 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 } Searching An Array of Structure

C » 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

C » 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

C » 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); } Files with Array of Structures