Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)

Slides:



Advertisements
Similar presentations
Lecture 20 Arrays and Strings
Advertisements

Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
Arrays Chapter 6.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
1 Lecture 22 Chapter 12 Arrays Dale/Weems/Headington.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
 2006 Pearson Education, Inc. All rights reserved Arrays.
CECS 121 EXAM 2.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data type.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Chapter 8 Arrays and Strings
Arrays- Part 2 Spring 2013Programming and Data Structure1.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Pointers *, &, array similarities, functions, sizeof.
Arrays and Strings Lecture 30. Summary of Previous Lecture In the previous lecture we have covered  Functions Prototypes Variable Scope  Pointers Introduction.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Arrays.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Arrays An array is an indexed data structure which is used to store data elements of the same data type. An array is an indexed data structure which is.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Arrays Chapter 12. One-Dimensional Arrays If you wanted to read in 1000 ints and print them in reverse order, it would take a program that’s over 3000.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
1 Multidimensional Arrays Chapter 13 2 The plural of mongoose starts with a "p" Initializing a multidimensional array Processing by.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
C Programming Lecture 15 Two Dimensional Arrays. Two-Dimensional Arrays b The C language allows arrays of any type, including arrays of arrays. With two.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Module 2 Arrays and strings – example programs.
C++ Data Types Simple Structured Address Integral Floating
EKT150 : Computer Programming
Beginning C for Engineers
Arrays Arrays A few types Structures of related data items
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Presentation transcript:

Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)

Homework Read Chapter 6 Read Chapter 6 The project has been posted. The project has been posted. HW5 is due next week and helps you start the project. HW5 is due next week and helps you start the project. Exam Study (Question and Answer) Session for both Sections: Exam Study (Question and Answer) Session for both Sections: Monday October 10 in DCC 330 starting at 8pm Monday October 10 in DCC 330 starting at 8pm

Declare variables to store and add 3 temperatures int temp1, temp2, temp3; int total; temp2temp1temp3 scanf(“%d %d %d”, &temp1, &temp3, &temp3); total = temp1 + temp2 + temp3; 4006 total

What if you wanted to store and total 1000 temperatures? int temps[ 1000 ] ; int temps[ 1000 ] ; /*declares an array of 1000 int values */ /*declares an array of 1000 int values */ temp[0] temp[1] temp[2].... temp[999]

Array Definition An array is a structured collection of components (called array elements), all of the same data type, given a single name, and stored in adjacent memory locations. The individual components are accessed by using the array name together with an integer valued index in square brackets. The index indicates the position of the component within the collection (starts at 0, not 1).

Another Example Declare an array called which will hold up to 5 test scores. Declare an array called scores which will hold up to 5 test scores. float scores[5]; /* declaration allocates memory */ scores[0] scores[1] scores[2] scores[3] scores[4] number of elements in the array indexes or subscripts Base Address

Assigning Values to Individual Array Elements float temps[ 5 ] ; /* allocates memory for array */ int m = 4 ; temps[ 2 ] = 98.6 ; temps[ 3 ] = ; temps[ 0 ] = 99.4 ; temps[ m ] = temps[ 3 ] / 2.0 ; temps[ 1 ] = temps[ 3 ] ; /* what value is assigned?*/ temps[0] temps[1] temps[2] temps[3] temps[4] ?

What values are assigned? float temps[ 5 ] ; /* allocates memory for array */ int m ; for (m = 0; m < 5; m++) { temps[ m ] = m  0.2 ; temps[ m ] = m  0.2 ;} temps[0] temps[1] temps[2] temps[3] temps[4] ? ? ? ? ?

Now what values are printed? float temps[ 5 ] ; /* allocates memory for array */ int m ; for (m = 4; m >= 0; m-- ) { printf(“%f\n”, temps[ m ]); printf(“%f\n”, temps[ m ]);} temps[0] temps[1] temps[2] temps[3] temps[4]

Initializing in a Declaration int ages[ 5 ] = { 40, 13, 20, 19, 36 } ; int m; for ( m = 0; m < 5; m++ ) { printf( “%f\n”, ages[ m ]) ; printf( “%f\n”, ages[ m ]) ;} ages[0] ages[1] ages[2] ages[3] ages[4]

Copying Arrays You assign arrays with = You cannot assign arrays with = int mylist[100], yourlist[100]; … mylist = yourlist; /* WRONG! */ Instead, you must copy each element: Instead, you must copy each element: for (i = 0; i < 100; i++) mylist[i] = yourlist[i];

Character strings represented as char Arrays char name[10] = “Bettina”; // allocates 10 chars A character string always ends with a ‘\0’ (the null character, a byte with all 0’s) Therefore you can only store 9 chars + ‘\0’ in a 10 character array. ‘B’‘e’‘t’‘t’‘i’‘n’‘a’‘\0’

Assigning Values to Character Strings #include Assigning Values to Character Strings #include You can initialize a string with = when you declare it You can initialize a string with = when you declare it char name[10] = “Bettina”; You cannot assign a string with = after it’s been declared You cannot assign a string with = after it’s been declared name = “Bettina”;/* WRONG! */ Instead, use the function to copy a value to a variable. strcpy (variable, value); Instead, use the strcpy function to copy a value to a variable. strcpy (variable, value); strcpy(name, “Bettina”);

