Functions and Recursion

Similar documents
C++ Programming Lecture 11 Functions Part I

Chapter 3 - Functions

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

4. C++ functions. 1. Library Function 2. User-defined Function

Introduction to C++ Introduction to C++ 1

Programming Language. Functions. Eng. Anis Nazer First Semester

Arrays. Week 4. Assylbek Jumagaliyev

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Functions and Recursion

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Chapter 2 - Control Structures

Floating-point numbers. Phys 420/580 Lecture 6

In this chapter you will learn:

Introduction to Programming

Function with default arguments

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Chapter 2 - Control Structures

Chapter 2 - Control Structures

1 #include <iostream > 3 using std::cout; 4 using std::cin; 5 using std::endl; 7 int main(){ 8 int x=21; 9 int y=22; 10 int z=5; 12 cout << (x/y%z+4);

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

An inline function is one in which the function code replaces the function call directly. Inline class member functions

Chapter 2 - Control Structures

Chapter 15 - C++ As A "Better C"

Chapter 3 - Functions

Computing and Statistical Data Analysis Lecture 3

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Shahram Rahatlou. Static Data Members Enumeration std::pair, std::vector, std::map. Computing Methods in Physics

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and Recursion

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

EP578 Computing for Physicists

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

A SHORT COURSE ON C++

Computer Science II Lecture 2 Strings, Vectors and Recursion

Lab Instructor : Jean Lai

C Functions. Object created and destroyed within its block auto: default for local variables

Separate Compilation of Multi-File Programs

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

University of Dublin

Determination of Maximum Likelihood: Iterative Approaches PROJECT REPORT

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Introduction to C++ Systems Programming

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

1st Midterm Exam: Solution COEN 243: Programming Methodology I

Control Statements: Part Pearson Education, Inc. All rights reserved.

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

CS242 COMPUTER PROGRAMMING

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Computer Science II Lecture 1 Introduction and Background

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors

Streams. Ali Malik

CS201 Solved MCQs.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

C++ Programming: From Problem Analysis to Program Design, Third Edition

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

C, C++, Fortran: Basics

C++ basics Getting started with, and Data Types.

3.1. Chapter 3: The cin Object. Expressions and Interactivity

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

Engineering Problem Solving with C++, Etter/Ingber

Summary of basic C++-commands

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

Introduction. Program construction in C++ for Scientific Computing. School of Engineering Sciences. Introduction. Michael Hanke.

The following is a typical execution run of this program:

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Faculty of Science, Engineering and Technology

The American University in Cairo Department of Computer Science & Engineeringt CSCI &09 Dr. KHALIL Exam-I Fall 2009

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Chapter 3 - Functions

Today s class. Roots of equation Finish up incremental search Open methods. Numerical Methods, Fall 2011 Lecture 5. Prof. Jinbo Bi CSE, UConn

Sample Code: OUTPUT Daily Highs & Lows

Introduction to Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CS 101 Computer Programming and Utilization. Lecture 5, More Numerical computing (Slides courtesy Prof Ranade)

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

do { statements } while (condition);

Classes and Data Abstraction. Topic 5

Name SECTION: 12:45 2:20. True or False (12 Points)

Chapter 17 - Notes Recursion

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

Transcription:

Functions and Recursion 1 some useful problems

2 Function: power Power iteration Power recursive

#include <iostream> #include <cmath> 3 using std::cout; using std::cin; using std::endl; // function prototype long poweriteration(int, int); long powerrecursive(int, int); int main() int x, y; long result; cout << "Enter an integer number"<<endl; cin >> x; cout<< "Enter the power you want to raise your number at: " << endl; cin >> y; result = poweriteration(x,y); cout<< x << " to the power "<< y<< " is ((using iterative method)) " << result << endl; cout << endl; result = powerrecursive(x, y); cout<< x << " to the power "<< y<< " is ((using recursive method)) " << result << endl; cout << endl; return 0;

long poweriteration (int number, int exponent) int x, y; long result = 1; x = number; y = exponent; 4 if (y==0) return 1 else for (int i=1; i<=y; i++) result = result*x; return result;

