CS 1430: Programming in C++ 1. Test 2 Friday Functions Arrays For Loops Understand Concepts and Rules Memorize Concepts and Rules Apply Concepts and Rules.

Slides:



Advertisements
Similar presentations
Array. Convert Numbers in Different Base Systems Generate values to a series of numbers in different base systems: Base is between 2 and 9; Maximum number.
Advertisements

Student Data Score First Name Last Name ID GPA DOB Phone... How to store student data in our programs? 1.
Functions 1. Example: Power, Square Root and Absolute values of a number #include … float num; float power, squareRoot, absolute; cout
1 C++ Functions. // The function computes and returns the gross pay // based on the pay rate and hours. Hours over // 40 will be paid 1.5 times the regular.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Functions g g Data Flow g Scope local global part 4 part 4.
1 Principles of Programming I Note Set #12. 2 Semester Overview Functions Character File I/O Arrays Pointers and Dynamic Memory Allocation Characters.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 CS 1430: Programming in C++. 2 Input: Input ends with -1 Sentinel-Controlled Loop Input: Input begins with.
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Organizing Heterogeneous Data Arrays allow a programmer to organize lists of values that are all of the same type (homogeneous). But we are often faced.
Review Binary Numbers Bit : 0 or 1 Byte: 8 bites 256 different values 2 8 KB : 1024 bytes 2 10 bytes MB : 1024 * 1024 bytes 2 10 * 2 10 (2 20 ) bytes GB.
Defining a 2d Array A 2d array implements a MATRIX. Example: #define NUMROWS 5 #define NUMCOLS 10 int arr[NUMROWS][NUMCOLS];
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Quiz // // The function exchanges the two parameters. // Param: ( ) // Param:
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Review for Final Exam. Contents 5 questions (20 points each) + 1 bonus question (20 points) – Basic concepts in Chapters 1-4 – Chapters 5-9 – Bonus: Chapter.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
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.
1 CS 1430: Programming in C++. 2 Find Max, Min, Average of m Sections Max, Min and Average of each section Max, Min and Average of all sections together.
1 CS 1430: Programming in C++. Quiz Functions Function Prototype float sqrt(float x); Function name, type, parameter and parameter type Function.
1 CS 1430: Programming in C++. 2 C++ Loops Sentinel Controlled Count Controlled EOF Controlled.
Data Types Storage Size Domain of all possible values Operations 1.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Arrays.
CS 1430: Programming in C++ Function Design 1. Good Functions Focusing on one thing Function name tells what it does sqrt(val) pow(base, exp) cin.eof()
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
Class Method Read class Student { private: string id; string firstName, lastName; float gpa; public: // Will the method change any data members? // Yes!
1 Functions Function Prototype float sqrt(float x); Function name, type, parameter and parameter type Function Definition float sqrt(float x) { // compute.
CS 1430: Programming in C++.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Arrays float Scores[9]; ? index: element // one dimensional array 1.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Activation Record int main() { float allScores[MAX_ROWS][MAX_COLS]; int rows, cols; GetAllData(allScores, rows, cols);... } 1 void GetAllData(float a[][MAX_COLS],
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
CS 1428 Final Exam Review. Exam Format 200 Total Points – 60 Points Writing Programs – 45 Points Tracing Algorithms and determining results – 20 Points.
Arrays float Scores[9]; ? index: element // one dimensional array 2.
Reference and Value Parameters Reference Parameters (&) The formal parameter receives the address of the actual parameter, and the function can read and.
Nested Structures struct TDate { int year, month, day; }; struct StudentType { string id, firstName, lastName; float gpa; TDate DOB; }; struct SectionType.
CS 1430: Programming in C++.
CS 1430: Programming in C++.
Scope of Variables The region of code where it is legal to reference (use) an identifier. Local Scope Global Scope Class Scope.
CS 1430: Programming in C++.
CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
CS 1430: Programming in C++ No time to cover HiC.
Review for Final Exam.
CS150 Introduction to Computer Science 1
CS 1428 Final Exam Review.
CS 1430: Programming in C++.
CS 1428 Final Exam Review.
Review for Final Exam.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Fundamental Programming
CS 1430: Programming in C++.
Presentation transcript:

CS 1430: Programming in C++ 1

Test 2 Friday Functions Arrays For Loops Understand Concepts and Rules Memorize Concepts and Rules Apply Concepts and Rules to Different Problems 2

3 C++ Functions Why? Modularity!

4 C++ Functions Function Prototype int IndexOfMax(const float s[], int size); Function Definition int IndexOfMax(const float s[], int size) { int index = 0; for (int i = 1; i < size; i ++) if (s[i] > s[index]) index = i; return index; } Function Call index = IndexOfMax(Test2Scores, numStudents);

5 Function Type The type of the value returned by a function float sqrt(float x); int IndexOfMax(const float s[], int size); bool eof(); char RomanChar(int romanDigitValue); StudentType GetStudent(); void ReadAnswers(char answers[], int numQuestions); RETURN Statement! Not Parameters!

6 Prog4 Required Function // // Finds and returns an index of the look-up-mass // in the Masses array. Since the Masses array is // ordered in ascending order by mass, this function // returns the index of the first mass in the masses // array such that lookUpMass is less than or equal // to masses[i]. // On the off chance that no such index can be found, // returns -1. // params: ( ?, ?, ? ) // int FindIndexOfMass(const int masses[], int lookUpMass, int size);

7 Prog4 Required Function // // Returns the largest value in the dim array; // size is how many items are in the dim array. // params: ( ?, ? ) // float FindLargestDimension(const int dim[], int size);

8 Prog4 Required Function // // Returns the girth of a parcel where girth is // calculated as twice the difference of the sum of // the elements in the dim array and the largest of // the dimensions. // params: ( ?, ? ) // float Girth( const int dim[], int size);

Function Parameters Need to pass data to the function May need more than one value out of the function Not Return Statement! Parameters are local variables Parameters get values or addresses at function calls 9

Formal Parameters and Actual Parameters Formal Parameters In function prototype and definition Must specify type with/without & [] for arrays with/without const Actual Parameters In function call No type, &, and no [] or const for arrays 10

Passing Parameters Basic Data Types (char, int, float, string, bool) Pass by Value (without & in prototype) Pass by Reference (with & in prototype) Arrays (of any data type) Always Pass by Reference (pointer!) (Never &) (Structure and Class) 11

Value Parameters and Reference Parameters const float REG_HOURS = 40.0; const float OVER_TIME = 1.5; int main() { float hours, rate, gross; GetInput(rate, hours); gross = GrossPay(rate, hours); // display result return 0; } float GrossPay(float payRate, float hours) { if (hours > REG_HOURS) payRate = (hours - REG_HOURS) * OVER_TIME * payRate + REG_HOURS * payRate; else payRate = hours * payRate; return payRate; } main() GetInput() void GetInput(float& payRate, float& hoursWorked) { cout << "Enter pay rate: "; cin >> payRate; cout << "Enter hours: "; cin >> hoursWorked; return; } GrossPay() Passing parameters Passing parameters Addresses of rate and hours Return control With value Return control 12

In, Out, InOut Parameters The original value of the actual parameter The value of the actual parameter before the function call In The function uses the original value of the actual parameter, but does not change its value. Out The function does not use the original value of the actual parameter, but changes its value. InOut The function uses the original value of the actual parameter, and also changes its value. 13

Tracing Functions Input: float GrossPay(float payRate, float hours) void GetInput(float& payRate, float& hoursWorked); main() GetInput() GrossPay() hours rate gross payRate& hoursWorked& hours payRate ? ? ? ? ? ? ? Addr of Addr of rate hours

Arrays Array Declaration const int MAX_SIZE = 30; int size = 30; int nums[30]; // Valid? float ArrayA[MAX_SIZE]; // Valid? float ArrayB[size]; // Valid? Memory allocation Array Element and Index Index starts with 0 An array element is the same as a single variable For Loop on array for (int i = 0; i < size; i ++) cin >> ArrayA[i]; 15

Functions on Arrays Always passing by reference No & Size is passed separately Const for IN parameter void ReadAnswers(char answers[], int numQuestions); void ProcessAnswer(const char keys[], const char answers[], int numQuestion, int& correct, bool& pass); Function calls No [] Passing arrays and passing array elements average = ArrayAvg(Scores, count); max = Largest(Scores[0], Scores[1], Scores[2]); Linear search return value or index 16

For Loops Same as while loops Better on arrays Better on Count-Controlled loops 17

Nested For Loops int result; for (int i = 4; i < 6; i ++) { result = 1; for (int j = i; j > 1; j --) result *= j; cout << “The result: “ << result; } 18

Tracing int i, j, result; for (i = 4; i < 6; i ++) { result = 1; for (j = i; j > 1; j --) result *= j; cout << “The result: ” << result; } Do it yourself now! i j result ? ? ?

Schedule Quiz7-1 Lab7 & Lab8 Prog4 Test 2 20

21 Test 1 Test 2 Test 3Final