Special PRG Lecture No. 2. Professor David Brailsford Special PRG Lecture: Arrays

Similar documents
A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Arrays and Pointers. CSE 2031 Fall November 11, 2013

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Computer System and programming in C

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Programming for Engineers Introduction to C

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Data types, variables, constants

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Programming for Electrical and Computer Engineers. Pointers and Arrays

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

DECISION CONTROL AND LOOPING STATEMENTS

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Welcome to... CS113: Introduction to C

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

Basic Assignment and Arithmetic Operators

Structured programming

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Basic Types and Formatted I/O

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Display Input and Output (I/O)

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental of Programming (C)

Goals of this Lecture

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

2. Numbers In, Numbers Out

Week 8: Arrays and File I/O. BJ Furman 21OCT2009

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Course Outline Introduction to C-Programming

Chapter 3: Arrays and More C Functionality

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Fundamental of Programming (C)

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Lectures 4 and 5 (Julian) Computer Programming: Skills & Concepts (INF-1-CP1) double; float; quadratic equations. Practical 1.

Basics of Programming

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Chapter 11 Introduction to Programming in C

HW1 due Monday by 9:30am Assignment online, submission details to come

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

2. Numbers In, Numbers Out

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

EC312 Chapter 4: Arrays and Strings

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Arrays and Pointers in C. Alan L. Cox

C Programming

Programming Language A

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

C: How to Program. Week /Mar/05

Arrays, Strings, & Pointers

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

Chapter 11 Introduction to Programming in C

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

At the end of this module, the student should be able to:

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

Review of the C Programming Language for Principles of Operating Systems

CSE / ENGR 142 Programming I

Dept. of CSE, IIT KGP

Summary of Lecture 4. Computer Programming: Skills & Concepts (INF-1-CP1) Variables; scanf; Conditional Execution. Tutorials.

Work relative to other classes

Procedural Programming

UIC. C Programming Primer. Bharathidasan University

Chapter 11 Introduction to Programming in C

A Fast Review of C Essentials Part I

printf( Please enter another number: ); scanf( %d, &num2);

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Chapter 11 Introduction to Programming in C

Lecture 16 CSE July 1992

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

CpSc 1111 Lab 4 Formatting and Flow Control

Chapter 1 & 2 Introduction to C Language

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Fundamentals of Programming Session 4

Programming and Data Structures

Transcription:

Special PRG Lecture No. 2 Professor David Brailsford (dfb@cs.nott.ac.uk) School of Computer Science University of Nottingham Special PRG Lecture: Arrays Page 1

The need for arrays Suppose we want to write a set of programs to analyse air temperatures in Nottingham, (in degrees Celsius rounded to the nearest integer) If there s only a handful of daily temperatures, not strongly related to one another, we might use separately-named integer variables e.g. int montemp = 14, tuetemp = 17, fritemp = 15; But if we need to hold a set of related temperatures e.g. for a whole week, or a whole year, it makes sense to use an array. We can declare an array to hold 7 temperatures as follows: int thisweek_temps[7]; We can declare an array in this way globally, or in main, or in a function Page 2

