Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Similar documents
Answers to Review Questions Chapter 7

13 Classes & Objects with Constructors/Destructors

C++FA 5.1 PRACTICE MID-TERM EXAM

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Goals for This Lecture:

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Passing 1D arrays to functions.

Data Structures using OOP C++ Lecture 1

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Computer Programming C++ Classes and Objects 15 th Lecture

Arrays in Java. Working with Arrays

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Comp151. Definitions & Declarations

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

COMPUTER SCIENCE 1999 (Delhi Board)

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Sources: On the Web: Slides will be available on:

Moving from C++ to VBA

Chapter One Introduction to Programming

Chapter 5 Functions. Introducing Functions

While Loop. 6. Iteration

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Member Functions of the istream Class

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Illustration 1: Diagram of program function and data flow

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Introduction to Java

C++ INTERVIEW QUESTIONS

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

arrays C Programming Language - Arrays

Basics of I/O Streams and File I/O

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

An Incomplete C++ Primer. University of Wyoming MA 5310

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Binary storage of graphs and related data

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Compiler Construction

C++FA 3.1 OPTIMIZING C++

Common Beginner C++ Programming Mistakes

CISC 181 Project 3 Designing Classes for Bank Accounts

7.7 Case Study: Calculating Depreciation

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Tutorial on C Language Programming

AP Computer Science Java Subset

The C Programming Language course syllabus associate level

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Object Oriented Software Design II

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

N3458: Simple Database Integration in C++11

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Formatting Numbers with C++ Output Streams

Java Interview Questions and Answers

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

C++ Programming Language

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

5 Arrays and Pointers

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

In this Chapter you ll learn:

C++ Essentials. Sharam Hekmat PragSoft Corporation

6. Control Structures

Stacks. Linear data structures

C++ Input/Output: Streams

COSC 181 Foundations of Computer Programming. Class 6

J a v a Quiz (Unit 3, Test 0 Practice)

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 9 Text Files User Defined Data Types User Defined Header Files

Basics of C++ and object orientation in OpenFOAM

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Moving from CS 61A Scheme to CS 61B Java

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Example of a Java program

Project 2: Bejeweled

Class 16: Function Parameters and Polymorphism

El Dorado Union High School District Educational Services

Ch 7-1. Object-Oriented Programming and Classes

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

C Interview Questions

Note: Syntactically, a ; is needed at the end of a struct definition.

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Programming Languages CIS 443

Learning Computer Programming using e-learning as a tool. A Thesis. Submitted to the Department of Computer Science and Engineering.

Sequential Program Execution

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

The While Loop. Objectives. Textbook. WHILE Loops

Advanced Bash Scripting. Joshua Malone

Lesson 10: Video-Out Interface

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

Functions and Parameter Passing

Statements and Control Flow

EP241 Computer Programming

Transcription:

Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection of stdin and stdout TNCG18 (C++): Lec 3 1 Arrays Name of array int c[12]; Consecutive group of memory locations of the same type. To refer to an element (e.g. 3 rd ) c[2] First element at position 0 ith element at position i-1 c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] -45 6 0 72 1543-89 0 62-3 1 6453 78 Position number of the element within array c TNCG18 (C++): Lec 3 2 Lec 3 Programming in C++ 1

Arrays Array elements like other variables Assignment and printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ] << endl; Can perform operations inside subscript c[ 5 2 ] same as c[3] TNCG18 (C++): Lec 3 3 Declaring Arrays When declaring arrays, specify type arrayname[ arraysize ]; int c[10]; // array of 10 integers float d[3284]; // array of 3284 floats The array size can be defined as a constant const int arraysize = 10; int c[ arraysize ]; See Fig04_06.cpp Declaring multiple arrays of same type Use comma separated list, like regular variables int b[ 100 ], x[ 27 ]; TNCG18 (C++): Lec 3 4 Lec 3 Programming in C++ 2

Initializing Arrays With a loop See Fig04_03.cpp, Fig04_05.cpp Initializer list See Fig04_04.cpp Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; int v[ 100 ] = {0}; If too many initializers then syntax error If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array TNCG18 (C++): Lec 3 5 Defining Array Size Can be specified with constant variable const int size = 20; char v[size]; Constants cannot be changed Constants must be initialized when declared Also called read-only variables See Fig04_08.cpp Fig04_07.cpp TNCG18 (C++): Lec 3 6 Lec 3 Programming in C++ 3

Examples Histogram SeeFig04_10.cpp Throwing a dice and counting frequencies SeeFig04_11.cpp Listing student grades frequencies See Fig04_09.cpp Compute mean, median, and mode See Fig04_17.cpp TNCG18 (C++): Lec 3 7 Arrays in C++ No range checking The array does not know its size Cannot input or output an array directly, except strings Comparison and assignment not implemented TNCG18 (C++): Lec 3 8 Lec 3 Programming in C++ 4

C strings Character Arrays Arrays of characters All C strings end with null ('\0') char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0 }; char string1[] = "hello"; Null character implicitly added string1 has 6 elements Subscripting string1[0] is 'h string1[2] is 'l' TNCG18 (C++): Lec 3 9 Character Arrays Input from keyboard See Fig04_12.cpp char string2[ 10 ]; cin >> string2; Reads user input in string2 Stops at first white space character Adds null character If too much text entered, data written beyond array #include <iomanip> char string3[ 5 ]; cin >> setw(5) >> string3; Reads at most 4 chars and last array position is for the null TNCG18 (C++): Lec 3 10 Lec 3 Programming in C++ 5