char name[10]; Assignment - Use strcpy(dest, source); strcpy(name, “Bettina”); /*Note: Can’t use name = “Bettina”; */ Comparing - Use strcmp(name, “Bettina”); /* Can’t use == */ - strcmp returns 0 if name == “Bettina” - something less than 0 if name is less than “Bettina”, and something greater than 0 if name is greater than “Bettina”. (alphabetical order & cap letters are greater than lower case) Concatenating - Use strcat(str1, str2); - combines two strings so new string is str1 followed by str2 strcat(name, “ Schimanski”); /* name is now “Bettina Schimanski” */ More Operations on Character Strings #include More Operations on Character Strings #include

Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information as arguments: the array itself the array itself the number of elements to process in the array the number of elements to process in the array

Passing Arrays as Arguments Normally, if you change the value of a parameter in a function it doesn’t affect the argument. () Normally, if you change the value of a parameter in a function it doesn’t affect the argument. (pass by value) Ex: int main( ) {… fun(x); fun(x);…} However, in C, are, so changes made to the parameter array are reflected in the argument However, in C, arrays are passed by reference, so changes made to the parameter array are reflected in the argument int main( ) {int x[5]; fun(x, 5); fun(x, 5);…} void fun(int a) { /* doesn’t change x */ a = 10; } void fun(int y[ ], int size) { /* changes x in main */ y[1] = 10; }

/* Get num integers into myarray */ void Read ( int myarray[ ], int num) { int i; for (i = 0; i < num; i++) { printf( “Enter a number: “); scanf(“%d”, &myarray[i]); } This changes the elements in the array, so that the changes are seen when you use the array in main or other functions (even though the function Read does not return anything) Example with Array Parameters

Function Calls with Arrays You only need to pass it the name of the array. You don’t use square brackets. int myarray[100]; Read(myarray, 100); No [ ] needed

More about Array Index it is the programmer’s responsibility to make sure that an array index does not go out of bounds. The index must be within the range 0 through the declared array size minus one. (i.e. int myarray[10] - index must be in range 0 – 9) using an index value outside this range causes the program to access memory locations outside the array. The index value determines which memory location is used.

Two-Dimensional Array is a collection of components, all of the same type, structured in two dimensions, (referred to as rows and columns). Individual components are accessed by a pair of indexes representing the component’s position in each dimension. DataType ArrayName [ConstIntExpr] [ConstIntExpr] ; SYNTAX FOR ARRAY DECLARATION

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] row 2, col 7 might be Arizona’s high for August Must be const or use integers directly -- To keep monthly high temperatures for all 50 states in one array. EXAMPLE -- To keep monthly high temperatures for all 50 states in one array. const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; … int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; [ 0 ] [ 0 ] [ 1 ] [ 1 ] [ 2 ] [ 2 ]... [ 48 ] [ 48 ] [ 49 ] [ 49 ] stateHighs[2][7]

Looping through a 2-D array: Use Nested loops The outer loop should be the rows, the inner loop the columns The outer loop should be the rows, the inner loop the columns const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; … int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; for (rows = 0; rows < NUM_STATES; rows++) for (cols = 0; cols < NUM_MONTHS; cols++) scanf (“%d”, &stateHighs[rows][cols]);

Consider the following input with the number of votes received by three candidates District Candidate A Candidate B Candidate C How would you read them in to an array called votes? const int num_districts = const int num_candidates = int votes [ num_districts ] [ num_candidates ] ; for (rows = 0; rows < num_districts; rows++) for (cols = 0; cols < num_candidates; cols++) scanf (“%d”, &votes[rows][cols]); 4; 3;

Summing rows and columns const int num_districts = 4; const int num_candidates = 3; int votes[num_districts][num_candidates]; … /* Sum district votes for one state */ int districtSums[num_districts]; for (d = 0; d < num_districts; d++) { districtSums[d] = 0; for (c = 0; c < num_candidates; c++) districtSums[d] += votes[d][c]; }

Summing rows and columns (cont.) const int num_districts = 4; const int num_candidates = 3; int votes[num_districts][num_candidates]; … /* Sum candidate votes for one state */ int candidateSums[num_candidates]; for (c = 0; c < num_candidates; c++) { candidateSums[c] = 0; for (d = 0; d< num_districts; d++) candidateSums[c] += votes[d][c]; }

Arrays as Parameters just as with a one-dimensional array, when a two- (or higher) dimensional array is passed as an argument, any changes made to the array in the function are reflected in main (or wherever the function was called from) just as with a one-dimensional array, when a two- (or higher) dimensional array is passed as an argument, any changes made to the array in the function are reflected in main (or wherever the function was called from) the in the function heading and prototype the size of all dimensions except the first must be included in the function heading and prototype the sizes of those dimensions in the function’s parameter list must be exactly the same as declared for the caller’s array the sizes of those dimensions in the function’s parameter list must be exactly the same as declared for the caller’s array

void clearArray (int stateHighs [ ] [ NUM_MONTHS] ) /* Clears the array for high temps, setting all values to 0 */{ int state; int state; int month; int month; int total; int total; for ( state = 0 ; state < NUM_STATES; state++ ) for ( state = 0 ; state < NUM_STATES; state++ ) { for (month = 0 ; month < NUM_MONTHS ; month++) for (month = 0 ; month < NUM_MONTHS ; month++) stateHighs[state][month] = 0; }} /* NUM_MONTHS and NUM_STATES were declared as global variables */

Labs and the Project Today’s Lab, as usual, is due by 11:59pm tomorrow if not finished in class today Today’s Lab, as usual, is due by 11:59pm tomorrow if not finished in class today HW 5 (start project) HW 5 (start project) Already posted on the web Already posted on the web