Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Introduction to C Programming
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 10.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Week 7 – String. Outline Passing Array to Function Print the Array How Arrays are passed in a function call Introduction to Strings String Type Character.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
UniMAP SEM I - 10/11EKT 120 Computer Programming1 Lecture 8 – Arrays (2) and Strings.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Dr. Sajib Datta  Ordering elements in some way  For numeric data, ascending order is the most common  Lots of techniques for sorting  These.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
C Formatted Input/Output
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Strings CSCI 112: Programming in C.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Computer Science 210 Computer Organization
Fundamentals of Characters and Strings
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
CSE 1320 Search, Sort and Strings
ICS103 Programming in C Lecture 3: Introduction to C (2)
A First Book of ANSI C Fourth Edition
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Arrays in C.
Computer Science 210 Computer Organization
Object Oriented Programming COP3330 / CGS5409
C Arrays.
Strings.
Arrays Kingdom of Saudi Arabia
Week 9 – Lesson 1 Arrays – Character Strings
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
IPC144 Introduction to Programming Using C Week 8 – Lesson 1
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Chapter 16 Pointers and Arrays
Chapter 8 Character Arrays and Strings
Arrays Arrays A few types Structures of related data items
EECE.2160 ECE Application Programming
Exercise Arrays.
CS31 Discussion 1H Fall18: week 6
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
EECE.2160 ECE Application Programming
4.1 Introduction Arrays A few types Structures of related data items
Files Chapter 8.
Presentation transcript:

Introduction to Programming Using C Arrays

2 Contents Arrays Subscripting

3 Arrays All of the variables we have seen hold a single value For some problems, this is sufficient Other problems need to read a great many values and store them Consider the problem of calculating the marks for a class of students

4 Arrays Each student has marks for each assignment and test We want to calculate the average mark for each assignment and test as well as the final mark for each student To do this we need – A mark variable to sum up the individual marks for each student and print the result – A variable to hold the sum of all marks for each assignment so we can calculate the average

5 Arrays We cannot calculate the average mark for each assignment until we have read all of the marks, so the variables holding the sums need to be stored until the end of the data One solution is to create a series of variables – double item1Total, item2Total, item3Total, item4Total, item5Total, item6Total, item7Total; Now, when we read the data, all we have to do is add onto each total

