Passing 1D arrays to functions.



Similar documents
Basics of I/O Streams and File I/O

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

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

Answers to Review Questions Chapter 7

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

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

Member Functions of the istream Class

C++ Input/Output: Streams

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

Common Beginner C++ Programming Mistakes

Introduction to Java

13 Classes & Objects with Constructors/Destructors

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

Comp151. Definitions & Declarations

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

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

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

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Chapter One Introduction to Programming

Data Structures using OOP C++ Lecture 1

While Loop. 6. Iteration

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

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

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Moving from C++ to VBA

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

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

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

Compiler Construction

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

7.7 Case Study: Calculating Depreciation

Appendix K Introduction to Microsoft Visual C++ 6.0

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

6. Control Structures

Stacks. Linear data structures

C++FA 5.1 PRACTICE MID-TERM EXAM

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Chapter 8 Selection 8-1

Variables, Constants, and Data Types

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

1. The First Visual C++ Program

5 Arrays and Pointers

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

VB.NET Programming Fundamentals

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

F ahrenheit = 9 Celsius + 32

Computer Programming C++ Classes and Objects 15 th Lecture

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

Java Interview Questions and Answers

Lecture 5: Java Fundamentals III

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:

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Arrays in Java. Working with Arrays

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

Conditions & Boolean Expressions

CS106A, Stanford Handout #38. Strings and Chars

Chapter 5 Functions. Introducing Functions

Sequential Program Execution

C++ Language Tutorial

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

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

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

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

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

Illustration 1: Diagram of program function and data flow

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 2 Introduction to Java programming

Lecture 22: C Programming 4 Embedded Systems

JavaScript: Control Statements I

UEE1302 (1102) F10 Introduction to Computers and Programming

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

Chapter 5. Selection 5-1

Lecture 2 Notes: Flow of Control

Chapter 2: Elements of Java

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

C++ INTERVIEW QUESTIONS

Building Java Programs

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

Common Data Structures

COMPUTER SCIENCE 1999 (Delhi Board)

Unit 6. Loop statements

Programming Languages CIS 443

The if Statement and Practice Problems

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

The While Loop. Objectives. Textbook. WHILE Loops

Informatica e Sistemi in Tempo Reale

1 Description of The Simpletron

Ch 7-1. Object-Oriented Programming and Classes

Introduction to Data Structures

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

Fondamenti di C++ - Cay Horstmann 1

Syllabus OBJECT ORIENTED PROGRAMMING C++

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

Pemrograman Dasar. Basic Elements Of Java

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Formatting Numbers with C++ Output Streams

Transcription:

Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function, when an array is the formal parameter, is the base address of the array (the memory address of the first element in the array). This is true whether the array has one or more dimensions. When declaring a 1-D array parameter, the compiler only needs to know that the parameter is an array; it doesn t need to know its size. The complier will ignore it, if it is included. However, inside the function we still need to make sure that only legitimate array elements are referenced. Thus a separate parameter specifying the length of the array must also be passed to the function. int ProcessValues (int [], int ); // works with ANY 1-d array Example: int SumValues (int [], int ); //function prototype void main( ) int Array[10]=0,1,2,3,4,5,6,7,8,9; int total_sum; total_sum = SumValues (Array, 10); //function call cout << Total sum is <<total_sum; int SumValues (int values[], int num_of_values) //function header int sum = 0; for( int i=0; i < num_of_values; i++) sum+=values[i]; return sum; Note that we are using only the name of the array in the function call: Array, not Array[10]. 1

Since arrays are always passed by reference, all changes made to the array elements inside the function will be made to the original array. The only way to protect the elements of the array from being inadvertently changed, is to declare an array to be a const parameter. Example: int SumValues (const int [], int); //function prototype int main( ) const int length =10; int Array[10]=0,1,2,3,4,5,6,7,8,9; int total_sum; total_sum = SumValues (Array, length); cout << Total sum is <<total_sum; return 0; //function call int SumValues (const int values[], int num_of_values) //function header int sum = 0; for( int i=0; i < num_of_values; i++) sum+=values[i]; return sum; Since you do not intend to change the values of an array in the above function, make it a const parameter to protect yourself. The original array (in the main) should not be const, or you wouldn t be able to make any changes to it at all. You do not however need to make the length of an array a const parameter, since it is passed by value and any changes to it will not affect the actual parameter. The compiler will not allow you to pass it by reference if it was declared as a const int in the main ( ). 2