long powerrecursive (int number, int exponent) int x, y; long result = 1; x = number; y = exponent; 5 if (y==0) return 1; else result = x*powerrecursive(x, y-1); return result;

6 Function: exponential e x = 1 + x/1! + x 2 /2! + x 3 /3! +.. (Taylor expansion) e = 1 + 1/1! + 1/2! + 1/3! +.. Where do you stop the summation? Until the final result is achieved! Result is achieved if the difference between current result and the result from previous iteration is very small (accuracy is user-defined)

#include <iostream> #include <math.h> using std::cout; using std::endl; using std::fixed; #include <iomanip> using std::setprecision; int factorial(int); int main() int number = 1; int counter = 1; int fact; double e_old, e_new; double err = 1; e_old = 1; while (err >= 1.0e-10) factorial = fact(number) e_new = e_old + static_cast<double>(1.0)/ factorial; number = number + 1; err = fabs(e_new - e_old); // update error e_old = e_new; cout<<setprecision(10)<<fixed<<e_new<<endl;; return 0; 7

////////////////////////// // compute fact(counter)// ////////////////////////// int factorial(int nb) int fact = 1; counter = nb; if (nb == 0) (nb == 1) return 1; else while (counter>=1) fact = fact*counter; counter = counter -1; return fact; 8

9 Function: sine sin(x)= x x 3 /3! + x 5 /5! x 7 /7! +.. (Taylor expansion)

#include <iostream> #include <math.h> using std::cout; using std::endl; using std::fixed; #include <iomanip> using std::setprecision; int factorial(int); int main() float number, fact; cout<<"enter a number: "<<endl; cin>>number; int counter = 1; double err = 1; double sine_old, sine_new; sine_old = number; int sign = -1; while (err >= 1.0e-10) counter = counter+2; fact = factorial(counter); sine_new = sine_old + sign*pow(number, counter)/fact; sign = sign*(-1); // change sign err = fabs(sine_new - sine_old); // compute the error sine_old = sine_new; // update sine_old cout<<setprecision(10)<<fixed<<sine_new<<endl;; return 0; 10

////////////////////////// // compute fact(counter)// ////////////////////////// int factorial(int nb) int fact = 1; counter = nb; if (nb == 0) (nb == 1) return 1; else while (counter>=1) fact = fact*counter; counter = counter -1; return fact; 11

12 Newton-Raphson method In numerical analysis, Newton's method (or the Newton Raphson method or the Newton Fourier method) is an efficient algorithm for finding approximations to the zeros (or roots) of a realvalued function, f(x). Start with an arbitrary value x 0 (the closer to the zero the better) and then define for each natural number n: Newton's method will usually converge provided the initial guess is close enough to the unknown zero

13 Newton-Raphson method Try to solve for the roots of: f(x) = ax 2 +bx+c Example: sqrt(9) f(x) = x 2-9 = 0 (i.e., a = 1, b=0, c = -9) Start with initial guess: x 0 Compute the new approximation: x 1 = x 0 f(x 0 )/f (x 0 ) Use x 1 to compute the new approximation x 2 = x 1 f(x 1 )/f (x 1 ) Use x n to compute the new approximation X n+1 = x n f(x n )/f (x n ) When do you stop? When the difference between the two approximations is very small

#include <iostream> using namespace std; 14 using std::cout; using std::cin; using std::endl; #include <cmath> void sq_root (float, float, float, float); int main() float a, b, c, x0; cout << "Enter values for a, b, and c :"; cin >> a >> b >> c; cout << "Enter a guess for the root :"; cin >> x0; sq_root (a, b, c, x0); return 0;

void sq_root (float a, float b, float c, float guess) float x1, x0, delta; int iters = 0; x0 = guess; 15 delta = 1.0; // set delta for first iteration while (delta >.00001) x1 = x0 - (a*x0*x0 + b*x0 + c) / ( 2*a*x0 + b); delta = fabs ( x1 - x0 ); x0 = x1; // new approximation becomes the old approximation // for the next iteration iters++; // count the number of iterations cout << "One root is " << x1 << endl; cout << "Found in " << iters << " iterations" << endl;