PHYS707: Special Topics C++ Lectures Lecture 3. Summary of Today’s lecture: 1.Functions (call-by-referencing) 2.Arrays 3.Pointers 4.More Arrays! 5.More.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Advertisements

Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Computer Science 1620 Math Library. Remember this program? suppose that I invest $25000 into a mutual fund that returns 8% per year. Write a program to.
PHYS707: Special Topics C++ Lectures Lecture 2. Summary of Today’s lecture: 1.More data types 2.Flow control (if-else, while, do-while, for) 3.Brief introduction.
Factorial Preparatory Exercise #include using namespace std; double fact(double); int fact(int); int main(void) { const int n=20; ofstream my_file("results.txt");
Vectors, lists and queues
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Derived data types Dealing with data –Where the information is stored –What value is kept there –What kind of information is stored Address operator Pointers.
Revision.
第三次小考. #include using namespace std; int aaa(int *ib,int a1,int a2) { int u,v; int m=(a1+a2)/2; if(a1==a2)return ib[a1]; u=aaa(ib,a1,m); cout
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Tinaliah, S. Kom.. * * * * * * * * * * * * * * * * * #include using namespace std; void main () { for (int i = 1; i
Triana Elizabeth, S.Kom. #include using namespace std; void main () { for (int i = 1; i
Local and Global Variables. COMP104 Local and Global / Slide 2 Scope The scope of a declaration is the block of code where the identifier is valid for.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
COMP102 – Programming Fundamentals I LA2B (Mon 5-7pm) LA2E (Fri 3-5pm) LA2F (Fri 5-7pm) TA: Jackie Lo.
16/19/2015 1:14 PM6/19/2015 1:14 PM6/19/2015 1:14 PMArrays and Structures Methods to manipulate a collection of values under one name. Arrays: Homogenous.
Functions. COMP104 Lecture 13 / Slide 2 Review of Array: Bubble Sort for (j=0; j List[j+1]) swap(List[j], List[j+1]); }
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
Functions Modules in C++ are called functions and classes
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
New Data Types in C++ Programs We can specify and implement new data types in C++ using classes  need specification as to how represent data objects of.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
By – Tanvir Alam.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google. 
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
CS1201: Programming Language 2 Recursion By: Nouf Almunyif.
February 11, 2005 More Pointers Dynamic Memory Allocation.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Functions Introduction to Programming By Engr. Bilal Ahmad 1ITP by Engr. Bilal Ahmad.
Current Assignments Homework 3 is due tonight. Iteration and basic functions. Exam 1 on Monday.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
Dynamic memory allocation and Pointers Lecture 4.
Chapter 7 Functions CS185/09 - Introduction to Programming Caldwell College.
Tracing through E01, question 9 – step 1 // p02.cc P. Conrad, for CISC181 07S // Exam question for E01 #include using namespace std; void mysteryFunction(int.
1 Original Source : and Problem and Problem Solving.ppt.
Objective: Students will be able to: Declare and use variables Input integers.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
CSci 162 Lecture 6 Martin van Bommel. Functions on Structures Rather than pass a copy of structure to a function, or return a copy back as the function.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
1 17/4/1435 h Monday Lecture 3 The Parts of a C++ Program.
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.
Fundamental Programming Fundamental Programming Data Processing and Expressions.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Static Data Member and Functions
Dynamic Memory Allocation Reference Variables
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
Starting Out with C++: From Control Structures through Objects
Pointers & Functions.
Chapter 4 Implementing Free Functions
Pass by Reference.
CSC 270 – Survey of Programming Languages
CS150 Introduction to Computer Science 1
Control Structures Part 1
Arrays of Two-Dimensions
Dynamic Memory.
Pointers & Functions.
Modifying Objects Assignment operation Assignment conversions
Main Title Here Topic 2 Topic 3 Topic 4 Topic 5
CS150 Introduction to Computer Science 1
Introduction to Algorithms and Programming COMP151
Presentation transcript:

