Presentation is loading. Please wait.

Presentation is loading. Please wait.

UMBC CMSC 104 – Section 01, Fall 2016

Similar presentations


Presentation on theme: "UMBC CMSC 104 – Section 01, Fall 2016"— Presentation transcript:

1 UMBC CMSC 104 – Section 01, Fall 2016
Functions II

2 Notes & Announcements Project 7 due before next class!
Posted Extra Credit for Project 7 Next Slide… Happy Thanksgiving!

3 Project 7 Extra Credit A twin prime is a prime number that is either two less or two more than another prime number -- for example, the twin prime pair (41,43). Write a program called campusid_twinprime.c that prompts the user to enter a minimum and maximum integer in the range 1 and 10,000. If the user enters an invalid range, they should be prompted again. Once a valid range has been entered, the program should print all the twin prime pairs in the given range. The following is example output for the minimum value 4 and maximum value 20: (5,7) (11,13) (17,19)

4 Quick Review of Functions
Functions contain repeatable code that can be called from other functions All C programs start with the main() function Functions may take one or more arguments, or may not take any arguments Functions may call other functions By convention, the main() method should be first in the file You must place a function prototype for each of your functions before the main() method

5 A Simple Function #include <stdio.h> void SayHello(); int main() { int i; for(i = 0 ; i < 10 ; i++) SayHello(); } return 0; void SayHello() printf("Hello!\n");

6 A Little More Complicated
#include <stdio.h> void PrintNumber(int num); int main() { int i; for(i = 0 ; i < 10 ; i++) PrintNumber(i); } return 0; void PrintNumber(int num) printf("I've got number %d!\n", num);

7 How About This? #include <stdio.h> void PrintNumber(int num); int main() { int num = 1; PrintNumber(num); num++; return 0; } void PrintNumber(int num) num += 5; printf("I've got number %d!\n", num);

8 Functions Can Return Values!
/**************************************************************************** ** AverageTwo - calculates and returns the average of two numbers ** Inputs: num1 - an integer value ** num2 - an integer value ** Outputs: the floating point average of num1 and num2 *****************************************************************************/ float AverageTwo (int num1, int num2) { float average ; /* average of the two numbers */ average = (num1 + num2) / 2.0 ; return average ; }

9 Using AverageTwo #include <stdio.h>
float AverageTwo (int num1, int num2) ; int main ( ) { float ave ; int value1 = 5, value2 = 8 ; ave = AverageTwo (value1, value2) ; printf (“The average of %d and %d is %f\n”, value1, value2, ave) ; return 0 ; } float AverageTwo (int num1, int num2) float average ; average = (num1 + num2) / 2.0 ; return average ;

10 Parameter Passing Actual parameters are the parameters that appear in the function call. average = AverageTwo (value1, value2) ; Formal parameters are the parameters that appear in the function header. float AverageTwo (int num1, int num2) Actual and formal parameters are matched by position. Each formal parameter receives the value of its corresponding actual parameter.

11 Parameter Passing (con’t)
Corresponding actual and formal parameters do not have to have the same name, but they may. Corresponding actual and formal parameters must be of the same data type, with some exceptions.

12 Local Variables Functions only “see” (have access to) their own local variables. This includes main( ) . Formal parameters are declarations of local variables. The values passed are assigned to those variables. Other local variables can be declared within the function body.

13 Parameter Passing and Local Variables
#include <stdio.h> float AverageTwo (int num1, int num2) float AverageTwo (int num1, int num2) ; { int main ( ) float average ; { float ave ; average = (num1 + num2) / 2.0 ; int value1 = 5, value2 = 8 ; return average ; } ave = AverageTwo (value1, value2) ; printf (“The average of “) ; printf (“%d and %d is %f\n”, value1, value2, ave) ; return 0 ; value value ave num num average int int float int int float

14 Same Name, Still Different Memory Locations
#include <stdio.h> float AverageTwo (int num1, int num2) float AverageTwo (int num1, int num2) ; { int main ( ) float average ; { float average ; average = (num1 + num2) / 2.0 ; int num1 = 5, num2 = 8 ; return average ; } average = AverageTwo (num1, num2) ; printf (“The average of “) ; printf (“%d and %d is %f\n”, num1, num2, average) ; return 0 ; num num average num num average int int float int int float

15 Changes to Local Variables Do NOT Change Other Variables with the Same Name
#include <stdio.h> void AddOne (int number) ; void AddOne (int num1) { int main ( ) num1++ ; { printf (“In AddOne: “) ; int num1 = 5 ; printf (“num1 = %d\n”, num1) ; AddOne (num1) ; } printf (“In main: “) ; printf (“num1 = %d\n”, num1) ; num1 return 0 ; } int num1 OUTPUT int In AddOne: num1 = 6 In main: num1 = 5

16 Header Files Header files contain function prototypes for all of the functions found in the specified library. They also contain definitions of constants and data types used in that library.

17 Commonly Used Header Files
Header File Contains Function Prototypes for: <stdio.h> standard input/output library functions and information used by them <math.h> math library functions <stdlib.h> conversion of numbers to text, text to numbers, memory allocation, random numbers, and other utility functions <time.h> manipulating the time and date <ctype.h> functions that test characters for certain properties and that can convert case <string.h> functions that manipulate character strings others see Chapter 5 of text

18 Using Header Files #include <stdio.h> #include <stdlib.h>
#include <math.h> int main ( ) { float side1, side2, hypotenuse ; printf(“Enter the lengths of the right triangle sides: “) ; scanf(“%f%f”, &side1, &side2) ; if ( (side1 <= 0) || (side2 <= 0) exit (1) ; } hypotenuse = sqrt ( (side1 * side1) + (side2 * side2) ) ; printf(“The hypotenuse = %f\n”, hypotenuse) ; return 0 ;

