850 likes | 1.01k Vues
CSC 211 Data Structures Lecture 4. Dr. Iftikhar Azim Niaz ianiaz@comsats.edu.pk. 1. Last Lecture Summary I. Generation of Programming Languages Machine Language Assembly Language High Level Languages Processing a Computer Program Stages of compilation, Interpreter
E N D
CSC 211Data StructuresLecture 4 Dr. Iftikhar Azim Niaz ianiaz@comsats.edu.pk 1
Last Lecture Summary I • Generation of Programming Languages • Machine Language • Assembly Language • High Level Languages • Processing a Computer Program • Stages of compilation, Interpreter • Procedural and modular programming • Structure of a C Program • Data and Data structure • Abstract Data Type (ADT) 2
Basic Terms • Data • means a value or set of values • 34, 10/01/1965, Pascal, (21,25,28,30,35,37,38) • Entity • Is one that has certain attributes and which may be assigned values. • Entity Employee • Attribute Name DOB Sex Designation • Value Ahmed 31/12/99 M Director • Domain • Set of all possible values that could be assigned to a particular attribute • Information is processed data or meaningful data
Data Type and Data Structure • Data Type • defines the specification of a set of data and the characteristics for that data. • is derived from the basic nature of data that are stored for processing rather from their implementation. • Data Structure • refers to the actual implementation of the data type and offers a way of storing data in an efficient manner. • Any data structure is designed to organize data to suit a specific purpose so that it can be accessed and worked in appropriate ways both effectively and efficiently • Are implemented using the data types, references and operations on them that are provided by a programming language. 4
Data Structure • Is a particular way of storing and organizing data in a computer so that it can be used efficiently • Different kinds of data structures are suited to different kinds of applications and some are highly specialized to specific tasks • e.g. B-trees are particularly well-suited for implementation of databases, while compiler implementations usually use hash tables to look up identifiers • provide a means to manage huge amounts of data efficiently, such as large databases and internet indexing services • Usually, efficient data structures are a key to designing efficient algorithms.
Everything is Just a Bunch of Bits • Bits can represent many different things • Depends on interpretation • You and your program must keep track of what kind of data is at each location in the computer’s memory • E.g., program data types
Big Picture • Processor works with finite-sized data • All data implemented as a sequence of bits • Bit = 0 or 1 • Represents the level of an electrical charge • Byte = 8 bits • Word = largest data size handled by processor • 32 bits on most older computers • 64 bits on most new computers
Data types in C • Only really four basic types: • char • int (short, long, long long, unsigned) • float • double • Size of these types • Sizes of these types vary from one machine to another!
Characters (char) • Roman alphabet, punctuation, digits, and other symbols: • Can encode within one byte (256 symbols) • ASCII encoding (man ascii for details) • In C: char a_char = ’a’; char newline_char = ’\n’; char tab_char = ’\t’; char backslash_char = ’\\’;
Characters are just numbers • What does this function do? argument type and name return type char fun(char c) { char new_c; if ((c >= ’A’) && (c <= ’Z’)) new_c = c - ’A’ + ’a’; else new_c = c; return (new_c); } procedure name local variable type and name comparisons with characters! Math on characters!
Arrays Array: a set of pairs (index and value) data structure For each index, there is a value associated with that index. representation (possible) implemented by using consecutive memory.
Arrays • An array is a group of related data items that all have the same nameand the same data type. • Arrays can be of any data type we choose. • Arrays are static in that they remain the samesizethroughout program execution. • An array’s data items are stored contiguously in memory. • Each of the data items is known as an element of the array. Each element can be accessed individually.
Arrays scalar: capable of holding a single data item aggregate variables: capable of holding a collections of values. Two kinds of aggregates in C: Arrays Structures An array is a data structure containing a number of data values, all of which have the same type Static entity same size throughout program.
Arrays One-Dimensional Arrays The simplest kind of arrays The elements, the values of the items, of a one-dimensional array are conceptually arranged one after another in a single row. int a[8]; a #define N 10 …… int a[N];
Arrays Subscripting Array elements are always numbered starting from 0, so the elements of an array of length n are indexed from 0 to n-1 a[8-1] a[0] a[1] a[1] = 9; printf(“%d\n”, a[5]); ++a[i];
Name of array (Note that all elements of this array have the same name, c) c[0] -45 c[1] 6 c[2] 0 c[3] 72 c[4] 1543 c[5] -89 c[6] 0 c[7] 62 c[8] -3 c[9] 1 c[10] 6453 c[11] 78 Position number of the element within array c Arrays • Array • Group of consecutive memory locations • Same name and type • To refer to an element, specify • Array name • Position number • Format: arrayname[position number] • First element at position 0 • n element array named c: • c[ 0 ], c[ 1 ]...c[ n – 1 ]
Declaring Arrays • When declaring arrays, specify • Name • Type of array • Number of elements arrayType arrayName[ numberOfElements ]; • Examples: int c[ 10 ]; float myArray[ 3284 ]; • Declaring multiple arrays of same type • Format similar to regular variables • Example: int b[ 100 ], x[ 27 ];
Array Declaration and Initialization int numbers[ 5 ] ; • The name of this array is “numbers”. • This declaration sets aside a chunk of memory that is big enough to hold 5 integers. • It does notinitialize those memory locations to 0 or any other value. They contain garbage. • Initializing an array may be done with an array initialization, as in : • int numbers[ 5 ] = { 5, 2, 6, 9, 3 } ; numbers 5 2 6 9 3
Compare: C:int array[10]; Java:int[] array = new int[10]; Arrays in C All elements of same type – homogenous Unlike Java, array size in declaration int array[10]; int b; array[0] = 3; array[9] = 4; array[10] = 5; array[-1] = 6; First element (index 0) Last element (index size - 1) No bounds checking! Allowed – usually causes no error array[10] may overwrite b
a[2] 0x1008 a[1] 0x1004 a[0] 0x1000 Array Representation • Homogeneous Each element same size – s bytes • An array of m data values is a sequence of ms bytes • Indexing: 0th value at byte s0, 1st value at byte s1, … • m and s are not part of representation • Unlike in some other languages • s known by compiler – usually irrelevant to programmer • m often known by compiler – if not, must be saved by programmer inta[3];
Accessing Array Elements • Each element in an array has a subscript (index) associated with it. • Subscripts are integers and always begin at zero. • Values of individual elements can be accessed by indexing into the array. For example, printf(“The third element = %d.\n”, numbers[ 2 ] ) ; would give the output The third element = 6. numbers 5 2 6 9 3 0 1 2 3 4
Accessing Array Elements (con’t) • A subscript can also be an expression that evaluates to an integer. numbers[ (a + b) * 2 ] ; • Caution! It is a logical error when a subscript evaluates to a value that is out of range for the particular array. Some systems will handle an out-of-range error gracefully and some will not (including ours). Normally, when you see a file named core (or core*) it means you exceeded the end of an array!
Modifying Elements • Individual elements of an array can also be modified using subscripts. • numbers[ 4 ] = 20 ; /*changes the value of the element found at subscript 4 to 20 */ • Initial values may be stored in an array using indexing, rather than using an array initialization. numbers[ 0 ] = 5 ; numbers[ 1 ] = 2 ; numbers[ 2 ] = 6 ; numbers[ 3 ] = 9 ; numbers[ 4 ] = 3 ;
Arrays • Array elements are like normal variables c[ 0 ] = 3; printf( "%d", c[ 0 ] ); • Perform operations in subscript. If x equals 3 c[ 5 - 2 ] == c[ 3 ] == c[ x ]
Arrays and For Loop Arrays and for loops go hand-in-hand Idioms: for(i = 0; i < N; i++) a[i] = 0; for(i = 0; i < N; i++) scanf(“%d”, &a[i]); for(i = 0; i < N; i++) sum += a[i];
Array and its Indexing • C doesn’t require that subscript bounds be checked. • If a subscript goes out of range, the program’s behavior is undefined. int a[10], i; for(i = 1; i <= 10; i++) a[i] = 0;
Filling Large Arrays • Since many arrays are quite large, using an array initialization can be impractical. • Large arrays are often filled using a for loop. • for ( i = 0; i < 100; i++ ) • { • values [ i ] = 0 ; • } • would set every element of the 100 element array “values” to 0.
More Declarations • int score [ 39 ] , gradeCount [ 5 ]; • Declares two arrays of type int. • Neither array has been initialized. • “score” contains 39 elements (one for each student in a class). • “gradeCount” contains 5 elements (one for each possible grade, A - F).
#define SIZE 39 #define GRADES 5 int main ( void ) { int score [ SIZE ] ; int gradeCount [ GRADES ] ; } Using #define for Array Sizes
Array subscript may be any integer expression a[i+j*10] i = 0; while(i < N) a[i++] = 0; i = 0; while(i < N) a[i] = b[i++];
Array Initialization Always initialize array when you declare it int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int a[10] = {1 , 2, 3, 4, 5, 6}; /* {1, 2, 3, 4, 5, 0, 0, 0, 0, 0} */ int a[10] = {0}; /* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */ int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */
Examples Using Arrays • Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 }; • If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 } • All elements 0 • If too many a syntax error is produced syntax error • C arrays have no bounds checking • If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; • 5 initializers, therefore 5 element array
Example Using Arrays Problem: Find the average test score and the number of A’s, B’s, C’s, D’s, and F’s for a particular class. Design: Main Print User Instructions Calculate Average Score
#include <stdio.h> #define SIZE 39 /* number of tests */ #define GRADES 5 /* number of different grades: A, B, C, D, F */ void printInstructions ( void ) ; double findAverage ( double sum, int quantity ) ; int main ( void ) { inti ; /* loop counter */ int total ; /* total of all scores */ int score [ SIZE ] ; /* student scores */ intgradeCount [ GRADES ] ; /* count of A’s, B’s, C’s, D’s, F’s */ double average ; /* average score */ /* Print the instructions for the user */ printInstructions ( ) ; Example Using Arrays (con’t)
Example Using Arrays (con’t) /* Initialize grade counts to zero */ for ( i = 0; i < GRADES; i++ ) { gradeCount [ i ] = 0 ; } /* Fill score array with scores */ for ( i = 0; i < SIZE; i++ ) { printf (“Enter next score: ”) ; scanf (“%d “, &score [ i ] ) ; }
Example Using Arrays (con’t) /* Calculate score total and count number of each grade */ for ( i = 0; i < SIZE; i++ ) { total += score [ i ] ; switch ( score [ i ] / 10 ) { case 10 : case 9 : gradeCount [ 4 ]++ ; break ; case 8 : gradeCount [ 3 ]++ ; break ; case 7 : gradeCount [ 2 ]++ ; break ; case 6 : gradeCount [ 1 ]++ ; break ; default : gradeCount [ 0 ]++ ; } }
/* Calculate the average score */ average = findAverage ( total, SIZE ) ; /* Print the results */ printf (“The class average is %.2f\n”, average ) ; printf (“There were %2d As\n”, gradeCount [ 4 ] ) ; printf (“ %2d Bs\n”, gradeCount [ 3 ] ) ; printf (“ %2d Cs\n”, gradeCount [ 2 ] ) ; printf (“ %2d Ds\n”, gradeCount [ 1 ] ) ; printf (“ %2d Fs\n”, gradeCount [ 0 ] ) ; return 0 ; } /* end main */ Example Using Arrays (con’t)
Example Using Arrays (con’t) /***************************************************************** ** printInstructions - prints the user instructions ** Inputs: None ** Outputs: None /***************************************************************** void printInstructions ( void ) { printf (“This program calculates the average score\n”) ; printf (“for a class of 39 students. It also reports the\n”) ; printf (“number of A’s, B’s, C’s, D’s, and F’s. You will\n”) ; printf (“be asked to enter the individual scores.\n”) ; }
/***************************************************************/*************************************************************** ** findAverage - calculates an average ** Inputs: sum - the sum of all values ** num - the number of values ** Outputs: the computed average ****************************************************************/ double findAverage ( double sum, int num ) { double average ; /* computed average */ if ( num != 0 ) { average = sum / num ; } else { average = 0 ; } return average ; } Example Using Arrays (con’t)
Indexing Arrays • As long as we know • the beginning location of an array, • the data type being held in the array, and • the size of the array (so that we don’t go out of range), • then we can access or modify any of its elements using indexing. • The array name alone (without [ ] ) is just a variable that contains the starting address of the block of memory where the array is held.
Call (Pass) by Value • So far, we have passed only values to functions. • The function has a local variable (a formal parameter) to hold its own copy of the value passed in. • When we make changes to this copy, the original (the corresponding actual parameter) remains unchanged. • This is known as calling (passing) by value.
Passing Arrays to Functions • The function prototype: • void fillArray ( int ages[ ], int numElements ); • The function definition header: • void fillArray ( int ages[ ], int numElements ) • The function call: • fillArray ( ages, SIZE ); • Notice that we are passing only the name of the array (the address) and that we aren’t returning anything (the function is void) because we will be modifying the original array from within the function.
Call (Pass) by Reference • As demonstrated with arrays, we can pass addresses to functions. This is known as calling (passing) by reference. • When the function is passed an address, it can make changes to the original (the corresponding actual parameter). There is no copy made. • This is great for arrays, because arrays are usually very large. We really don’t want to make a copy of an array. It would use too much memory.
#include <stdio.h> #define SIZE 4 void fillArray ( int intArray[ ], int size ) ; int main ( void ) { int someArray [ SIZE ] ; fillArray ( someArray, SIZE ) ; /* Print the elements of the array */ for ( i = 0; i < SIZE; i++ ) { printf (someArray[ %d ] = %d\n”, i, someArray[ i ] ) ; } return 0 ; } /******************************************* fillArray is a function that will fill each element of any integer array passed to it with a value that is the same as that element’s subscript. *******************************************/ void fillArray ( int anArray[ ], int numElements ) { int i ; for ( i = 0; i < numElements; i++ ) { anArray [ i ] = i ; } } Passing an Array to a Function someArray[ 0 ] = 0 someArray[ 1 ] = 1 someArray[ 2 ] = 2 someArray[ 3 ] = 3 output
Grades Program Using Pass by Reference • Problem: Find the average test score and the number of A’s, B’s, C’s, D’s, and F’s for a particular class. • New Design: Main Print User Instructions Initialize Grade Counts To Zero Read Grades Process the Grades Print the Results Calculate Average Score
#include <stdio.h> #define SIZE 39 #define GRADES 5 #define A 4 #define B 3 #define C 2 #define D 1 #define F 0 #define MAX 100 #define MIN 0 void printInstructions ( ) ; void initArray ( int anArray[ ], int size ) ; void fillArray ( int anArray[ ], int size ) ; double processGrades (int score[ ], int size, int gradeCount[ ] ) ; double findAverage ( double sum, int num ) ; void printResults ( double average, int gradeCount[ ] ) ; Grades Program (con’t)
int main ( void ) { int score [ SIZE ]; /* student scores */ intgradeCount [ GRADES ] ; /* count of A’s, B’s, C’s, D’s, F’s */ double average; /* average score */ printInstructions ( ) ; initArray ( gradeCount, GRADES ) ; fillArray (score, SIZE ) ; average = processGrades (score, SIZE, gradeCount ) ; printResults (average, gradeCount) ; return 0 ; } Grades Program (con’t)
Grades Program (con’t) /***************************************************************** ** printInstructions - prints the user instructions ** Inputs: None ** Outputs: None /***************************************************************** void printInstructions ( ) { printf (“This program calculates the average score\n”) ; printf (“for a class of 39 students. It also reports the\n”) ; printf (“number of A’s, B’s, C’s, D’s, and F’s. You will\n”) ; printf (“be asked to enter the individual scores.\n”) ; }
Grades Program (con’t) /******************************************************************* /* initArray - initializes an integer array to all zeros /* Inputs: anArray - array to be initialized /* size - size of the array /* Outputs: None /******************************************************************/ void initArray ( intanArray [ ], int size ) { for ( i = 0; i < size; i++ ) { anArray [ i ] = 0 ; } }
/****************************************************************************************/**************************************************************************************** ** fillArray - fills an integer array with valid values that are entered by the user. ** Assures the values are between MIN and MAX. ** Inputs: anArray - array to fill ** Outputs: size - size of the array ** Side Effect - MIN and MAX must be #defined in this file ****************************************************************************************/ void fillArray ( intanArray [ ], int size ) { inti ; /* loop counter */ for ( i = 0; i < size; i++ ) { printf (“Enter next value : ”) ; scanf (“%d “, &anArray [ i ] ) ; while ( (anArray [ i ] < MIN) || (anArray [ i ] > MAX) ) { printf ( “Values must be between %d and %d\n ”, MIN, MAX ) ; printf ( “Enter next value : ” ) ; scanf (“%d “, &anArray[ i ] ) ; } } } Grades Program (con’t)