PHYS707: Special Topics C++ Lectures Lecture 3

Summary of Today’s lecture: 1.Functions (call-by-referencing) 2.Arrays 3.Pointers 4.More Arrays! 5.More pointers!

But First: Namespaces Typical program: #include using namespace std; int main() { [program goes here] return 0; } The " #include " just includes a library of routines, but what the heck is that " using" stuff??

A "namespace" is where definitions of names are kept. "std" is the name of a particular namespace. In there, for example, are kept the names cin and cout. If you don't want to use "using namespace std;" you can still use the names it contains, including cin and cout: std::cout << "this is a sample output\n"; std::cin >> x; // this is a sample input Note the syntax: namespace_name::name_in_that_namespace (If you look on the web, you'll often see sample programs that do this instead of using the std namespace.) Q: Why NOT use "using namespace std;"? A: What if you want to use your own definition of cout (or some other defined name)?? Q: Can I create my own namespace? A: Yes!! Here's an example from the text:

#include using namespace std; // this namespace is used "globally" namespace savitch1 { void greeting(); } namespace savitch2 { void greeting(); // note: function has same name in both namespaces!! } void big_greeting(); int main() { using namespace savitch2; // only valid within this "block" greeting(); } { using namespace savitch1; // only valid within this "block" greeting(); } big_greeting(); return 0; }