Printing strings Character Arrays cout << string2 << endl; Does not work for other array types Characters printed until null character found TNCG18 (C++): Lec 3 11 Passing Arrays to Functions Function prototype void modifyarray( int b[], int arraysize ); void modifyarray( int [], int); No need for array size between brackets Ignored by compiler Array parameter as const Array values cannot be modified (compiler error) void donotmodify( const int [] ); See Fig04_15.cpp TNCG18 (C++): Lec 3 12 Lec 3 Programming in C++ 6

Calling Functions with Array Arguments Call function modifyarray To pass array myarray to modifyarray int myarray[24]; modifyarray(myarray, 24); Array size is usually an argument Not required Useful to iterate over all elements TNCG18 (C++): Lec 3 13 Passing Arrays to Functions Arrays passed-by-reference Functions can modify original array data The array s name is address of first element Function knows where the array is stored Can change original memory locations Individual array elements passed-by-value Like regular variables square(myarray[3]); See Fig04_14.cpp TNCG18 (C++): Lec 3 14 Lec 3 Programming in C++ 7

Default Arguments Function prototype void modifyarray( int b[], int arraysize = 100); Function call int v[100]; modifyarray(v); //modifyarray(v, 100); Default value modifyarray(myarray, 24); TNCG18 (C++): Lec 3 15 Static Local Arrays If static, local variables are saved between function calls Visible only in function body Used for performance reasons Can declare local arrays to be static Initialized to zero by default static int array[3]; If not static See Fig04_13.cpp Created (and destroyed) in every function call TNCG18 (C++): Lec 3 16 Lec 3 Programming in C++ 8

Multiple-Subscripted Arrays Multiple subscripts a[ i ][ j ] int a[ 3 ][ 4 ]; Tables with rows and columns Specify row, then column Array of arrays a[0] is an array of 4 elements a[0][0] is the first element of that array Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Column subscript Array name Row subscript TNCG18 (C++): Lec 3 17 Multiple-Subscripted Arrays To initialize Initializers grouped by row in braces int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Row 0 Row 1 1 2 3 4 int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 0 3 4 TNCG18 (C++): Lec 3 18 Lec 3 Programming in C++ 9

Multiple-Subscripted Arrays Access to an element 1 0 cout << b[0][1]; 3 4 Outputs 0 Cannot access an element using commas cout << b[0, 1]; Syntax error!!! See Fig04_22.cpp See Fig04_23.cpp Function prototypes Must specify sizes of subscripts First subscript not necessary, as with singlescripted arrays void printarray( int [][2], int size ); TNCG18 (C++): Lec 3 19 StructureType in C++ struct is used to contain data of different types struct Card { int value; char suit [10]; //field, member }; Card ace = {13, Hearts }; // initialization Size (i.e. number of bytes)? sizeof(ace). TNCG18 (C++): Lec 3 20 Lec 3 Programming in C++ 10

Structure Type How do you write in C? typedef struct { int value; // char suit [10]; } Card; Card ace = {13, Hearts }; TNCG18 (C++): Lec 3 21 Operations on structs Memberwise assignment ace.value = 1; Assignment is allowed Card ace2 = ace; Yes, array fields get copied without need to copy each field at a time!!! But surprise!!!, //doesn t compile ace2.suit = ace.suit; #include<cstring> //instead use a string copy function strcpy(ace2.suit, ace2.suit); TNCG18 (C++): Lec 3 22 Lec 3 Programming in C++ 11

Operations on structs Comparison, input, and output are not available if (ace2 == ace)... //does not work cin >> ace2; //does not work Implement your own functions Overload operators ==, >> and << See Fig06_01.cpp TNCG18 (C++): Lec 3 23 Using Structures as Function Arguments Pass the structure argument by value void printcard(card c){ cout << Value: << c.value << Suit: << c.suit << endl; } Pass an array by value to a function Create a structure with the array as a member See struct1.cpp TNCG18 (C++): Lec 3 24 Lec 3 Programming in C++ 12

Using Structures as Function Arguments Pass the structure argument by reference void printcard(const Card &c){ cout << Value: << c.value << Suit: << c.suit << endl; } Pass-by-reference more efficient TNCG18 (C++): Lec 3 25 Inline Functions inline double cube(const double side) { return side * side * side; } int main() { double val; cin >> val; cout << Cube volume: << cube(val) << endl; } return 0; TNCG18 (C++): Lec 3 26 Lec 3 Programming in C++ 13

Inline Functions Function call replaced by functions code Only used for small functions Compiler is free to ignore the inline qualifier Advantage Efficiency: avoid function call overhead Disadvantages Changes in a inline function require that whole project to be recompiled Program size increases TNCG18 (C++): Lec 3 27 Reading a Sequence of Values cin >> k returns 0 when EOF is found or a value of the wrong type is given int main(){ int k, sum = 0; while (cin >> k) sum += k; cout << sum << endl; return 0; } See sum.cpp TNCG18 (C++): Lec 3 28 Lec 3 Programming in C++ 14

Reading Variables int k; cin >> k; cout << k; Prints any trash in k, if user gives a non-integer value. int k; if (cin >> k) cout << k; No problem!!! TNCG18 (C++): Lec 3 29 Redirection of input and output Redirection of input (DOS and Unix) sum < input.txt reads sequence of ints from file input.txt Redirection of output sum > output.txt writes the result to file output.txt Piping (DOS and Unix) dice sum output of dice.exe is redirected as input to sum.exe TNCG18 (C++): Lec 3 30 Lec 3 Programming in C++ 15