Why arrays? To group distinct variables of the same type under a single name.

Similar documents
Arrays. What if you have a 1000 line file? Arrays

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays, Strings, & Pointers

ESC101N: Fundamentals of Computing End-sem st semester

Arrays. Arrays (8.1) Arrays. One variable that can store a group of values of the same type. Storing a number of related values.

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

Strings. Chuan-Ming Liu. Computer Science & Information Engineering National Taipei University of Technology Taiwan

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

Computer Science & Engineering 150A Problem Solving Using Computers

Lesson #8. Structures Linked Lists Command Line Arguments

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

PDS Class Test 2. Room Sections No of students

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

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

CSCI 171 Chapter Outlines

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

Arrays and Pointers in C. Alan L. Cox

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

20 Dynamic allocation of memory: malloc and calloc

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

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

ARRAYS(II Unit Part II)

A Fast Review of C Essentials Part I

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

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

C programming basics T3-1 -

Lecture 04 Introduction to pointers

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Kurt Schmidt. October 30, 2018

Arrays and Strings. Arash Rafiey. September 12, 2017

COMP1917: 09 Arrays and Strings

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

ESC101N Fundamentals of Computing

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

1 Pointer Concepts. 1.1 Pointer Examples

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Computers Programming Course 11. Iulian Năstac

ONE DIMENSIONAL ARRAYS

CSC 2400: Computer Systems. Arrays and Strings in C

Array Initialization

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Arrays and Pointers (part 1)

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computers Programming Course 10. Iulian Năstac

Pointers and File Handling

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

First of all, it is a variable, just like other variables you studied

Lesson 7. Reading and Writing a.k.a. Input and Output

Dynamic Memory Allocation and Command-line Arguments

Pointers. Pointer References

Lab 3. Pointers Programming Lab (Using C) XU Silei

CS Programming I: Arrays

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

CS201 Lecture 2 GDB, The C Library

Intermediate Programming, Spring 2017*

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Computer Science & Engineering 150A Problem Solving Using Computers

Content. In this chapter, you will learn:

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Pointers. Introduction

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

8. Characters, Strings and Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CSC 2400: Computer Systems. Arrays and Strings in C

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

Contents of Lecture 3

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

This exam is worth 24 points, or 24% of your total course grade. The exam contains six

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

Arrays and Pointers (part 1)

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Unit 7. Functions. Need of User Defined Functions

PERIYAR CENTENARY POLYTECHNIC COLLEGE Periyar Nagar- Vallam Thanjavur

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions

C Structures, Unions, Bit Manipulations, and Enumerations

CSE / ENGR 142 Programming I

Contents. A Review of C language. Visual C Visual C++ 6.0

Sequential Search (Searching Supplement: 1-2)

Fast Introduction to Object Oriented Programming and C++

Carnegie Mellon. Cache Lab. Recitation 7: Oct 11 th, 2016

OBJECT ORIENTED PROGRAMMING USING C++

Multidimension array, array of strings

CSE 303 Midterm Exam

C mini reference. 5 Binary numbers 12

Transcription:

Lesson #7 Arrays

Why arrays? To group distinct variables of the same type under a single name. Suppose you need 100 temperatures from 100 different weather stations: A simple (but time consuming) solution would be to have 100 different variables to hold the values. A better solution is to have one array with 100 cells.

Declaring arrays To declare regular variables (a.k.a. scalar variables), you just specify its type and its name: double x; You also have the option of declaring and putting a value in it at the same time: double y=3.57; To declare an array, you specify its type, its name and how many cells you need: double z[100];

Declaring arrays You can also put the values in the array while declaring it: double a[5]={1.3, 2.4, 6.2, 4.5, 1.1}; When declaring and initializing, the size is then optional: double b[ ]={6.78, 7.88, 4.55, 1.33}; What is the size of array b?

Referencing values Let's have the declaration: int age [6]; It creates an array of integers that looks like this: age Each cell can be referenced by a number. Numbering always starts at zero. age 0 1 2 3 4 5

Cell numbers A cell is always referenced by its cell number (also called subscript or offset). age[2] is actually the third cell of the array called age. Note that age[6] does not exist! Since age is size 6, then its cells are numbered from 0 to 5 only.

Filling an array To fill an array with values, we first have to know that individual cells behave exactly like regular (scalar) variables. age 0 1 2 3 4 5 age[2]=35; will put the value 35 into cell 2. age 0 1 2 3 4 5 35