Passing arrays to functions (examples) 4/9/04 Passing arrays to functions (Examples). //example of passing one-dimensional array to functions int maximum_1_d (int[ ], int); void main() const int size = 5; int nums[size] = 2,18,1,25,3; // 1-D array cout << "The max value of array nums is " << maximum_1_d(nums, size) << endl; int maximum_1_d ( int vals[ ], int number_elements) int i, max = vals[0]; for (i=0; i<number_elements; i++) if (max <vals[i]) max = vals[i]; return max; 1

Passing arrays to functions (examples) 4/9/04 // The called function receives access to the actual array, not a copy of the values in the // array. Thus any changes made to the array within the function change the original // array. void change_1_d(int[], int); // function prototype void main() const int size = 5; int i; int nums[size] = 2,18,1,25,3; cout << "The values in array nums before the functions call are "; for (i=0; i<size;i++) cout<<nums[i]<<' '; cout<<endl; change_1_d(nums,size); //function call cout << "The values in array nums after the functions call are "; for (i=0; i<size;i++) cout<<nums[i]<<' '; cout<<endl; void change_1_d(int vals[], int number_elements) //function header int i; // let's try to change the values in vals for (i=0;i<number_elements; i++) vals[i]=i; 2

1D Arrays Code example: passing arrays to functions void get_array(int[], int); int calc_sum(int[], int); void display_array(int[], int); void main () int num[1000]; int n; cout << "Enter size of array (must be < 1000):"; cin >> n; int sum; get_array(num, n); cout << endl; display_array(num, n); cout << endl; sum = calc_sum(num, n); cout << "The sum is " << sum << endl; void get_array(int arr[], int size) for (int k = 0; k < size; k++) cout << "Please enter value for arr[" << k << "]:"; cin >> arr[k]; int calc_sum(int arr[], int size) int s = 0; for (int i = 0; i < size; i++) s += arr[i]; return s; void display_array(int arr[], int size) for(int j = 0; j < size; j++) cout << "arr[" << j << "] = " << arr[j] << endl;

1 Strings A string literal (or string) is any sequence of characters enclosed in double quotes. In C++ strings of characters are held as an array of characters, one character held in each array element. A special null character, represented by `\0', is appended to the end of the string to indicate the end of the string. Think of it as a sentinel that marks the end of every string. If a string has n characters then it requires an n+1 element array (at least) to store it. Note: \0 is stored by the compiler as a single character. A single character enclosed in double quotes, rather than single quotes, is also viewed by the compiler as a string. Character in single quotes - `a'- is stored in a single byte. Character in double quotes -"a" is stored in two consecutive bytes holding the character `a' and the null character. Examples of strings: o This is a string o xyz 123 *!#@@& o m o A string variable s1 could be declared as follows: char s1[10]; The string variable s1 could hold strings of length up to nine (only 9!!!) characters since space is needed for the final null character. Strings can be initialized at the time of declaration just as other variables are initialized. For example: char s1[] = "example"; char s2[20] = "another example" would store the two strings as follows: s1 e x a m p l e \0 s2 a n o t h e r e x a m p l e \0???? In the first case the array would be allocated space for eight characters, that is space for the seven characters of the string and the null character. In the second case the string is set by the declaration to be twenty characters long but only sixteen of these characters are set, i.e. the fifteen characters of the string and the null character. Note that the length of a string does not include the terminating null character.

