Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Chapter 7: User-Defined Functions II
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
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: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
1 CSC 211 Data Structures Lecture 4 Dr. Iftikhar Azim Niaz 1.
UMBC CMSC 104 – Section 01, Fall 2016
User-Written Functions
UMBC CMSC 104 – Section 01, Fall 2016
Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Computer Science 210 Computer Organization
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
- Standard C Statements
Functions, Part 2 of 2 Topics Functions That Return a Value
Arrays in C.
User-Defined Functions
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
CS 1430: Programming in C++.
Computer Science 210 Computer Organization
FUNCTIONS WITH ARGUMENTS
Arrays, Part 1 of 2 Topics Definition of a Data Structure
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
The while Looping Structure
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
Final Exam Final Exam: Thursday Dec 13th, 2001 at 8:30 pm in SS-111, the regular classroom.
EKT150 : Computer Programming
Functions, Part 2 of 3 Topics Functions That Return a Value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
The while Looping Structure
Introduction to C Topics Compilation Using the gcc Compiler
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
A function with one argument
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Chapter 7 Arrays PROGRAMMING IN ANSI C.
Functions with arrays.
Topics discussed in this section:
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays Topics Definition of a Data Structure Definition of an Array
Chapter 7: User-Defined Functions II
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays I Handling lists of data.
Introduction to C Topics Compilation Using the gcc Compiler
Fundamental Programming
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Dale Roberts, Lecturer IUPUI
Variables in C Topics Naming Variables Declaring Variables
The while Looping Structure
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays Topics Definition of a Data Structure Definition of an Array
Functions, Part 2 of 3 Topics Functions That Return a Value
The while Looping Structure
Functions, Part 2 of 42 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
More Loops Topics Counter-Controlled (Definite) Repetition
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Presentation transcript:

Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works Call by Value Call by Reference Grades Program Revised Reading Section 5.8 Sections 6.1 - 6.5

Array Declarations Revisited int numbers[5] ; This declaration sets aside a chunk of memory that is big enough to hold 5 integers. Besides the space needed for the array, there is also a variable allocated that has the name of the array. This variable holds the address of the beginning (address of the first element) of the array. FE00 numbers FE00 -- -- -- -- -- 0 1 2 3 4

Array Name Holds an Address #include <stdio.h> int main( ) { int numbers[5] = {97, 68, 55, 73, 84} ; printf (“numbers[0] = %d\n”, numbers[0]) ; printf (“numbers = %X\n”, numbers) ; printf (“&numbers[0] = %X\n”, &numbers[0]) ; return 0 ; } numbers[0] = 97 numbers = FE00 &numbers[0] = FE00 output

Location=(beginning address) + (index * sizeof(array type)) How Indexing Works numbers[2] = 7 ; The element assigned the value 7 is stored in a memory location that is calculated using the following formula: Location=(beginning address) + (index * sizeof(array type)) Assuming a 4-byte integer, Location = FE00 + (2 * 4) FE00 FE04 FE08 FE0C FE10 numbers FE00 97 68 7 73 84 0 1 2 3 4

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.

int float num1 num2 average 5 8 int float val1 val2 ave #include <stdio.h> float averageTwo (int num1, int num2) ; int main ( ) { float ave ; int val1 = 5, val2 = 8 ; ave = averageTwo (val1, val2) ; printf (“Ave of %d and %d is %f\n”, val1, val2, ave) ; return 0 ; } float averageTwo (int num1, int num2) { float average ; average = (num1 + num2) / 2.0 ; return average ; } int float num1 num2 average 5 8 int float val1 val2 ave

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.

Passing an Array to a Function #include <stdio.h> #define SIZE 4 void fillArray (int intArray[ ], int size) ; int main ( ) { int i; int someArray [SIZE] ; fillArray (someArray, SIZE) ; /* Print the elements of the array */ for ( i = 0; i < SIZE; i++ ) printf (“someArray[%d] = %d\n”, 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 ; } 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 Read Grades Process the Grades Print the Results Initialize Grade Counts To Zero Print User Instructions Calculate Average Score

“Clean” Grades Program (con’t) #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[ ] ) ;

int score [SIZE]; /* 39 student scores */ Main Read Grades Process the Grades Print the Results Initialize Grade Counts To Zero Print User Instructions Calculate Average Score int main ( ) { int score [SIZE]; /* 39 student scores */ int gradeCount [GRADES] ; /* 5 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 ; }

“Clean” 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”) ; }

“Clean” 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 (int anArray [ ], int size) { int i; for ( i = 0; i < size; i++ ) anArray [ i ] = 0 ; }

“Clean” Grades Program (con’t) void fillArray (int anArray [ ], int size) { int i ; /* 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) ; scanf (“%d “, &anArray[ i ] ) ; }/*end of while*/ }/*end of for*/ }

“Clean” Grades Program (con’t) double ProcessGrades (int score [ ], int size, int gradeCount [ ] ) { int i; int total = 0; /* total of all scores */ double average; /* average score */ for ( i = 0 ; i < size ; i++) { total += score [ i ] ; switch ( score [ i ] / 10 ) case 10 : case 9 : gradeCount [A]++ ; break ;

case 8 : gradeCount [B]++ ; break ; case 7 : gradeCount [C]++ ; Main Read Grades Process the Grades Print the Results Initialize Grade Counts To Zero Print User Instructions Calculate Average Score case 8 : gradeCount [B]++ ; break ; case 7 : gradeCount [C]++ ; case 6 : gradeCount [D]++ ; case 5 : case 4 : case 3 : case 2 : case 1 : case 0 :gradeCount [F]++ ; default : printf (“Error in score.\n”) ; } average = findAverage (total, size) ; return average ;

“Clean” Grades Program (con’t) /*************************************************************** ** 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 ;

“Clean” Grades Program (con’t) /*********************************************************************************** ** printResults - prints the class average and the grade distribution for ** the class. ** Inputs: average - class average ** gradeCount - number of A’s, B’s, C’s, D’s, and F’s ** Outputs: None ** Side Effect: A, B, C, D, and F must be #defined in this file /***********************************************************************************/ void printResults (double average, int gradeCount [ ] ) { printf (“The class average is %.2f\n”, average ) ; printf (“There were %2d As\n”, gradeCount [A] ) ; printf (“ %2d Bs\n”, gradeCount [B] ) ; printf (“ %2d Cs\n”, gradeCount [C] ) ; printf (“ %2d Ds\n”, gradeCount [D] ) ; printf (“ %2d Fs\n”, gradeCount [F] ) ; }

%d prints as decimal integer %6d prints as decimal integer at least 6 characters wide %f prints as floating point %6f prints as floating point of at least 6 characters wide %.2f prints as floating point, 2 characters after the point %6.2f prints as floating point, at least 6 characters wide and 2 characters after the point

#include<stdio.h> int main(){ int a=123456789; int b=12; float c=2.012345; printf(“a=>%6d<\n",a ); printf(“b=>%6d<\n",b); printf(“c=>%f<\n",c); printf(“c=>%.3f<\n",c); printf(“c=>%.2f<\n",c); return 0; } a=>123456789< b=> 12< c=>2.012345< c=>2.012< c=>2.01< Note the 4 spaces Before the number %6d makes it print the number at least 6 characters wide