Filling an array You can also ask the user (or read from a file) for a value to put into the array: scanf ("%d", &age[4]); will put the value entered into cell #4. Let's suppose the user enters 42. We have then 0 1 2 3 4 5 age 35 42 You can also have operations like this: age[0]=age[4]*2+age[2]; 0 1 2 3 4 5 age 119 35 42

Filling an array But by far the most powerful way to fill an array is to use a loop. The following code, for (i = 0; i < 6; ++i) age[i] = i * i; will give this result. Notice that the previous values have been replaced by the new ones just like regular variables: age 0 1 2 3 4 5 0 1 4 9 16 25

Filling/printing an array Another common way to fill an entire array with a loop is to read all the values from the keyboard or a file. for (i = 0; i < 6; ++i) scanf ("%d", &age[i]); An easy way to print out the entire array is: for (i = 0; i < 6; ++i) printf ("%d ", age[i]);

Arrays and pointers We know variables that contain addresses of other variables in C are called pointers. &x is the address of x or where is x? If we assign &x to a variable y (y being of int* type), y becomes a pointer to x and *y is in fact x itself. For arrays, only the address of the first cell is important as all cells are stored together in the machine. x[1] is stored next-door to x[0]. The array name without any subscript is the address of the first cell (but is not actually a pointer as you cannot modify it). If I have an array declared int age[6];, age is the same thing as &age[0].

Arrays and pointers Now that we understand the relation between addresses and arrays better, let's revisit the array declaration. int age [6]; age 0 1 2 3 4 5 age, as we know, is the address of age[0], but age+1 is the address of age[1], age+2 the address of age[2], and so on...

Arrays and cells age being an array, a statement like age=70; would be illegal as age would be an address, not a value. With a value, you must always mention which cell to fill, so age[3]=70; would be correct. The sizeof operator will return the size (in bytes) of the array. printf ("%d", sizeof (age)); would display 24 on a 32-bit system (6 cells of integers at 32 bits or 4 bytes each).

Sending arrays to functions Sending an array to a function is like sending multiple values all at once. The best way is to send the address (the array name alone) to the function so that the function can work with the original array stored in the calling function (main). Let's have a function that finds the largest value in an array of integers and returns the cell number where it was found. Note that we must always send the size of the array as an argument because the function will have no way of knowing it otherwise.

Sending arrays to functions find (int array[], int size) { int i, largest, where; largest = array [0]; for (i=0; i<size; ++i) if (array[i]>largest) { largest = array[i]; where = i; } return (where); } *** There is something missing in this program, can you find out what?

