4. Functions. March 10, 2010
|
|
- Gwendoline Goodwin
- 6 years ago
- Views:
Transcription
1 March 10, 2010 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 40
2 Outline Recapitulation Functions Part 1 What is a Procedure? Call-by-value and Call-by-reference Functions Part 2 The Details Recursion An Example: gcd (greatest common divisor) Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 2 of 40
3 Recapitulation What is the difference between = and ==? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
4 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
5 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
6 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? What is a scope? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
7 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? What is a scope? What is the meaning of a while-loop? What does a while-loop look like? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
8 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? What is a scope? What is the meaning of a while-loop? What does a while-loop look like? Can we modify a parameter within a while-loop? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
9 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? What is a scope? What is the meaning of a while-loop? What does a while-loop look like? Can we modify a parameter within a while-loop? What happens if a single integer is argument/guard of a while-loop? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
10 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? What is a scope? What is the meaning of a while-loop? What does a while-loop look like? Can we modify a parameter within a while-loop? What happens if a single integer is argument/guard of a while-loop? What is dangerous if we declare two integer variables in one row: i n t a, b=10; Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
11 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? What is a scope? What is the meaning of a while-loop? What does a while-loop look like? Can we modify a parameter within a while-loop? What happens if a single integer is argument/guard of a while-loop? What is dangerous if we declare two integer variables in one row: i n t a, b=10; What is the difference of the compiler and the linker? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
12 Recapitulation What is the difference between = and ==? What is a strict boolean expression? Why should an if-statement always be followed by a {? What is a scope? What is the meaning of a while-loop? What does a while-loop look like? Can we modify a parameter within a while-loop? What happens if a single integer is argument/guard of a while-loop? What is dangerous if we declare two integer variables in one row: i n t a, b=10; What is the difference of the compiler and the linker? What is the difference of a declaration and the definition? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 3 of 40
13 4.1. Functions 1 What do these two sayings have in common? Common saying: Good things come in small packages. Common saying: Never reinvent the wheel. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 4 of 40
14 Code Dublication i n t main ( ) { double priceofmoutainbike = ; double exchangeratejanuary = ; / / January double exchangeratefebruary = ; / / February double exchangeratemarch = 1,3569; / / March / We always have to pay 60% of t o t a l cost t h i s month. / double f i r s t P a y m e n t = ; double t o t a l C o s t ; t o t a l C o s t = ( firstpayment priceofmoutainbike ) exchangeratejanuary + ( ( firstpayment ) priceofmoutainbike ) exchangeratefebruary ; std : : cout << p r i c e of January : << t o t a l C o s t << std : : endl ; t o t a l C o s t = ( firstpayment priceofmoutainbike ) exchangeratefebruary + ( ( firstpayment ) priceofmoutainbike ) exchangeratemarch ; std : : cout << p r i c e of February : << t o t a l C o s t << std : : endl ; There is two bugs in this code! Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 5 of 40
15 Code Dublication Duplicated code is difficult to maintain, to fix, and to extend. void main ( ) { code p a r t A code p a r t A Long code is difficult to read and to understand (Spaghetti code). void main ( ) { code doing one t h i n g code doing something d i f f e r e n t Duplicated code is a loss of development time. void main ( ) { code implementing Gauss quadrature void main ( ) { another implementing Gauss quadrature Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 6 of 40
16 Functions void compute ( double price, double firstpayment, double ratea, double rateb ) { double t o t a l C o s t = ( firstpayment price ) ratea + ((1.0 firstpayment ) price ) rateb ; std : : cout << t o t a l C o s t << std : : endl ; i n t main ( ) { double p r i c e = ; double january = ; / / January double f e b r uary = ; / / February double march = 1,3569; / / March double f i r s t P a y m e n t = ; std : : cout << January : ; compute ( price, firstpayment, january, february ) ; std : : cout << February : ; compute ( price, firstpayment, february, march ) ; Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 7 of 40
17 void foo ( i n t a ) { a += 20; std : : cout << a ; foo ( 3 9 ) ; i n t b=20; foo ( b ) ; foo ( b +10); C/C++ mechanism: Function or procedure. A function is a helper/assistant of the whole program. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 8 of 40
18 void foo ( i n t a ) { a += 20; std : : cout << a ; foo ( 3 9 ) ; i n t b=20; foo ( b ) ; foo ( b +10); C/C++ mechanism: Function or procedure. A function is a helper/assistant of the whole program. i n t a0 = 39; / / foo (39) a0 += 20; std : : cout << a0 ; i n t b=20; i n t a1 = b ; / / foo ( b ) a1 += 20; std : : cout << a1 ; i n t a2 = b+10; / / foo ( b+10) Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 8 of 40
19 Functions and Scopes void foo ( i n t a ) { a += 20; std : : cout << a ; b += 1; void bar ( i n t b ) { foo ( b ) ; foo ( b +10); foo ( b +20); What happens here? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 9 of 40
20 Functions and Scopes void foo ( i n t a ) { a += 20; std : : cout << a ; b += 1; void bar ( i n t b ) { foo ( b ) ; foo ( b +10); foo ( b +20); What happens here? Functions define a scope due to the brackets { (basis block). Variables of other scopes are not defined within the function. Code above consequently does not work. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 9 of 40
21 Global Variables i n t b ; void foo ( i n t a ) { a += 20; std : : cout << a ; b += 1; void bar ( i n t b ) { foo ( b ) ; foo ( b +10); foo ( b +20); C/C++ allows programmer to define (global variables). Good practice: avoid them due to side effects. Now, code does work. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 10 of 40
22 Functions and the Program Counter Memory void foo() { foo1; foo2; foo3;... foo(); // call foo foo(); PC 21: 22; foo1 // first operation of foo 23; foo2 24; foo3 25; 26; 27; foo() // call of foo 28: foo() Function call modifies program counter. Computer remembers where to jump back. Function code is only stored once in memory. Not only the program counter is remembered, but all the variables. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 11 of 40
23 The Call-Stack void foo ( ) { i n t a = 20; / / do something with a / / a now equals 50; void bar ( ) { i n t a = 30; foo ( ) ; Function call modifies program counter. Computer remembers where to jump back. Function code is only stored once in memory. Not only the program counter is remembered, but all the variables. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 12 of 40
24 The Return Statements i n t increment ( i n t a ) { a = a+1; r e t u r n a ; void bar ( ) { i n t a = 30; i n t b = increment ( a ) ; std : : cout << b ; Functions can return a value due to the return command. Returned type has to equal the type of the function. If a function doesn t return a value, the function s type is void. Consequently, void is a new primitive datatype. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 13 of 40
25 What is the main Function? i n t main ( ) { / / do something void bar ( ) { / / do something double foo ( ) { / / do something Any program is a collection of functions. They have to have unique signatures (names). At startup, the computer has to know where to set the program counter to. It always sets it to the main function. The main function returns 0 if it has been successful (error code). This is a UNIX convention. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 14 of 40
26 Functions Some Best Practices i n t main ( ) { / / do something void bar ( ) { / / do something double foo ( ) { / / do something One purpose, one function. Any function should concentrate solely on one job. One page, one function. With a less, one should be able to see the complete function. A function without documentation does not exist. Functions should have meaningful names (verbs). Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 15 of 40
27 4.2. Call-by-reference vs. Call-by-value The Call-Stack and Variables void foo ( ) { i n t a = 20; / / do something with a / / a now equals 50; void bar ( ) { i n t a = 30; i n t b = 20; foo ( ) ; Computer encounters function call (foo()). It stores away all variables and remembers where it has been called from. It resets the program counter. As soon as the function terminates, it jumps back to the place of invocation, and it restores all variables. This way, a function cannot modify an outer variable. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 16 of 40
28 Call-by-value void foo ( i n t x ) { / / do something with x / / x now equals 50; void bar ( ) { i n t a = 30; i n t b = 20; foo ( a ) ; Computer encounters function call (foo()) with argument a. It stores away all variables and remembers where it has been called from. Furthermore, it creates a copy of a. It resets the program counter. This way, a function cannot modify an outer variable. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 17 of 40
29 Call-by-value In C/C++, parameters (arguments) are passed call-by-value. Functions work on copies of the original variables. The original variables are saved away on the call stack. As soon as the operation terminates, the old variable values are restored. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 18 of 40
30 The Return Statement and Call-by-value i n t foo ( i n t x ) { x = x 2; r e t u r n x ; void bar ( ) { i n t a = 30; i n t b = foo ( a ) ; a = foo ( a ) ; The return statement takes the value of the function s copy and writes it to the left-hand side of the function invocation. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 19 of 40
31 Call-by-reference i n t foo ( i n t & x ) { x = x 2; r e t u r n x ; void bar ( ) { i n t a = 30; i n t b = foo ( a ) ; The & operator is the reference operator. It tells C/C++ to pass the argument with call-by-reference semantics. Then, C/C++ does not create a copy, but the operation works on the original variable. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 20 of 40
32 i n t foo ( i n t & x ) { x = x 2; r e t u r n x ; void bar ( ) { i n t a = 30; i n t b = foo ( a ) ; a = foo ( a ) ; The & operator is the reference operator. It tells C/C++ to pass the argument with call-by-reference semantics. Then, C/C++ does not create a copy, but the operation works on the original variable. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 21 of 40
33 Exercise: Swap Two Variables void main ( ) { i n t a = 3; i n t b = 4; / / interchange a and b a = b ; b = a ; std : : cout << a << std : : endl ; std : : cout << b << std : : endl ; Fix the code above. Extract the swap functionality in a function of its own. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 22 of 40
34 Efficient Codes Copy-by-value is save as it forbids side-effects. Whenever possible, use copy-by-value (default). Copy-by-reference is faster. Question: Can we write fast and save code? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 23 of 40
35 Const References void foo ( i n t a, i n t b ) { void bar ( i n t & a, i n t & b ) { void e f f i c i e n t F o o ( const i n t & a, const i n t & b ) { Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 24 of 40
36 4.3. const Modifier an Excursus In C++, we can mark any argument to be a const argument, i.e. the function is not allowed to modify it. void foo ( const i n t a ) { const allows compiler to optimise code aggressively. const allows you to write bug-safe code (user cannot modify a variable by accident). const closes the performance gap between C/C++ and Fortran. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 25 of 40
37 Please, Use Const Remember the 80 : 20 rule you never know the performance properties. Remember that it might help others and you to produce less bugs. Remeber the implications. void foo ( i n t & a ) { void bar ( i n t a ) { / / t h i s f u n c t i o n i s very slow and has to be tune foo ( a ) ; / / continue c a l c u l a t i o n s foo ( 1 0 ) ; / / t h i s does not work, instead we have to w r i t e i n t tmp = 10; foo ( tmp ) ; We cannot optimise bar, as foo does not have a const signature. The last example is an aritificial one, but we will encounter similar problems soon. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 26 of 40
38 4. 2 The Signature of a Function i n t foo ( ) i n t bar ( ) i n t foo ( i n t a ) i n t foo ( double x ) i n t foo ( i n t a, const double& b, double x ) A function is unique due to its name, and due to the number of arguments, and due to the type of the arguments, and due to the const modifiers of its arguments, and due to a const modifier (not addressed yet). Everything besides the name defines the signature. The name and the signature make the function unique. The return value however does not come into play. Some definition make the const modifier not part of the signature. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 27 of 40
39 Overloading i n t foo ( ) i n t foo ( i n t a ) { i n t foo ( double a ) { foo ( ) ; foo ( 3. 4 ) ; foo ( 4 ) ; To overload a function means to offer it with different signatures. C/C++ then automatically tries to find the right signature. However, be aware of automatic type conversions. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 28 of 40
40 Automatic Type Conversion i n t foo ( ) i n t foo ( i n t a ) { i n t foo ( double a ) { i n t a = 10; double b = a ; foo ( a ) ; foo ( b ) ; foo ( a / 3. 0 ) ; Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 29 of 40
41 Priority i n t foo ( ) i n t foo ( i n t a ) { i n t foo ( double a ) { i n t bar ( i n t a, i n t b ) { i n t bar ( double a, double b ) { i n t a = 10; double b = a ; foo ( a ) ; foo ( b ) ; foo ( a / 3. 0 ) ; bar ( a, 3 ) ; bar ( b, 3 ) ; bar ( a, 3. 0 ) ; Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 30 of 40
42 Rules for Overloading If the arguments match exactly without type conversion, use this definition. If there is no exact match but a match due to automatic type conversion, C/C++ uses this definition. If there s a const and a non-const argument, C/C++ uses the const variant (not for all compilers). Besides, the automatic type conversion, also take care of return type conversion: double foo ( i n t a ) { r e t u r n a / 3 ; foo ( 4. 0 ) ; / / well, t h i s does not work foo ( 4 ) ; Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 31 of 40
43 Default Arguments void foo ( i n t a = 3 ) ; void bar ( ) ; void bar ( i n t b = 3 ) ; / / not allowed void tee1 ( i n t c, double d = 2. 0 ) ; void tee2 ( i n t c =2, double d ) ; / / not allowed void tee3 ( i n t c =2, double d = 4. 0 ) ; foo ( ) ; foo ( 7 ) ; tee3 ( ) ; tee1 ( 1 ) ; tee1 ( 1, 4. 0 ) ; C/C++ support default arguments. They may not interfere with overloaded functions. They may not be followed by arguments without default arguments. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 32 of 40
44 Return Statements double foo ( double a, double h ) { i f ( h==0) { r e t u r n 0. 0 ; i f ( a==0) r e t u r n ; / / e r r o r / / do something complicated with a and h r e t u r n a ; void foo ( double a, double h ) { r e t u r n 1; / / e r r o r A return statements makes the application leave the current function. A return statement accepts one argument: the return value (if it is not a void function). A return statement may be everywhere in the function. However, multiple return statements often are considered to be bad style. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 33 of 40
45 4.5. Recursion A Simple Game void foo ( i n t l e f t, i n t r i g h t, i n t t ) { / / value of v a r i a b l e s i n t b = l e f t + r i g h t ; / / value of v a r i a b l e s b /= 2; / / value of v a r i a b l e s i f ( b<t ) { foo ( b, r i g h t, t ) ; / / value of v a r i a b l e s i f ( b>t ) { foo ( l e f t, b, t ) ; / / value of v a r i a b l e s foo ( 12,40,7); Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 34 of 40
46 Recursion Principles void foo1 ( i n t a ) { i f ( a==0) { return ; foo1 ( a 1); Functions may call themselves (recursion). Each function call has its own copy of all the variables. This may not terminate, so we have to be careful. So code a proper termination criterion. The underlying pattern often is referred to divide and conquer (which is not a Roman saying!). Recursion is a very powerful tool (matrix block algorithms, multiscale basis systems, adaptive mesh refinement, e.g.) a tool many programmers however do not understand. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 35 of 40
47 Greatest Common Divisor Write a recursive function gcd(int a, int b) which computes the greatest common divisor. Test it for a=50,b=54. Make it plot the trace. Idea: a%b = 0 b is the gcd. Otherwise gcd(a, b) gcd(b, a%b). Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 36 of 40
48 Types of Recursion Linear vs. Non-linear Recursion / / Finonacci implementation 1 void foo ( i n t a ) { i f ( a==0) { return ; foo1 ( a 1); / / Finonacci implementation 2 void bar ( i n t a ) { i f ( a==0) { return ; bar ( a 1); bar ( a 2); Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 37 of 40
49 Types of Recursion (Linear) Tail Recursion / / Finonacci implementation 1 void foo ( i n t a ) { i f ( a==0) { return ; foo1 ( a 1); void bar ( i n t a ) { while ( ) { i f ( a==0) { return ; Theorem: You can rewrite every tail recursion into a loop. Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 38 of 40
50 Tail Recursion in Action i n t foo ( i n t a ) { i f ( a <= 1) { r e t u r n 1; return a foo ( a 1); What is the semantics of foo(int)? Rewrite foo(int) without recursion. Which variant might perform faster? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 39 of 40
51 Indirekt Recursion (Kaskadische Rekursion void foo ( i n t a ) { i f ( ) { foo ( a 4); bar ( a 1); foo ( a 1); void bar ( i n t a ) { foo ( a 1); Is foo a recursive function? Is foo a tail recursion? Is foo linear? Is bar a recursive function? Is bar a tail recursion? Is bar linear? Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 40 of 40
6. Pointers, Structs, and Arrays. March 14 & 15, 2011
March 14 & 15, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung
More information6. Pointers, Structs, and Arrays. 1. Juli 2011
1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung
More information5. Applicative Programming. 1. Juli 2011
1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 41 Outline Recapitulation Computer architecture extended: Registers and caches Header files Global variables
More information10. Object-oriented Programming. 7. Juli 2011
7. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Object Case Study Brain Teaser Copy Constructor & Operators Object-oriented Programming, i.e.
More informationObject-oriented Programming in C++
Object-oriented Programming in C++ Working with C and C++ Wolfgang Eckhardt, Tobias Neckel June 30, 2014 Working with C and C++, June 30, 2014 1 Challenges of This Course Heterogeneity of the audience
More informationObject-oriented Programming in C++
Object-oriented Programming in C++ Working with C and C++ Wolfgang Eckhardt, Tobias Neckel March 23, 2015 Working with C and C++, March 23, 2015 1 Challenges of This Course Heterogeneity of the audience
More information8. Object-oriented Programming. June 15, 2010
June 15, 2010 Introduction to C/C++, Tobias Weinzierl page 1 of 41 Outline Recapitulation Copy Constructor & Operators Object-oriented Programming Dynamic and Static Polymorphism The Keyword Static The
More information11. Generic Programming and Design Patterns. 8. Juli 2011
8. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 26 Outline Recapitulation Template Programming An Overview over the STL Design Patterns (skipped) Evaluation/feedback
More informationChapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
More informationScientific Computing
Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationPointers, Arrays and Parameters
Pointers, Arrays and Parameters This exercise is different from our usual exercises. You don t have so much a problem to solve by creating a program but rather some things to understand about the programming
More information2. Variables, Identifiers, and Expressions. March 8, 2011
March 8, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 34 Outline A Movie Structure of Simple C Codes Comments & Documentation Variables & Identifiers Built-in
More informationCS 310 Advanced Data Structures and Algorithms
CS 310 Advanced Data Structures and Algorithms Recursion June 27, 2017 Tong Wang UMass Boston CS 310 June 27, 2017 1 / 20 Recursion Recursion means defining something, such as a function, in terms of itself
More informationSPIM Procedure Calls
SPIM Procedure Calls 22C:60 Jonathan Hall March 29, 2008 1 Motivation We would like to create procedures that are easy to use and easy to read. To this end we will discuss standard conventions as it relates
More informationProgramming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3
Programming in C main Level 2 Level 2 Level 2 Level 3 Level 3 1 Programmer-Defined Functions Modularize with building blocks of programs Divide and Conquer Construct a program from smaller pieces or components
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationSeparate Compilation Model
Separate Compilation Model Recall: For a function call to compile, either the function s definition or declaration must appear previously in the same file. Goal: Compile only modules affected by recent
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017
More informationUser Defined Functions
User Defined Functions CS 141 Lecture 4 Chapter 5 By Ziad Kobti 27/01/2003 (c) 2003 by Ziad Kobti 1 Outline Functions in C: Definition Function Prototype (signature) Function Definition (body/implementation)
More informationOrdering Within Expressions. Control Flow. Side-effects. Side-effects. Order of Evaluation. Misbehaving Floating-Point Numbers.
Control Flow COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Control Flow Time is Nature s way of preventing everything from happening at once. Scott
More informationMidterm Practice TA: Brian Choi Section Webpage:
Midterm Practice TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 *** Make sure you try all exercises by hand! You won t have access to Visual C++ during the exam.
More informationControl Flow COMS W4115. Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science
Control Flow COMS W4115 Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science Control Flow Time is Nature s way of preventing everything from happening at once. Scott identifies
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationCS 3410 Ch 7 Recursion
CS 3410 Ch 7 Recursion Sections Pages 7.1-7.4, 7.7 93-319, 333-336 7.1 Introduction 1. A recursive method is a method that either directly or indirectly makes a call to itself. [Weiss]. It does this by
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationMachine Language Instructions Introduction. Instructions Words of a language understood by machine. Instruction set Vocabulary of the machine
Machine Language Instructions Introduction Instructions Words of a language understood by machine Instruction set Vocabulary of the machine Current goal: to relate a high level language to instruction
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter
More informationConditionals !
Conditionals 02-201! Computing GCD GCD Problem: Compute the greatest common divisor of two integers. Input: Two integers a and b. Output: The greatest common divisor of a and b. Exercise: Design an algorithm
More informationCh. 12: Operator Overloading
Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42
More informationBasic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable
Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is
More informationStatements execute in sequence, one after the other, such as the following solution for a quadratic equation:
Control Structures Sequence Statements execute in sequence, one after the other, such as the following solution for a quadratic equation: double desc, x1, x2; desc = b * b 4 * a * c; desc = sqrt(desc);
More informationComputer Organization & Assembly Language Programming
Computer Organization & Assembly Language Programming CSE 2312 Lecture 11 Introduction of Assembly Language 1 Assembly Language Translation The Assembly Language layer is implemented by translation rather
More informationBruce Merry. IOI Training Dec 2013
IOI Training Dec 2013 Outline 1 2 3 Outline 1 2 3 You can check that something is true using assert: #include int main() { assert(1 == 2); } Output: test_assert: test_assert.cpp:4: int main():
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationNote 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...
CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?
More informationCIS 190: C/C++ Programming. Classes in C++
CIS 190: C/C++ Programming Classes in C++ Outline Header Protection Functions in C++ Procedural Programming vs OOP Classes Access Constructors Headers in C++ done same way as in C including user.h files:
More informationint foo() { x += 5; return x; } int a = foo() + x + foo(); Side-effects GCC sets a=25. int x = 0; int foo() { x += 5; return x; }
Control Flow COMS W4115 Prof. Stephen A. Edwards Fall 2007 Columbia University Department of Computer Science Order of Evaluation Why would you care? Expression evaluation can have side-effects. Floating-point
More informationLECTURE 18. Control Flow
LECTURE 18 Control Flow CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear in a program text. Selection (or alternation): a
More informationCOSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26
COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.
More informationAgenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures
The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF
More informationFunctions, Pointers, and the Basics of C++ Classes
Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.
More informationSystem Software Assignment 1 Runtime Support for Procedures
System Software Assignment 1 Runtime Support for Procedures Exercise 1: Nested procedures Some programming languages like Oberon and Pascal support nested procedures. 1. Find a run-time structure for such
More informationPatterns: Working with Arrays
Steven Zeil October 14, 2013 Outline 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates
More informationMidterm Review. PIC 10B Spring 2018
Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed
More informationControl Flow. Stephen A. Edwards. Fall Columbia University
Control Flow Stephen A. Edwards Columbia University Fall 2013 Control Flow Time is Nature s way of preventing everything from happening at once. Scott identifies seven manifestations of this: 1. Sequencing
More informationCh. 11: References & the Copy-Constructor. - continued -
Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed
More informationAbstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles
Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can
More informationFunctions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function
Functions in C++ Functions For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Declarations vs Definitions Inline Functions Class Member functions Overloaded
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationChapter 3 Function Overloading
Chapter 3 Function Overloading Function Overloading. Calling Overloaded Function. Function Overloading When Several Function declaration are specified for a single function name in the same scope, the
More informationMemory and Pointers written by Cathy Saxton
Memory and Pointers written by Cathy Saxton Basic Memory Layout When a program is running, there are three main chunks of memory that it is using: A program code area where the program itself is loaded.
More informationUEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter
UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter What you will learn from Lab 7 In this laboratory, you will understand how to use typical function prototype with
More informationAS08-C++ and Assembly Calling and Returning. CS220 Logic Design AS08-C++ and Assembly. AS08-C++ and Assembly Calling Conventions
CS220 Logic Design Outline Calling Conventions Multi-module Programs 1 Calling and Returning We have already seen how the call instruction is used to execute a subprogram. call pushes the address of the
More informationG Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University
G22.2110-001 Programming Languages Spring 2010 Lecture 4 Robert Grimm, New York University 1 Review Last week Control Structures Selection Loops 2 Outline Subprograms Calling Sequences Parameter Passing
More informationLecture 7: General Loops (Chapter 7)
CS 101: Computer Programming and Utilization Jul-Nov 2017 Umesh Bellur (cs101@cse.iitb.ac.in) Lecture 7: General Loops (Chapter 7) The Need for a More General Loop Read marks of students from the keyboard
More informationCS 247: Software Engineering Principles. ADT Design
CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data
More informationChapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1
Chapter - 9 Variable Scope and Functions Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Variable Scope and Class Variables are defined by two attributes: Scope The area where a
More informationCompiler Construction
Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-17/cc/ Generation of Intermediate Code Outline of Lecture 15 Generation
More informationLecture Notes on Contracts
Lecture Notes on Contracts 15-122: Principles of Imperative Computation Frank Pfenning Lecture 2 August 30, 2012 1 Introduction For an overview the course goals and the mechanics and schedule of the course,
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,
More informationPointers and References
Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers
More informationEL6483: Brief Overview of C Programming Language
EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions
More informationProgramming, numerics and optimization
Programming, numerics and optimization Lecture A-2: Programming basics II Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428 March
More informationReading 8 : Recursion
CS/Math 40: Introduction to Discrete Mathematics Fall 015 Instructors: Beck Hasti, Gautam Prakriya Reading 8 : Recursion 8.1 Recursion Recursion in computer science and mathematics refers to the idea of
More information377 Student Guide to C++
377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationScope. Chapter Ten Modern Programming Languages 1
Scope Chapter Ten Modern Programming Languages 1 Reusing Names Scope is trivial if you have a unique name for everything: fun square a = a * a; fun double b = b + b; But in modern languages, we often use
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationProtection Levels and Constructors The 'const' Keyword
Protection Levels and Constructors The 'const' Keyword Review: const Keyword Generally, the keyword const is applied to an identifier (variable) by a programmer to express an intent that the identifier
More informationIntroduction to Programming in C Department of Computer Science and Engineering\ Lecture No. #02 Introduction: GCD
Introduction to Programming in C Department of Computer Science and Engineering\ Lecture No. #02 Introduction: GCD In this session, we will write another algorithm to solve a mathematical problem. If you
More informationThe American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science
The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Dr. Khalil Final Exam Fall 2013 Last Name :... ID:... First Name:... Form
More informationObject Oriented Design
Object Oriented Design Chapter 6 Example Activity Diagram 1 Outline Chapter 6 Topics 6.6 C++ Standard Library Header Files 6.14 Inline Functions 6.16 Default Arguments 6.17 Unary Scope Resolution Operator
More informationEngineering Tools III: OOP in C++
Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Why C++? C++ as a powerful and ubiquitous tool for programming of numerical simulations super-computers (and other number-crunchers)
More informationB16 Object Oriented Programming
B16 Object Oriented Programming Michael A. Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/teaching.html#b16 Hilary 2013 Topic 4: Constructors Recall our definition of the Complex class.
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationObject Oriented Software Design II
Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February
More informationProgramming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python
Programming Languages Streams Wrapup, Memoization, Type Systems, and Some Monty Python Quick Review of Constructing Streams Usually two ways to construct a stream. Method 1: Use a function that takes a(n)
More informationDiscussion 1E. Jie(Jay) Wang Week 10 Dec.2
Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the
More informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationIntroduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)
Introduction to C++ 1. General C++ is an Object oriented extension of C which was derived from B (BCPL) Developed by Bjarne Stroustrup (AT&T Bell Labs) in early 1980 s 2. A Simple C++ Program A C++ program
More informationArrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff
and Arrays Comp Sci 1570 Introduction to C++ Outline and 1 2 Multi-dimensional and 3 4 5 Outline and 1 2 Multi-dimensional and 3 4 5 Array declaration and An array is a series of elements of the same type
More informationCompiler Construction
Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-17/cc/ Generation of Intermediate Code Conceptual Structure of
More informationFORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):
FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere
More information(Refer Slide Time 01:41 min)
Programming and Data Structure Dr. P.P.Chakraborty Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture # 03 C Programming - II We shall continue our study of
More informationChapter Goals. Contents LOOPS
CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common
More informationC++ For Science and Engineering Lecture 12
C++ For Science and Engineering Lecture 12 John Chrispell Tulane University Monday September 20, 2010 Comparing C-Style strings Note the following listing dosn t do what you probably think it does (assuming
More informationComputer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview
Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring 2009 Topic Notes: C and Unix Overview This course is about computer organization, but since most of our programming is
More informationCh 4. Parameters and Function Overloading
2014-1 Ch 4. Parameters and Function Overloading March 19, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;
More informationPIC 10A Objects/Classes
PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous
More informationQUIZ. What are 3 differences between C and C++ const variables?
QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,
More informationa data type is Types
Pointers Class 2 a data type is Types Types a data type is a set of values a set of operations defined on those values in C++ (and most languages) there are two flavors of types primitive or fundamental
More informationVariable Definitions and Scope
Variable Definitions and Scope The scope of a variable is the part of the program where the variable may be used. For a variable defined inside a function, its scope is the function, from the point of
More informationUnderstanding C/C++ Strict Aliasing
Understanding C/C++ Strict Aliasing or - Why won't the #$@##@^% compiler let me do what I need to do! by Patrick Horgan There's a lot of confusion about strict aliasing rules. The main source of people's
More informationC++ Programming. Pointers and Memory Management. M1 Math Michail Lampis
C++ Programming Pointers and Memory Management M1 Math Michail Lampis michail.lampis@dauphine.fr Dynamic Memory Allocation Data in your program lives (mostly) in two areas The stack The heap So far, we
More informationExercise 1.1 Hello world
Exercise 1.1 Hello world The goal of this exercise is to verify that computer and compiler setup are functioning correctly. To verify that your setup runs fine, compile and run the hello world example
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions
More information7.1 Optional Parameters
Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default
More information