Math Functions & 2-D Arrays Programming. COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 2 Copyright © 2000 by Brooks/Cole Publishing.

Slides:



Advertisements
Similar presentations
Functions. COMP104 Functions / Slide 2 Introduction to Functions * A complex problem is often easier to solve by dividing it into several smaller parts,
Advertisements

Single Variable and a Lot of Variables The declaration int k; float f; reserve one single integer variable called k and one single floating point variable.
Programming Searching Arrays. COMP102 Prog. Fundamentals: Searching Arrays/ Slide 2 Copyright © 2000 by Broks/Cole Publishing Company A division of International.
Introduction to Functions Programming. COMP102 Prog Fundamentals I: Introduction to Functions /Slide 2 Introduction to Functions l A complex problem is.
CSE202: Lecture 2The Ohio State University1 Variables and C++ Data Types.
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
Chapter 4 Summation.
Functions. COMP104 Lecture 13 / Slide 2 Review of Array: Bubble Sort for (j=0; j List[j+1]) swap(List[j], List[j+1]); }
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.
Multiple-Subscripted Array
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
CSE202: Lecture 16The Ohio State University1 Two Dimensional Arrays.
Topic 2A – Library Functions and Casting. CISC 105 – Topic 2A Functions A function is a piece of code which performs a specific task. When a function.
Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize & display Part I.
Basic Elements of C++ Chapter 2.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 8 Arrays and Strings
1 Last of the basics Controlling output Overflow and underflow Standard function libraries Potential pitfalls of getting information with cin Type casting.
COMP102 Lab 091 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
CS31: Introduction to Computer Science I Discussion 1A 4/9/2010 Sungwon Yang
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
C++ Programming: Basic Elements of C++.
CSE1222: Lecture 2The Ohio State University1. mathExample2.cpp // math example #include using namespace std; int main() { cout
Week 2 - Friday.  What did we talk about last time?  Base systems  C literals  Representations in memory.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 8 Multidimensional Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Basic Mathematics Chapter 1 (1.2 and 1.3) Weiss. Recursion / Slide 2 Logarithms * Definition: if and only if * Theorem 1.1: n Proof: apply the definition.
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
C++ Programming, Namiq Sultan1 Chapter 3 Expressions and Interactivity Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Chapter 2: Introduction to C++. Language Elements Keywords Programmer-defined symbols (identifiers) Operators Punctuation Syntax Lines and Statements.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
 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.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter 3 – Variables and Arithmetic Operations. First Program – volume of a box /************************************************************/ /* Program.
Lecture 5 Computer programming -1-. Input \ Output statement 1- Input (cin) : Use to input data from keyboard. Example : cin >> age; 2- Output (cout):
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Sahar Mosleh California State University San MarcosPage 1 One Dimensional Arrays: Structured data types.
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.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Bill Tucker Austin Community College COSC 1315
Chapter Topics The Basics of a C++ Program Data Types
Computing and Statistical Data Analysis Lecture 2
Two-Dimensional Arrays Lesson xx
Basic Elements of C++.
Multi-dimensional Array
Basic Elements of C++ Chapter 2.
Chapter 2 Elementary Programming
Using Free Functions Chapter 3 Computing Fundamentals with C++
Functions.
Fundamental Programming
Programming Structures.
Programming Structures.
Presentation transcript:

Math Functions & 2-D Arrays Programming

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 2 Copyright © 2000 by Brooks/Cole Publishing Company A division of International Thomson Publishing Inc. 2-D Array Example

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 3 2-D Array Example // 2-D array of 30 uninitialized ints int table[3][10];

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 4 2-D Array References -- table // 2-D array of 18 uninitialized chars char table[3][6]; table[1][2] = ' a ' ; char resp = table[1][2]; --a 0 2 1

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 5 2-D Array Initialization Declaration only reserves memory for the elements in the array. No values will be stored. If we don't initialize the array, the contents are unpredictable. Generally speaking, all arrays should be initialized. One way to initialize a 2D array is shown below // 2-D array of 18 initialized chars const int NUM_ROWS = 3, NUM_COLS = 6; char table[NUM_ROWS][NUM_COLS]={'a','b','c','d', 'e','f','g','h','i','j','k','l','m','n', 'o','p','q','r'}; nopm table rq hijglk bcdafe 0 2 1

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 6 Ex. 1: 2-D Array Initialization It is highly recommended, however, that you nest the data in braces to show the exact nature of the array. For example, array table is better initialized as : // 2-D array of 18 initialized chars const int NUM_ROWS = 3, NUM_COLS = 6; char table[NUM_ROWS][NUM_COLS]={ {'a','b','c','d','e','f'}, {'g','h','i','j','k','l'}, {'m','n','o','p','q','r'} }; nopm table rq hijglk bcdafe 0 2 1

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 7 Ex. 1: 2-D Array Inputting Values aln table ra Another way to fill up the values is to read them from the keyboard. For a two-dimensional array this usually requires nested for loops. If the array is an n by m array, the first loop varies the row from 0 to n-1. The second loop varies the column from 0 to m -1. const int NUM_ROWS = 3, NUM_COLS = 6; for (int row=0; row < NUM_ROWS; row++) for (int column = 0; column < NUM_COLS; column++) cin.get(table[row][column]); //input “ two-dimensional array” ensmoi wo-tid 0 2 1

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 8 Ex. 1: 2-D Array Outputting Values We can print the values of the elements one-by-one using two nested loops. Again, if the array is an n by m array, the first loop varies the row from 0 to n-1. The second loop varies the column from 0 to m-1. const int NUM_ROWS = 3, NUM_COLS = 6; for (int row=0; row < NUM_ROWS; row++) for (int column = 0; column < NUM_COLS; column++) cout << table[row][column]; aln table ra ensmoi wo-tid 0 2 1

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 9 Ex. 2: Addition Table We can store the values of the elements in an addition table in a two-dimensional array using two nested loops. Again, if the array is an n by n array, the first loop varies the row from 0 to n-1. The second loop varies the column from 0 to n table

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 10 Ex. 2: Addition Table // An addition table in a 2-dimensional array #include using namespace std; const int TABLE_SIZE = 4; // global size of addition table int main(){ int row, column; int add_table [TABLE_SIZE][TABLE_SIZE];// declare array // create the array for the addition table for (row = 0; row < TABLE_SIZE; row++){ for (column = 0; column < TABLE_SIZE; column++){ add_table[row][column] = row + column; }}

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 11 Ex. 2: Addition Table // Print the addition table for (row = 0; row < TABLE_SIZE; row++){ for (column = 0; column < TABLE_SIZE; column++){ cout << add_table[row][column] << " "; } cout << endl; } return 0; }

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 12 Mathematical Functions l #include (text book page 785) l double log(double x) //natural logarithm l double log10(double x) //base 10 logarithm l double exp(double x) //e to the power x l double pow(double x, double y) //x to the power y l double sqrt(double x) //positive square root of x l double sin(double x), cos(double x), tan(double x) //and many others

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 13 Mathematical Functions l double ceil(double x) //smallest integer not less than x // ceil(1.1) == 2, ceil(-1.9) == -1 l double floor(double x) //largest integer not greater than x // floor(1.9) == 1, floor(-1.1) == -2

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 14 Ex. 3: Distance Between Two Points We can use the Pythagorean theorem to calculate the distance between 2 points: a 2 + b 2 = c 2 x * 2 3 4* y b a c

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 15 Ex. 3: Distance Between Two Points // Compute distance between two points #include // contains sqrt() #include using namespace std; int main(){ double col1, row1, col2, row2; // coordinates for pnt 1 & 2 double dist; // distance between points cout > col1 >> row1; cout > col2 >> row2; // Compute the distance between points 1 & 2 //dist=sqrt((col2-col1)*(col2-col1)+(row2-row1)*(row2-row1)); dist = sqrt(pow((col2 – col1),2) + pow((row2-row1),2)); cout << "The distance is " << dist << endl; return 0; }

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 16 Ex. 4 & 5: Graphing Trajectories The next 2 examples use arrays to store the characters in a grid. Example 4 graphs one line on the grid. Example 5 graphs multiple lines on the grid, using an extra while loop.

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 17 Ex. 4: Trajectory Between 2 Points x * 2* 3* 4* 5* y

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 18 Ex. 4: Graphing a Trajectory Given a pair of coordinates (x1, y1), (x2, y2), we can easily get its formula: (y – y1)/(x – x1) = (y2 – y1)/(x2 – x1) = k which can also be written as: y = k * (x – x1) + y1 Assuming x1 < x2, using a for loop, we can set x be x1+1, x1+2, x1+3 … until x2-1, and calculate the correspond y and plot them on the grid.

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 19 Ex. 4: Graphing a Trajectory // Graph line between two points #include using namespace std; int const NUMBER_ROWS = 11; // global constants int const NUMBER_COLS = 31; int main(){ // set an array for the grid char grid[NUMBER_ROWS][NUMBER_COLS]; int row, col, row1, col1, row2, col2;// coordinates double rise, run, slope; // for background, fill grid with '-' character for (row = 0; row < NUMBER_ROWS; row++) for(col = 0; col < NUMBER_COLS; col++) grid[row][col] = '-';

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 20 Ex. 4: Graphing a Trajectory // get user input and check that it is on the grid do{ cout << "Enter column (x<" << NUMBER_COLS << ") & row (y<" << NUMBER_ROWS <<") coordinates of the 1st point: "; cin >> col1 >> row1; } while((row1 = NUMBER_ROWS) || (col1<0) || (col1 >= NUMBER_COLS)); do{ cout << "Enter column (x<" << NUMBER_COLS << ") & row (y<" << NUMBER_ROWS <<") coordinates of the 2nd point: "; cin >> col2 >> row2; } while((row2 = NUMBER_ROWS) || (col2<0) || (col2 >= NUMBER_COLS));

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 21 Ex. 4: Graphing a Trajectory // put characters into array to graph the line on grid // handle special cases where col1 == col2 first // to avoid division by 0 if((row1 == row2) && (col1 == col2)) // just one point grid[row1][col1] = '*'; else if(col2 == col1){ //slope is infinite if (row1 < row2) //fill downward for(row = row1; row <= row2; row++) grid[row][col1] = '*'; else//fill upward for(row = row1; row >= row2; row--) grid[row][col1] = '*'; }

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 22 Ex. 4: Graphing a Trajectory else{ rise = row2 - row1; run = col2 - col1; slope = rise / run; // run cannot = 0 if (run >0){ for(col = col1; col <= col2; col++){ // row1 is offset for starting point row = (int)(slope * (col - col1) + row1); grid[row][col] = '*'; } else{ for(col = col1; col >= col2; col--){ row = (int)(slope * (col - col1) + row1); grid[row][col] = '*'; }

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 23 Ex. 4: Graphing a Trajectory // print the grid from the array to the screen for(row = 0; row < NUMBER_ROWS; row++){ for(col = 0; col < NUMBER_COLS; col++){ cout << grid[row][col]; } cout << endl; } return 0; }

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 24 Ex. 5: Trajectories Among Points x ***** 2****** 3** 4* 5* y

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 25 The First Computer The construction of the first electronic computer, named the ENIAC, was commissioned by the US military in 1943 to compute the trajectory of a 16-in naval shell. But WWII was already over when the ENIAC was completed. All together, the U.S. Army provided approximately $500,000 for the ENIAC's development.

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 26 The First Computer l ENIAC (Electronic Numerical Integrator and Computer) l Development period: l Designers: John Mauchly and J. Presper Eckert, Jr.

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 27 The First Computer l Development organization: The Moore School of Electrical Engineering, University of Pennsylvania l Components: 18,000 vacuum tubes l Weight: 30 tons l Room to hold it: 1,500 square feet l Word size: 10 decimal digits l Cycle time: 100K Hz l Internal storage: none

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 28 Flight Distance of a Projectile l Newton's laws of motion n V = V 0 + a t (1) n S = V 0 t + ½ a t² (2) l Where n V is the velocity after acceleration; n V 0 is the initial velocity; n a is the acceleration; n t is the flight time; n S is the flight distance.

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 29 Flight Distance of a Projectile l Assuming no air resistance n V y = 0 when it is half way into the flight n a y = -g gravity which is 9.8 meters/sec² n half flight time t = V 0y /g = V 0 * sin(¼ π)/9.8 (1) n flight_distance = V 0 x * 2 * t = V 0 * cos(¼ π ) * 2 * t (2) l For example, for a howitzer ( Type mm, made in China) with muzzle speed of 515 meters/sec pointing at 45º upward. flight_time = 2 * 515 * sin(¼  )/9.8 n flight_distance = 515 * cos(¼ π ) * flight_time

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 30 Flight Distance of a Projectile V0V0 V 0 sin(  ) V 0 cos(  ) 

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 31 A Plotting Function //Function that places a 'o' at location (x,y) void graph_x_y(int x, int y){ if (x >= 0 && x < x_size && y >= 0 && y < y_size) grid[x][y] = 'o'; }

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 32 Using the Plotting Function /*Draw a trajectory for a gun whose muzzle speed is 515 meters/sec at 45 degrees upward angle */ v = 515.0; theta_r =0.25 * PI; // Find 1/2 flight time using 0 = v y - gt t_half = v * sin(theta_r) / GRAV; fl_time = 2 * t_half; // Find proper x-scale x_scale = fl_time / x_size; // Find max flight height height=v*sin(theta_r)*t_half - 0.5*GRAV*t_half*t_half; // Find proper y-scale y_scale = (y_size - 1) / height;

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 33 Using the Plotting Function // Graph this trajectory for (i = 0; i < x_size; i++){ fl_time = i * x_scale; h=int((v*sin(theta_r)*fl_time- 0.5*GRAV*fl_time*fl_time)*y_scale+0.5)); graph_x_y(i, h); } // Print the trajectories for (int j = y_size-1; j >= 0; j--){ for (i = 0; i < x_size; i++) cout << grid[i][j]; cout << endl; }

COMP102 Prog. Fundamentals I: Math Functions & 2D Arrays / Slide 34 Using the Plotting Function Draw the trajectories of a gun whose muzzle speed is 515 meters/second pointing at upward angles of 45 and 30 degrees: ooooooooooo oooo oooo ooo ooo oo oo o o oo oo o o oo oo o o oo oooooooooooooooo oo o ooo oooo o o ooo oo o o oo oo o o o oo o oo o o