Initializing arrays If we want to set up initial values in the array at compile time then we can do it as follows: int thisweek_temps[7] = {9, 8, 13, 13, 11, 11, 6; Let s assume our week runs from Monday to Sunday. Monday s temperature can be selected via: thisweek_temps[0]; So we see that arrays can be indexed to select certain values but indexing starts at zero. To select Thursday s temperature do: thisweek_temps[3]; You can compile-time-intialize any array, declared locally or globally. But if your local array is of a large size then you may want to consider making it global, or possibly static (see later) Page 3

Indexing into arrays? So, thisweek_temps[3] is the fourth element of the array The C compiler knows that ints on a 32-bit machine (say) occupy 4 bytes each. So the fourth element starts at 4 3 = 12 bytes beyond start of array. We can have arrays of almost anything in C, e.g. doubles, chars, strings, functions etc. So long as the compiler knows the size of everything (characters, integers, addresses etc.) for the given machine, it can do array indexing calculations to find the address of the target array element.. The nth object in a one-dimensional array will be at (n 1) objectsize bytes beyond the array s start address Page 4

Example: average temperature using an array #include <stdio.h> int thisweek_temps[7] = {9, 8, 13, 13, 11, 11, 6; char mesg1[12] = { A, v, e, r, a, g, e,, i, s, :, \0 ; char mesg2[] = "Average is:"; /*declarations for mesg1 and mesg 2 both work OK!*/ /*But the mesg2 version is simpler */ int main(char argc, char *argv[]) { double avge; int i, total = 0; for (i=0; i < 7; i++) total = total + thisweek_temps[i]; avge = total / 7; printf("%s %2.2f\n", mesg1, avge); avge = total / 7.0; printf("%s %2.2f\n", mesg2, avge); /*different answer? */ Page 5

Analysis of last program Declaration for mesg1 as array of single chars is perfectly legal But to get it treated as a string, in printf, we must pack in a \0 at the end. A set of array initializers is enclosed in { braces The %2.2f in printf asks for two decimal places before and after the decimal point The value of total / 7 has two int arguments. Therefore C does the division in integer arithmetic and throws away the remainder It then converts the result, 10, to being 10.00 to match the double type of the variable avge To force real number division make one argument be an obvious real number (e.g. 7.0) Page 6

Two dimensional arrays #define NO_WEEKS 4/* number of weeks*/ #define NO_DAYS 7/* number of days in a week*/ #include <stdio.h> int nov_temps [NO_WEEKS] [NO_DAYS] = {9, 8, 13, 13, 11, 11, 6, 10, 9, 10, 10, 9, 9, 9, 10, 11, 12, 8, 8, 8, 9, 7, 4, 9, 9, 9, 9, 8; /* Note declaration and how it specifies 4 rows by 7 columns */ char mesg2[] = "Average forecast temp for Nov. is:"; int main(char argc, char *argv[]) { double avge; int i,j, total = 0; for (i = 0; i < 4 ; i++) for (j = 0; j < 7; j++) total = total + nov_temps[i][j]; avge = (double) total / (NO_WEEKS * NO_DAYS); printf("%s %2.2f\n", mesg2, avge); Page 7

Analysis of 2D array slide You can now envisage how a full year of temperatures could be kept in a 52 7 array e.g. int year_temps[52][7]; Note that subscripts of a two-dimensional array a are written, in C, in the form a[i][j] The format a[i,j], as used in mathematics, is WRONG in C The format A(I,J) as used in Basic is also WRONG Notice how nested for loops are a natural way to access array elements in turn The construct (double) total delivers a real number copy of the integer in total. The contents of total are unaffected This is our first encounter with a cast, as a way of forcing a type conversion Page 8

Input / output to and from arrays (1) So far we have pre-initialized the values in our global arrays But more commonly we will want to assign values to array elements or even to read in the array values as data Examples: price[5] = 10.65; scanf("%d %2.2f", &grades[0], &price[2]); scanf("%c", &code[0]); /* code is an array of chars */ scanf("%d %d %d", &grades[0], &grades[1], &grades[2]); /* However a more usual way to fill in successive array elements would be: */ for (i = 0; i <= 3 ; i++) /* reads in 4 values */ { printf("enter a grade: "); scanf ("%d", &grades[i]); Page 9

Page 10 Input/output to and from arrays (2) We can output individual array elements using printf But more commonly we will want to output successive array values using a for loop. Examples: printf ("%2.2f", price[6]); printf("the value of element %d is %d", i, grades[i]); for (n = 5; n <= 20; n++) printf("%d %2.2f\n", n, price[n]); Note that C does not check whether your array subscripts are within the declared array bounds. If you get the array indexing wrong the program will (probably) crash at run time However the compiler will do its best to issue warnings if it feels your array-accessing code is suspect in any way

Outputting arrays of chars Let s revisit our old friends mesg1 and mesg2 Page 11 #include <stdio.h> #define MSIZE 12 char mesg1[msize] = { A, v, e, r, a, g, e,, i, s, :, \0 ; char mesg2[] = "Average is:"; /*declarations for mesg1 and mesg 2 both work OK!*/ /*But the mesg2 version is simpler */ int main(char argc, char *argv[]) { int i; for (i = 0; i < MSIZE - 1; i++)/* Why MSIZE -1?*/ printf("%c", mesg1[i]); printf("\n"); /*Much more efficient way but still step-by-step is */ char *p = mesg1;/* p is of type "pointer to char" */ while (*p!= \0 ) { putchar(*p); p++; /* *p means "get me the contents of byte address p" */ /* The p++ increments the byte address,as we ve just covered in G51CSA */ printf("%s", mesg1); /* automates the above while loop! */

Analysis of last slide Indexing arrays of chars in a printf inside a for loop works just fine! You need to know the array size in order to stop the loop from printing out characters beyond the end of the array The compiler has to work out each indexed byte address from first principles. This involves (slow) multiplies and adds (see slide 4) But if we know the characters are stored next to each other then we can just increment the byte address every time around the loop. The while-loop-plus-pointer method is the one we ve used in G51CSA Note how helpful C is when handling strings. The %s formatter in printf automates string printouts. You ll learn much more about pointers later in the module Page 12

Page 13 More about initialization Once C knows the overall size of an array then initialization can be done with a one-dimensional list of values This is true even for a multi-dimensional array! Examples: /* All three of the declarations below are equivalent */ /*declaration 1 */ int val[3][4] = {8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10; /*declaration 2 */ int val[3][4] = {8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10; /*declaration 3. Note CAREFULLY where the commas and braces are placed */ int val[3][4] = { {8, 16, 9, 52, {3, 15, 27, 6, {14, 25, 2, 10 ; To preserve the sanity of the maintenance programmer who comes after you, adopt style 2, or style 3, for 2D arrays.

Passing array parameters to procedures An array parameter to a procedure passes over the array s start address Technical phraseology is: Array names are passed by reference Contrast this with an int parameter, where a copy is made (i.e. it is passed by value) It is not feasible to pass arrays by value would need to make a copy of a (potentially huge) array! The formal parameter in the function definition must specify the array bounds so that the compiler can check your usage Be careful that because the actual array parameter is a start address (a reference) then any alteration to array elements inside the function affects the values in the original array. Page 14

Maximum November temperature Function to find a maximum temperature in a 2D array Page 15 #include <stdio.h> #define NO_WEEKS 4 /* number of weeks*/ #define NO_DAYS 7 /* number of days in a week*/ int nov_temps [NO_WEEKS] [NO_DAYS] = {9, 8, 13, 13, 11, 11, 6, 10, 9, 10, 10, 9, 9, 9, 10, 11, 12, 8, 8, 8, 9, 7, 4, 9, 9, 9, 9, 8; char mesg2[] = "Maximum forecast temp. for Nov. is:"; int maxval(int vals[no_weeks][no_days]) { int i, j, temp, max = 0; for (i = 0; i < NO_WEEKS; i++) for (j = 0; j < NO_DAYS; j++) { temp = vals[i][j]; if (temp > max) max = temp; return (max); int main(char argc, char *argv[]) { printf("%s %d\n", mesg2, maxval(nov_temps));

Analysis of max November temp. The function maxval delivers the maximum temperature from an array transmitted to it with (formal) parameter name vals The actual parameter on this occasion is the global array nov_temps So why not dispense with the function parameter and let the maxval function operate directly on the globally visible name nov_temps? But if you do that you would limit maxval to working only with nov_temps! Parameterised version of the function can take, as input, any suitable local or global array Notice the formal parameter declaration for vals where you tell the compiler to expect an incoming 2D array Page 16

Page 17 Maximum October temperature using scanf #include <stdio.h> #define NO_WEEKS 4 /* number of weeks*/ #define NO_DAYS 7 /* number of days in a week*/ char octmess[] = "Maximum October temp. was :"; int maxval(int vals[no_weeks][no_days]) { int i, j, temp, max = 0; for (i = 0; i < NO_WEEKS; i++) for (j = 0; j < NO_DAYS; j++) { temp = vals[i][j]; if (temp > max) max = temp; return (max); int main(char argc, char *argv[]) { int i=0, j=0; int oct_temps [NO_WEEKS] [NO_DAYS]; for (i = 0; i< NO_WEEKS; i++) for (j = 0; j< NO_DAYS; j++) scanf("%d,", &oct_temps[i][j]); printf("%s %d\n", octmess, maxval(oct_temps));

Analysis of max October temp. This time the actual parameter to maxval is an array oct_temps declared locally to main Filling the oct_temps array is done with input data, via scanf Note that scanf ignores all spaces, newlines, vertical tabs etc. (collectively known as whitespace) So you can spread your input data over several lines if you want However the particular scanf format used here does expect that every single input value will be followed by a comma. Don t forget the & in &oct_temps[i][j] If you do forget, then you will get a Segmentation Violation at run time i.e. a bad address. (I speak as one who knows ) Page 18

Initializations global, local and static Original K&R C in the 1970s allowed only global arrays to be initialized This restriction was for efficiency reasons. Local array initializations have to be recreated every time you enter and re-enter a function ANSI C (1983) lifted the restriction but we need to understand the issues Consider the following fragment: #include <stdio.h> int hugearray[10000] = { /* massive initialization here */; int myfunc (double d) { int i,j; char message[] = "This is a fairly long but not too extensive string"; int thisweek_temps[7] = {9, 8, 13, 13, 11, 11, 6; static int bigarray[1000] = {/* 1000 initialization values here */; Page 19

Initializations more analysis The initialized contents of message and thisweek_temps are no big deal (approx. 50 bytes and 30 bytes respectively) So setting them up afresh, in calls of myfunc, is no big deal either But bigarray is different. If you miss off the static keyword then all 4Kbytes of it (on a 32-bit m/c) will be re-initialized each time The effect of static is to store it globally but to restrict where you can access it (via the identifier bigarray) to the function in which you declared it (myfunc) So changes to bigarray will persist between function calls By contrast hugearray is global and visible everywhere (Dangerous?!) You ll be amused to know that there is a paper entitled: Global Variable Considered Harmful by Bill Wulf Page 20