1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Chapter 7: User-Defined Functions II
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
Functions a group of declarations and statements that is assigned a name effectively, a named statement block usually has a value a sub-program when we.
Chapter 6: User-Defined Functions I
1 Gentle Introduction to Programming Session 2: Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
TK1913-C Programming1 TK1913-C Programming 1 C Library Functions C provides a collection of library functions for programmers If these library functions.
CS 201 Functions Debzani Deb.
Programming Functions. A group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a value A sub-program.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
1 Gentle Introduction to Programming Session 2: Functions.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Lecture 6 – Functions (2). Outline Recall - sample application functions that return no value functions that return a value Recall – global variable vs.
1. Function prototype Function prototype is a declaration; indicates the function exists Should have function name, return type and parameter Placed before.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
FUNCTIONS AND STRUCTURED PROGRAMMING CHAPTER 10. Introduction A c program is composed of at least one function definition, that is the main() function.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
1 Programming a Computer Lecture Ten. 2 Outline  A quick introduction to the programming language C  Introduction to software packages: Matlab for numerical.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions What is a function –“sub” program, with an isolated set of statements –Accepts parameters, returns a result (perhaps) –Think of it as its own.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Program Development and Design Using C++, Third Edition
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
C Programming.
UMBC CMSC 104 – Section 01, Fall 2016
C++ Laboratory Instructor: Andrey Dolgin
Functions Course conducted by: Md.Raihan ul Masood
Chapter 6: User-Defined Functions I
Programming Functions.
Functions, Part 2 of 2 Topics Functions That Return a Value
Functions Dr. Sajib Datta
Functions Department of Computer Science-BGU יום רביעי 12 ספטמבר 2018.
CSCI 161: Introduction to Programming Function
Functions.
User-Defined Functions
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
Functions, Part 2 of 3 Topics Functions That Return a Value
A function with one argument
Chapter 6: User-Defined Functions I
Function.
In C Programming Language
Introduction to Problem Solving and Programming
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
Function.
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Functions that return a value
Presentation transcript:

1 Today: Functions

2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process

3 Some General Tips on Programming (Cont.) Use Debugger or printf to follow your execution flow and find what went wrong Understanding is good but not enough – you must practice!

4 Functions a group of declarations and statements that is assigned a name effectively, a named statement block usually has a value a sub-program when we write our program we always define a function named main inside main we can call other functions which can themselves use other functions, and so on…

5 What are They Good For? generalize a repeated set of instructions we don’t have to keep writing the same thing over and over they can break your problem down into smaller sub-tasks easier to solve complex problems they make a program much easier to read and maintain abstraction – we don’t have to know how a function is implemented to use it

6 Example - Square #include double square(double a) { return a*a; } int main(void) { double num; printf("enter a number\n"); scanf("%lf",&num); printf("square of %g is %g\n",num,square(num)); return 0; } This is a function defined outside main Here is where we call the function square

7 Functions Template return-type name(arg_type1 arg_name1, arg_type2 arg_name2, …) { function body; return value; } double square(double a) { return a*a; } int main(void) { … }

8 Return Statement Return causes the execution of the function to terminate and usually returns a value to the calling function The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type) If no value is to be returned, the return-type of the function should be set to ‘void’

9 Example: Factorial #include int factorial(int n) { int i, fact = 1; for (i=2; i<=n; i++) fact *= i; return fact; } int main(void) { int num; printf("enter a number\n"); scanf("%d",&num); printf("%d!=%d\n",num,factorial(num)); return 0; }

10 A Detailed Example Write a program that receives a nominator and a denominator from the user, and displays the reduced form of the number. For example, if the input is 6 and 9, the program should display 2/3.

11 Example – solution (step I) #include int main(void) { int n, d; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); Calculate n’s and d’s Greatest Common Divisor printf("The reduced form of %d/%d is %d/%d", n, d, n/gcd, d/gcd); return 0; }

12 Example – solution (step II) #include int main(void) { int n, d, g; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form of %d/%d is %d/%d", n, d, n/g, d/g); return 0; }

13 Example – solution (step III) /* Returns the greatest common divisor of its two parameters. Assumes both are positive. */ int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; }