19 int randomNumber = rand % n;
Random Numbers! If you include <stdlib.h>, you can call the rand() function, which returns a random number between 1 and a #defined value RAND_MAX You can generate a random number between 0 and n-1 using the following: int randomNumber = rand % n;

20 Printing Some Random Numbers
#include <stdio.h> #include <stdlib.h> int main() { int i; for(i = 0 ; i < 5 ; i++) printf("%d\n", rand() % 100); } return 0;

21 How is this different? #include <stdio.h> #include <stdlib.h> int main() { int i; for(i = 0 ; i < 5 ; i++) printf("%d\n", (rand() % 100) + 1); } return 0;

22 Flipping A Coin 10 Times #include <stdio.h> #include <stdlib.h> int FlipCoin(); int main() { int i; for(i = 0 ; i < 10 ; i++) switch(FlipCoin()) case 0: printf("Heads!\n"); break; case 1: printf("Tails!\n"); } return 0; int FlipCoin() return rand() % 2;

23 Functions Can Call Themselves
#include <stdio.h> int Factorial(int a); int main() { printf("%d factorial is %d!\n", 6, Factorial(6)); return 0; } int Factorial(int a) if (a > 1) return (a * Factorial(a-1)); else return 1;

24 Let’s Revisit This… #include <stdio.h> void PrintNumber(int num); int main() { int i; for(i = 0 ; i < 10 ; i++) PrintNumber(i); } return 0; void PrintNumber(int num) printf("I've got number %d!\n", num);

25 The Same Code Without Functions
#include <stdio.h> void PrintNumber(int num); int main() { printf("I've got number 0!\n"); printf("I've got number 1!\n"); printf("I've got number 2!\n"); printf("I've got number 3!\n"); printf("I've got number 4!\n"); printf("I've got number 5!\n"); printf("I've got number 6!\n"); printf("I've got number 7!\n"); printf("I've got number 8!\n"); printf("I've got number 9!\n"); return 0; }

26 x2 + 3x – 4 = 0 Solve For x! Given: What is the value of x?
Can we make a generic solution? Can we turn that generic solution into a C program?

27 I Know C, but not Math!!! #include <stdio.h>
float QuadraticFormula(float a, float b, float c); int main() { float a, b, c; printf("What is the value of a, b, and c? "); scanf("%f%f%f", &a, &b, &c); printf("Answer = %g\n", QuadraticFormula(a, b, c)); return 0; } float QuadraticFormula(float a, float b, float c) /* I don’t know math!!! */

28 … have the Math guy fill it in!
#include <stdio.h> #include <math.h> float QuadraticFormula(float a, float b, float c); int main() { float a, b, c; printf("What is the value of a, b, and c? "); scanf("%f%f%f", &a, &b, &c); printf("Answer = %g\n", QuadraticFormula(a, b, c)); return 0; } float QuadraticFormula(float a, float b, float c) return ((-b + sqrt((b*b) - 4*a*c)) / 2 * a);

29 gcc -Wall -ansi -lm code.c
Using math.h If you want to include math.h, you usually have to pass gcc an additional flag (-lm) on compilation. For example: gcc -Wall -ansi -lm code.c

30 But What’s Missing? This works, but something’s missing…
The formula calls for ± We can’t return two values from a function… How could we get both results, not just +? float QuadraticFormula(float a, float b, float c) { return ((-b + sqrt((b*b) - 4*a*c)) / 2 * a); }

31 But What’s Missing? What if we added a multiplier parameter?
Definitely need a comment to describe how it works! /************************************** ** Inputs: a, b, c: Respective values from equation ** plusOrMinus: Multiplier for the plus/minus ** piece of the equation. Valid ** values are 1 (for plus) or -1 ** (for minus) ** Outputs: The equation result **************************************/ float QuadraticFormula(float a, float b, float c, int plusOrMinus) { return ((-b + plusOrMinus * sqrt((b*b) - 4*a*c)) / 2 * a); }

32 And again with the ± #include <stdio.h> #include <math.h> float QuadraticFormula(float a, float b, float c, int plusOrMinus); int main() { float a, b, c; printf("What is the value of a, b, and c? "); scanf("%f%f%f", &a, &b, &c); printf("Answer = %g & %g\n", QuadraticFormula(a, b, c, 1), QuadraticFormula(a, b, c, -1)); return 0; } float QuadraticFormula(float a, float b, float c, int plusOrMinus) return ((-b + plusOrMinus * sqrt((b*b) - 4*a*c)) / 2 * a);

33 How Would We…? Write a function that takes an integer x and raises it to the integer y power Lets use an example… 23 = 2 * 2 * 2 = 8

34 One Way To Do It… int Exponent(int base, int raisedTo) { int i; int result = 1; for(i = 1 ; i <= raisedTo ; i++) result *= base; } return result;

35 How About Without A Loop?
The for/while loop solution works, but what if I said you have to do it without a loop? Remember, functions can call themselves!

36 The Recursive Solution
int Exponent(int base, int raisedTo) { int result; if(raisedTo == 0) result = 1; } else result = base * Exponent(base, raisedTo - 1); return result;

37 Recursive vs Iterative
Any recursive function can be rewritten as iterative But often the recursive version is shorter and easier to understand!

38 Questions?


Download ppt "UMBC CMSC 104 – Section 01, Fall 2016"

Similar presentations


Ads by Google