6 Arrays for(i = 1; i <= numMarks; i++) { scanf(“%lf”, mark); studentTotal += mark; switch(i) { case 1: item1Total += mark; break; case 2: item2Total += mark; break; case 3: item3Total += mark; break; case 4: item4Total += mark; break; case 5: item5Total += mark; break; case 6: item6Total += mark; break; case 7: item7Total += mark; break; }

7 Arrays That’s a long piece of code to decide which variable to add onto In fact we do the same thing every time and just change the number in the variable name There must be a better way …

8 Arrays What we need is – A single variable with one name – That can hold several values – Where we can specify the value we want by its number That is exactly what an array is !

9 Arrays We can declare an array called itemTotal that can hold 10 marks like this – double itemTotal[10]; This lays out 10 storage locations, each of which can hold one number Each location is numbered from zero up itemTotal

10 Subscripting We can access any member of the array by enclosing its number in square brackets – itemTotal[1] accesses the second member – itemTotal[9] accesses the last member Accessing array members by specifying their position is called subscripting Now that we have arrays, we can rewrite the code to read and store the totals like this

11 Subscripting for(i = 1; i <= numMarks; i++) { scanf(“%lf”, mark); studentTotal += mark; itemTotal[i] += mark; } This code is – Shorter – Easier to read – Easier to write – Less prone to error * See arraysumdemo.c

12 Passing Arrays to Functions Passing an array by copying all of the values can be an expensive operation if the array is big A better way, is to pass the address of the first member of the array This is the way it is done and you don’t have to use the & operator or the * operator within the function

13 Passing Arrays to Functions Let’s say that we want to create a function to fill an array with a single value void fill(int ar[], int value, int size) { int i; for(int i = 0; i < size; i++) { ar[i] = value; }

14 Passing Arrays to Functions Things to note – We can indicate an array is being passed using empty square brackets int ar[] You might also see this written as a pointer to an integer int *ar – We cannot determine the size of the array and must pass this as a parameter – We don’t have to dereference the array to access the value, just subscript it – All changes made by the function really affect the original array, not a copy of it

15 Passing Arrays to Functions We can call this function as follows #include void fill(int ar[], int value, int size) ; #define SIZE 10 main() { int i, totals[SIZE]; fill(totals, 0, SIZE); for(i = 0; i < SIZE; i++) printf(“%d “, totals[i]); }

16 Initializing Arrays Arrays can be initialized by supplying them with values in curly brackets when they are declared – int x[5] = {10, -2, 4, 88, 91}; This is the same as if we had typed – x[0] = 10; – x[1] = -2; – x[2] = 4; – x[3] = 88; – x[4] = 91; * See arrayfinddemo.c

17 Initializing Arrays If you – Supply too many values, the extra are discarded – If you don’t supply enough, the remaining elements are set to zero If you do not initialize any variable, you have no idea what its value is This assignment of values to the entire array can only be done once, at initialization time

18 Character Strings It is common to want to store strings in your programs A string is stored as – An array of characters of a fixed length – A special character ‘\0’ that marks the end of the string, which might be shorter than the array in which it is stored

19 Character Strings We can declare a character array to hold a string like this – char name[10]; – Which will allow us to store up to 9 letter names plus the string terminator ‘\0’ String constants are always enclosed in double quotes – “Fred”

20 Character Strings What is actually generated is – “Fred\0” – Since the ‘\0’ terminator is automatically appended to all string constants Assigning a string constant to an array is not straight-forward and requires that we use a function called strcpy()

21 Character Strings To assign our name to the array we type – strcpy(name, “Fred”); – This has the effect of copying the value of the 2 nd parameter to the 1 st parameter – The direction of the assignment is right-to-left just like the assignment operator After the assignment, out array looks like this name Fred\0

22 Character Strings The string terminator is actually the null character and has the numeric value 0 If you look at an ASCII table, you will see it as the first value in the table Since it does not print as anything, we cannot type it, so use the special notation – ‘\0’

23 strcpy To see how strcpy works, let’s write our own void mystrcpy(char to[], char from[]) { int i; for(i = 0; from[i] != ‘\0’; i++) { to[i] = from[i]; } to[i] = ‘\0’; }

24 strcpy As you can see, this is just regular code which copies characters one-by-one from one array to another Note how it watches for the string terminator and how it adds one to the destination string Remember, strcpy cannot determine the size of the destination array and you should be careful not to copy a string which is too big to it

25 Assigning Strings A lot of students tell me this works – name = “Fred”; /* wrong, wrong, wrong !! */ – What it does is copy the address of the first letter of “Fred” to the variable name – Now, the compiler stores “Fred” in a temporary location, which can be reused at any time – So, for a while it might seem to work, but it’s a disaster waiting to happen

26 strlen This is another commonly used function which returns the length of a string It returns all of the characters before the string terminator char address[20]; int len; strcpy(address, “21 Main St.”); len = strlen(address); printf(“The length is %d\n”, len);/* prints 11 */

27 strcmp We cannot compare strings with the relational operators – if(“dog” > “cat”)/* wrong ! */ To compare strings we use strcmp – int strcmp(char first[], char second[]) Which returns – <0 if first is smaller than second – 0 if first equals second – >0 if first is larger than second

28 strcmp So, what do we mean by larger and smaller It is almost the same as alphabetical order but is based on the ASCII table rather than just the 26 letters in the alphabet Therefore – ‘A’ < ‘a’ – ‘1’ < ‘A’ – ‘0’ < ‘1’ – ‘A’ < ‘B’ – ‘a’ < ‘b’ * See stringfuncdemo.c

29 String Input and Output You could write a function to output a string like this void printString(char s[]) { int i; for(I = 0; s[i] != ‘\0’; i++) printf(“%c”, s[i]); }

30 String Input and Output But this capability is builtin to printf – printf(“%s\n”, “Hello, World!”); As with the other format specifications, you can control the width of the field You can also control the maximum number of characters which will be printed using a decimal notation

31 String Input and Output The following prints a maximum of 10 characters, right justified is a field 15 characters wide – printf(“%-15.10s”, mystring); The %s format can also be used with scanf with the following caveats – You do not need an & in front of the array which will receive the string – It will read text until it finds whitespace and stop

32 String Input and Output For example char name[31]; printf(“Enter your name: “); scanf(“%s”, name); There is another notation that lets you specify a list of valid characters and stop reading when any other character is found

33 String Input and Output The following will read Y or N in either case – scanf(“%[yYnN]”, answer); This will read any string containing alphabetic characters and the space – scanf(“%[ a-zA-Z]”, name); The ^ symbol indicates everything except the characters shown The following will read everthing until the end of line – scanf(“%[^\n]”, line);

34 String Input and Output You can also indicate a maximum field width so that it will not read more data than your string can hold – scanf(“%30[^\n]”, name); – This will not read more than 30 characters To read an entire line and discard the newline – scanf(“%[^\n]%*c”, line); – This action is also done by the function gets() – gets() will work with an empty line whereas the scanf will not

35 Reading a Line All of the library functions have drawbacks – Can overflow the buffer – Do not all handle empty lines the same Therefore, let’s write our own void get_a_line(char line[], int max) { int n = 0; char c; while(‘\n’ != (c = getchar())) { if(n < max) line[n++] = c; } line[n] = ‘\0’; }

36 2-D Arrays So far, the arrays we have seen look like lists We can also have arrays which look like tables Rather than just having a position for each value, they have a row and column for each value

37 2-D Arrays ill\0B hristine C arlene D om T lice A char names[5][11]; rows columns

38 2-D Arrays You can subscript a 2-D array by specifying the row and column numbers – names[0][3]/* c */ One of the common uses of 2-D arrays is to store arrays of strings This is just like an array of integers, except each member of the array is a complete string

39 2-D Arrays One of the differences between a 1-D array and a 2-D array is how it is passed to a function – void somefunc(char names[][11]); – When passed as a parameter, you must indicate the number of columns in the array Another useful technique is that you can treat each row in the array as if it was a string

40 Arrays of Strings Accessing a string in a 2-D array involves a trick – When you subscript a 2-D array with only 1 subscript, it accesses an entire row – Thus, if we use names[1], it accesses the name “Bill” To read into a row in our 2-D array – gets(names[i]); * See string_sorter.c