namespace savitch1 { void greeting() { cout << "Hello from namespace savitch1.\n"; } namespace savitch2 { void greeting() { cout << "Greetings from namespace savitch2.\n" } void big_greeting() { cout << "A Big Global Hello!\n"; } Output when program is executed: Greetings from namespace savitch2. Hello from namespace savitch1. A Big Global Hello!

Functions, Part 2 Passing arguments by reference: #include using namespace std; void get_numbers (int& input1, int& input2); // reads two integers from keyboard int main() { get_numbers(first_num, second_num); cout << first_num << " " << second_num << endl; return 0; } void get_numbers(int& input1, int& input2) { cout << "input 2 integers\n"; cin >> input1 >> input 2; } Note the “&” Note: No “&”!

NOTE: Values of input1 and input2 change! Use call-by-reference when you want the value of the argument to change Use call-by-reference when passing dynamic arrays or pointers * Can your function modify a parameter and return a value? SURE!! Can a function have some parameters call-by-position and others call-by- reference? SURE!! Can a function call another function? SURE!! But the function declaration MUST precede the function use. * But just a tad different format

Overloading Functions C++ is really smart! Can use the same name for related (but different) functions: #include using namespace std; double avg(double n1, double n2); // averages 2 numbers double avg(double n1, double n2, double n3); // averages 3 numbers int main() { cout << avg(1.0,2.0) << endl; cout << avg(1.0,2.0,3.0) << endl; return 0; } double avg(double n1, double n2) { return (n1+n2)/2.0; } double avg(double n1, double n2, double n3) { return (n1+n2+n3)/3.0; }

Arrays Declaring 1-D arrays: int score[5]; double mydata[25]; This is legal: const int maxdim = 5; double data[maxdim]; This is NOT: int maxdim = 5; double data[maxdim]; Using the array: for(i = 0; i < maxdim; i++) { data[i] = 2*i+4; } Warning: data[maxdim] = 3; // wrong!!

Arrays in Functions double fct(double a[], int numdim); int main() { [some code] x = fct(a, 5); // Note: no array brackets when calling the fct! } double fct(double z[], int dim) { double sum = 0; for(int i = 0, i < dim; i++) { sum += z[i]; } return sum; } Too bad: we have to know how big an array we need at the time we write the program 

Multi-Dimensional Arrays Correct: int a[3][4]; double c[4][12][2]; Wrong! int a[3,4]; double c(4,12,2);

Pointers A pointer variable “points to” (contains) the address of a variable When you declare a pointer variable, its “type” should be the same as the type of the variable that the pointer points to. int *p1, *p2, v1, v2; // p1 and p2 are pointers to integers. v1 and v2 are just integers. p1 = &v1; /* p1 now contains the address of v1 “&” means “give the address of the variable that follows”*/ Consider this code fragment: v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << endl; cout << *p1 << endl; This gives: 42 Try it!!

Variables?! We don’t need no stinkin’ variables!! int *p1 // declare pointer variable p1 = new int; // a new “nameless” variable is now pointed to by p1!! cin >> *p1; // put a value into the nameless variable pointed to by p1 *p1 = *p1 + 7; // add 7 to the nameless variable’s value cout << *p1 // the output is what you input, plus 7!! delete p; // frees up that memory location again (Important!!) The type of the nameless variable must match the type spec’d for the pointer We do this ALOT in C++ Good to free up the memory pointed to by p. (Memory returned to the “freestore” or “heap”) But don’t “kill” that spot until you’re done with it! If another pointer is pointing to that location and you delete p1, than the second pointer is left pointing to some random spot in memory!! (You told the computer you were done reserving that spot. It gave the spot away to some other needy customer.)

Dynamic Arrays It’s very inconvenient to have to know your array size at the time you write your program. Wouldn’t it be nice to let the array fit your needs at runtime? int main() { double *mydata; int array_size; cout << “How many data points do you have?\n”; cin >> array_size; mydata = new double [array_size]; for ( i = 0; i < array_size; i++) { mydata[i] = 2.0*double(i) +3.0; // Use just like any other array } [more code goes here…] delete [] mydata; // note the brackets!! return 0; } But why don’t I need the “*”???

Because an ordinary array variable is just a pointer!! // program to show an array variable is a pointer #include using namespace std; int main() { int *p, a[10], index; for (index = 0; index < 10; index++) a[index] = index; p= a; for (index = 0; index < 10; index++) cout << p[index] << “ “; cout << endl; for (index = 0; index < 10; index++) p[index] = p[index]+1; // changes to p => changes to a! for (index = 0; index < 10; index++) cout << a[index] << “ “; cout << endl; return 0; } Output: Since an array variable is a pointer, you treat it like one -- and, if your pointer points to an array, treat your pointer variable like an array variable!

Pointer Arithmetic double *d; int arraysize = 10; d = new double[array_size]; [ put some value into the array…] for (i = 0; i < array_size; i++) cout << *(d + i) << “ “; for (i = 0; i < array_size; i++) cout << d[i] << “ “; d now contains the address of d[0] ; d+1 points to d[1 ], etc. Output the contents of the memory at locations d+i using “normal” pointer notation This does the same thing! Can do addition and subtraction (with integers only); NO mult or div! (Why would you??) Can also subtract two pointers to the same variable. This gives the number of indexed variables between the two. C++ is smart: it figures out the number of variable spots, not bytes, between two pointers!

Passing Pointers as Function Arguments #include using namespace std; void swap(double *a, double *b); // function just swaps values of the 2 inputs int main() { double *a, *b; a = new double; b = new double; *a = 5.0; *b = 10.0; cout << *a << “ “ << *b << endl; swap(a, b); cout << *a << “ “ << *b << endl; return 0; } void swap(double *a, double *b) { double tmp; tmp = *a; *a = *b; *b = tmp; } Function declaration Note the “*” Function call No “*” (just like array) Function definition Note the “*”

Homework! 1.Write (and test) a function that takes 3 arguments: R, Area, and Circumference. When you call the function, you’ve only defined R, but when the function is executed, Area and Circumference now contain the area and circumference of a circle of radius R. 2.Write a program that asks you for the number of inputs you want to give it. Then have it ask you for those N inputs. Now call a function that returns the average of those N inputs. [Hint: put the inputs into an array, then pass that array to a function that takes the average of the array’s elements.]