2 Note: The individual characters in the string can be handled with standard array operations More examples of String Initialization Each of the following declarations produces the same result: char test[5] = abcd ; char test[ ] = abcd ; char test[5] = a, b, c, d, \0 ; char test[ ] = a, b, c, d, \0 ; String Output: A string is output by sending it to an output stream, for example: cout << "The string s1 is " << s1 << endl; would print The string s1 is example String Input (single word) When the input stream cin is used, space characters, newline etc. are used as separators and terminators. Thus when inputting numeric data cin skips over any leading spaces and terminates reading a value when it finds a white-space character (space, tab, newline etc. ). This same system is used for the input of strings, hence a string to be input cannot start with leading spaces, also if it has a space character in the middle then input will be terminated on that space character. The null character will be appended to the end of the string in the character array by the stream functions. If the string s1 was initialized char s1[] = "example"; then the statement cin << s1; would set the string s1 as follows when the string "first" is entered (without the double quotes) f i r s t \0 e \0 Note that the last two elements are a relic of the initialization at declaration time.

3 Note: If the string that is entered is longer than the space available for it in the character array then C++ will just write over whatever space comes next in memory. This can cause some very strange errors when some of your other variables reside in that space! String Input (several words, i.e. strings that contain spaces) To read a string with several words in it we can call cin once for each word. A better way is to use cin.getline( ) or cin.get( ) cin.getline( ) continuously accepts and stores characters typed at the terminal into the character array until either the array size is reached or the end-of-string(null, \0) marker is detected. (Note: \n is input when the Enter key is depressed. This character is interpreted by cin.getline( ) as the end-of-line entry. cin.getline( ) inserts the \0 character in place of the \n character at the end of the array.). whereas cin reads entry up to the first blank space or \n, cin.getline( ) accepts whitespace as a character and terminates with \n (or until the array if full). syntax: o cin.getline(string, terminating-length, terminating-character) string a string or character pointer variable terminating-length an integer constant or variable indicating the maximum number of input characters that can be input terminating-character an optional character constant or variable specifying the terminating character if omitted, the default terminating character is the newline ( \n ) character Examples: cin.getline(message, size); cin.getline(message, size, \n ); cin.getline(message, size, x ); the first two functions stop reading characters when the Return key is pressed or until size characters have been read, whichever comes first. The third function continues until size or the character x have been read. cin.get( ) reads in a single character at a time. Will read any character. if you need to read the ENTER key, a space, or the tab key, you cannot use cin. These characters stop cin from reading!!! You must use cin.get because cin.get will read any character. Example: char c1; cin.get(c1) - reads a single character into variable c1

Character Arrays and Strings: Worksheet 2 1. What is the difference between character arrays and strings? 2. char my_word[5] = c, l, a, s, s ; a. Is it a character array or a string? Why? b. How can you display it to the screen? 3. char my_word[6] = c, l, a, s, s, \0 ; a. Is it a character array or a string? Why? b. How can you display it to the screen? 4. Given the following declaration: char hello[3] = hi ; a. What is hello[0] = b. What is hello[2] = c. What is hello[3] = d. Adding the following lines: hello[1] = m ; cout << hello; What is displayed on a screen?

5. Write a code segment that will prompt the user for his first name and his last name and display to the screen: Hello, first_name last_name. 6. Write a function that will accept two strings and return true if they are equal in length and false if they are not. 7. Write a function that will accept an integer array, its size and a code integer. The function should find the location of that code integer in the array and return it s position (index) in the array or 999 if the code was not found in the array.

1D Arrays Code example: manipulating strings int calc_length(char w[]); bool compare_words(char w1[], char w2[]); void main () char word1[81], word2[81]; int word_length1, word_length2; cout << "Enter word 1 (max 80 chars): "; cin >> word; cout << "Enter word 2 (max 80 chars): "; cin >> word; word_length1 = calc_length(word1); word_length2 = calc_length(word2); cout << "Length of word 1 is " << word_length1; cout << "Length of word 2 is " << word_length2; if (compare_words(word1, word2)) cout << "Words are the same"; else cout << "Words are not the same ; cout << endl; int calc_length(char w[]) int len; // continue looping until we bump into the null char for (len = 0; w[len]!= '\0'; len++); return len; bool compare_words(char w1[], char w2[]) int i; // continue looping as long as chars are equal and not null for (i = 0; w1[i]!= '\0' && w2[i]!= '\0' && w1[i] == w2[i]; i++); // the only way that identical words can end the loop is // by both having a null char at the same time: any other // combination means that they are not identical return (w1[i] == '\0' && w2[i] == '\0');