Sending arrays to functions /* the main program */ int main (void) { int a[] = {6,2,8,7,3}; int location; location = find (a, 5); printf ( Cell #%d\n, location); return (0); }

Having an array as a result An array can never be a result as it represents multiple values. As with function with multiple results, we will have to use pointers. void addarrays (const int a[], const int b[], int c[], int size) { int i; for (i=0; i<size; ++i) c[i] = a[i] + b[i]; } The const option means that the specified array cannot be modified by the function.

Having an array as a result /* the main program */ int main (void) { int x[] = {1,2,3,4}, i; int y[] = {10,20,30,40}; int z[4], i; addarrays (x, y, z, 4); for (i=0; i<4; ++i) printf ("%4d", z[i]); return (0); }

Sending arrays to functions (multiple results ) /* function provides the smallest value in an array and its location */ find_small (int array[], int size, int *smallest) { int i, where; *smallest = array [0]; where = 0; for (i=0; i<size; ++i) if (array[i] < *smallest) { *smallest = array[i]; where = i; } return (where); }

Sending arrays to functions (multiple results ) /* the main program */ int main (void) { int a[] = {6,2,8,7,3}; int location, small; location = find_small (a, 5, &small); printf ( Smallest number: %d\n, small); printf ( Location: %d\n, location); return (0); }

Dynamic allocation of arrays Arrays, as we know them now, can only be of a fixed size. int x[100]; declares an array size 100, no less no more. It is illegal in ANSI C to do the following. Do you know why? printf ("Enter the size of the array: "); scanf ("%d", &size); int x[size];

Dynamic Allocation of Arrays It is impossible to have arrays of varying sizes because that makes programming inefficient. C is very strict with arrays but it is also the most efficient of all the high-level languages. There is a way to have dynamic allocation in C. The solution is to use heap memory instead of the usual memory we have been using so far. Heap memory: slower, less-structured, dynamic memory.

Using a dynamic array int size; /* 1. declare a pointer to the array */ double *array; printf ("Enter the size of the array: "); scanf ("%d", &size); /* 2. allocate the array in the heap */ array = (double *) calloc (size, sizeof(double)); /* 3. use the array normally */... /* 4. free the heap memory */ free (array); See the complete program at ihypress.net/programming/c/07.php (program #9)

Arrays of characters (Strings) There is no string type in C. Instead, to approximate strings, we will use arrays of characters. To transform a simple array of characters into a string, it must contain the '\0' character in the last cell. Note that '\0' is one character. It is called the null character or the end-of-string character.

Strings To declare a string and initialize it we could do it the same way as seen before: char city[ ] = {'T', 'o', 'r', 'o', 'n', 't', 'o', '\0'}; Notice that the size of the array can be omitted here, since the computer can deduce it. However, declaring the size (in this case 8), is always good form. But there is a simpler way: char city[ ] = "Toronto"; If you specify the size here, do not forget the invisible '\0'! Size must be 8 not 7! The result is exactly the same. By using the simpler way, the '\0' is added automatically at the end. city 0 1 2 3 4 5 6 7 'T' 'o' 'r' 'o' 'n' 't' 'o' '\0'

"X" and 'X' Double quotes " " represent a string, single quotes ' ', one character. 'X' is the single character X, but "X" is an array size 2 containing the 'X' character and the '\0' character. All string constants are represented in double quotes (remember "This is my first C program."?).

Accessing array cells Array cells in strings can be accessed by subscript like numerical arrays. For example, after the following operation, the city string seen earlier would become Taranta. for (i=0; i<7; ++i) if (city[i]=='o') city[i]='a';

Arrays of strings It is also possible to have arrays of strings. Since strings are themselves arrays, then we need to add a second size. An array of strings is in fact an array with two dimensions, width (columns) and height (rows). char list_cities[100][15]; will be able to contain 100 city names with a maximum of 14 letters per city. Why not 15?

Arrays of strings (cont.) Example: An array containing the names of the months. char months [12][10] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; Can you find the value of months[3]? How about months [7][3]?

Filling a string We have already seen how to fill a string by initializing it in a declarative statement. Now how to do it in an executable statement. To fill a string from standard input (scanf) or file (fscanf), we use a special placeholder for strings %s. scanf ("%s", city); (Notice the absence of &. It is not necessary here since city is already an address, the same as &city[0], remember?)

Filling a string (scanf vs. fgets) There is one problem with the %s placeholder when used with scanf (or fscanf). It considers the space as a delimiter. Therefore, if for a city name you enter Los Angeles, you will get only Los stored in the string. The solution is to use a function named fgets. That function only considers the new line character as the delimiter, not the space. Instead of scanf ("%s", city); you use fgets (city, size, stdin); instead of fscanf (in, "%s", city); you use fgets(city, size, in);

Filling a string (gets) A simpler gets function exists in C but its usage is considered dangerous. gets does not allow you limit the amount of input, which means it can potentially overflow the buffer into which the input is placed (for example you could read a sentence of 100 characters into an array size 10!). gets is deprecated (obsolete). Programs that use gets can actually be a security problem on your computer. Always use fgets.

Printing a string The space problem does not occur with printf. If the city is "Los Angeles" then a printf ("%s", city); will print out the entire city name.

String function: strcpy There are many useful functions to manipulate strings in the string library (need #include <string.h>). strcpy: the function to transfer a string into a variable. Equivalent to the assignation operator. With strings you cannot do city="toronto"; in an executable statement. To do an assignment operation we must use strcpy. char city[10], city2[10]; strcpy (city, "Toronto"); /* places "Toronto" into city /* strcpy (city2, city); /* places "Toronto" into city2 /* city2 0 1 2 3 4 5 6 7 8 9 'T' 'o' 'r' 'o' 'n' 't' 'o' '\0'??

String function: strlen strlen: the strlen function returns the length of the string not counting the null character. char city[10]; strcpy (city, "Toronto"); /* places "Toronto" into city */ printf ("%d", strlen (city)); /* displays 7 on the screen */

An example using strings #include <stdio.h> #include <string.h> int main (void) { char city[20], city2[20]; printf ("What is the capital of Canada? "); fgets (city, 20, stdin); /* the string is read with fgets */ printf ("What is the capital of Argentina? "); fgets (city2, 20, stdin); /* \n kept at end if input smaller than array size, replace it with \0 */ city[strlen(city)-1] = '\0'; city2[strlen(city2)-1] = '\0'; /* here is the report */ printf ("\nthe capital of Canada is: %s.", city); printf ("\nthe capital of Argentina is: %s.", city2); } return (0);

Arrays of multiple dimensions We have seen that with strings, we can have arrays of strings. These arrays of strings are actually arrays of arrays. Arrays of arrays are also called two-dimensional arrays. If it is possible with strings, it is also possible with numerical arrays. We use two dimensions when we require two coordinates: map coordinates, pixels on a screen, matrix representations and so on...

Multiple Dimensions The number of subscripts used to access a particular element in an array is called the dimension of the array. An array of two dimensions will have two sizes (number of rows and number of columns), hence by multiplying the two sizes we obtain the total number of cells. For example a dozen eggs in a carton could be an array size 2x6.

Two Dimensions An array of two dimensions can be represented by a grid of rows and columns. Each row is numbered from 0 to size-1 (like an regular array). The same for the columns. int a[3][4]; will declare an 2D array of integers with 3 rows (numbered 0-2) and 4 columns (numbered 0-3). By providing the two coordinates, we can refer to an individual cell. a[1][2]=57; will place the value 57 into the third cell of the second row.

a Two Dimensions 0 1 2 3 0 1 57 2

A Simple 2D Program Let's have a simple program that will fill a 5x5 matrix with values taken from a file that contains 25 integers and then find the locations of the zero values. To travel within a 2D array we will need two travelling variables (we only needed one for 1D arrays). We usually name them i and j for historical reasons dating from the days of the Fortran programming language.

A Simple 2D Program #include <stdio.h> int main (void) { int matrix[5][5]; int i, j; FILE *in; in=fopen("data2.dat", "r"); for (i=0; i<5; ++i) for (j=0; j<5; ++j) fscanf (in, "%d", &matrix[i][j]); fclose(in); /* the matrix is filled */

A Simple 2D Program (Cont.) /* find zeros */ for (i=0; i<5; ++i) for (j=0; j<5; ++j) if (matrix[i][j]==0) printf ("Zero found at: %d / %d\n", i, j); /* print matrix */ for (i=0; i<5; ++i) { for (j=0; j<5; ++j) printf ("%4d", matrix[i][j]); printf ("\n"); } } return (0);

2D Arrays and Functions To send a 2D array to a function, we must send (as we did for 1D arrays), the array name alone as argument (the address of the array's cell 0). Like 1D arrays of numbers we must send the size (we need two now, the number of rows and the number of columns). As formal parameters in the function, the array must be indicated with two subscripts of course and we must have two parameters to receive the two sizes..

2D Arrays and Functions /* get the largest number in a 2D array of doubles */ double largest2d (double array[10][10], int nrows, int ncols) { int i, j; int large = array[0][0]; for (i=0; i<nrows; ++i) for (j=0; j<ncols; ++j) if (array[i][j]>large) large = array[i][j]; return (large); The call would look like this: y = largest2d (a, r, c); array sizes } See ihypress.net/programming/c/09.php (program #1) for another example.

2D Dynamic Allocation There are two methods to do dynamic allocation for two dimensional arrays The first one is called the software engineer's method. Dynamic allocation of arrays of more than one dimension is easily done. You can simulate a twodimensional array with a single, dynamicallyallocated one-dimensional array. However, you must now perform subscript calculations manually, accessing the [i][j]th element with array[i * ncolumns + j]. Software engineers prefer this method for its elegance and efficiency.

2D Dynamic Allocation The second method is called the traditional or computer scientist's method. Dynamic allocation of arrays of more than one dimension can also be done using a pointer pointing to an array of pointer and each pointer of that array pointing to an array of values. With that method you can use the real 2-D subscripts like array[i][j]. Visit ihypress.net/programming/c/09.php (programs #5 and #6) for examples of the two methods of 2D dynamic allocation.

Vectors and Matrices One of the most common use of arrays in scientific or engineering applications is the translation of vectors into 1D arrays and matrices into 2D arrays. A vector V = <10,20,30,40> would be represented by an array int v[4] = {10,20,30,40}; V1 being the first element, in the previous example, would be 10, represented in C by v[0]. Note that in math we start counting at 1 but in C, we start at 0. For matrices, the same approach uses 2D arrays. M21 would be translated as m[1][0]. Visit ihypress.net/programming/c/09.php (programs #2, #3, and #4) for examples.

End of lesson