14 GCD – step by step int main(void) { int n, d, g; printf("Please enter … : "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form…", n, d, n/g, d/g); return 0; } ndg 69---

15 GCD – step by step int main(void) { int n, d, g; printf("Please enter … : "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form…", n, d, n/g, d/g); return 0; } ndg 69---

16 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 69---

17 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 696

18 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 696

19 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 695

20 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 695

21 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 694

22 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 694

23 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 693

24 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 693

25 GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } xy i 693

26 GCD – step by step int main(void) { int n, d, g; printf("Please enter … : "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form…", n, d, n/g, d/g); return 0; } ndg 693

27 Example – Complete Solution gcd.c

28 Exercise: Fibonacci Input: An integer n Output: The n’th fibonacci number Note – Use an appropriately defined function

29 Solution fibonacci_func.c

30 Example Write a program that gets a positive integer from the user and prints all the prime numbers from 2 up to that integer. (Use a function that returns 1 if its parameter is prime, 0 otherwise)

31 Solution is_prime_func.c

32 Exercise Newton was the first to notice that for any positive n, and when x 0 =1, the following series converges to sqrt(n) – Use this fact to write a program that accepts a positive number and outputs its square root Hint – the thousandth element of Newton’s series is a good-enough approximation

33 Solution sqrt.c

34 Void When there’s no reason for a function to return a value the function’s return type should be ‘void’ Calling ‘return’ in a function returning void is not obligatory If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified If the function receives no parameters, the parameter list could be replaced by ‘void’

35 Example: Show Help void ShowHelp(void) { printf("This function explains what this program does…\n"); printf("Yadayadayada"); /* …. */ } int main(void) { char choice; printf("Please enter your selection: "); scanf("%c", &choice); if (choice==‘h’) ShowHelp(); else if /* Program continues … */ }

36 Pass-By-Value copying Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables will not change A change to the value of an argument in a function body will not change the value of variables in the calling function Example – add_one.c

37 add_one – step by step int add_one(int b) { b=b+1; return b; } int main(void) { int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; } ab 341 Main() memory state

38 add_one – step by step int add_one(int b) { b=b+1; return b; } int main(void) { int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; } ab 341 Main() memory state

39 add_one – step by step int add_one(int b) { b=b+1; return b; } int main(void) { int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; } ab 341 Main() memory state b 1 add_one memory state

40 ab 341 Main() memory state add_one – step by step int add_one(int b) { b=b+1; return b; } int main(void) { int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; } b 2 add_one memory state

41 ab 341 Main() memory state add_one – step by step int add_one(int b) { b=b+1; return b; } int main(void) { int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; } b 2 add_one memory state

42 add_one – step by step int add_one(int b) { b=b+1; return b; } int main(void) { int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; } ab 21 Main() memory state

43 add_one – step by step int add_one(int b) { b=b+1; return b; } int main(void) { int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; } ab 21 Main() memory state

44 What will be Printed Here? #include int factorial(int n) { int fact = 1; while (n>1) { fact *= n; n--; } return fact; } int main(void) { int n; printf("enter a number\n"); scanf("%d",&n); printf("%d!=%d\n", n, factorial(n)); /* What will this print? */ printf( "n = %d\n", n); return 0; }

45 Scope of Variables A variable declared within a function is unrelated to variables declared elsewhere (even if they share the same name) A function cannot access variables that are declared in other functions Example – scope.c

46 Example: Error in Scope int add_one(int b) { a=b+1; return a; } int main(void) { int a=34,b=1; add_one(b); printf("a = %d, b = %d\n", a, b); return 0; }

47 Function Declaration Most software projects in C are composed of more than one file We want to be able to define the function in one file, and to use it in all files declared For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time the declaration contains: the function name the data types of the arguments (their names are optional) the data type of the return value

48 Function Declaration #include int factorial(int a); /* Function Declaration! */ int main(void){ int num; printf("enter a number\n"); scanf("%d",&num); printf("%d!=%d\n",num,factorial(num)); return 0; } int factorial(int a){ int i,b=1; for(i=1; i<=a; i++) b=b*i; return b; }

49 Function Declaration stdio.h actually contains a large set of function declarations The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called

50 The math Library A collection of mathematical functions Need to include the header file math.h (#include ) Use functions of the library, e.g. double s,p; s=sqrt(p); Declared in math.h : double sqrt ( double x ); Content: Google: math C

51 The math Library: Content sin(x), cos(x), tan(x) x is given in radians asin(x), acos(x), atan(x) log(x) sqrt(x) pow(x,y) – raise x to the yth power. ceil(x), floor(x) …and more

52 Exercise Write a function that uses the formula  2 /6=1/1+1/4+1/9+1/16+…+1/n 2 (where n goes to infinity) in order to approximate . The function should accept an argument n which determines the number of terms in the formula. It should return the approximation of . Write a program that gets an integer n from the user, and approximate  using n terms of the above formula.

53 Solution pi.c

54 Exercise Modify the previous function that approximates . The function should accept an argument specifying the desired accuracy, and keep adding terms until the contribution of the next term drops below this level. Write a program that gets a (small) double, epsilon, from the user, and approximates  within this function.

55 Solution pi_eps.c