UMBC CMSC 104 – Section 01, Fall 2016

Slides:



Advertisements
Similar presentations
Fungsi Risanuri Hidayat, Ir., M.Sc.. Functions C usually consist of two things: instance variables and functions. All C programs consist of one or more.
Advertisements

Functions Quick Review What is a Function? A module of code that performs a specific job. Examples: Function that determines the maximum of two numbers.
CS 201 Functions Debzani Deb.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Computer Science 210 Computer Organization Introduction to C.
CMSC 1041 Functions II Functions that return a value.
CECS 121 Test 1. Functions allow you to group program statements under one name C and C++ are case-sensitive so main(), MAIN(), and Main() are all different.
Lecture 05 Functions II, Storage Class, Scope, rand() METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Functions Course conducted by: Md.Raihan ul Masood
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
INC 161 , CPE 100 Computer Programming
© 2016 Pearson Education, Ltd. All rights reserved.
Functions, Part 2 of 2 Topics Functions That Return a Value
Programming Fundamentals Lecture #7 Functions
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Chapter 5 - Functions Outline 5.1 Introduction
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 6 - Functions Outline 5.1 Introduction
Functions, Part 2 of 2 Topics Functions That Return a Value
Chapter 2 - Introduction to C Programming
Functions, Part 1 of 3 Topics Using Predefined Functions
Functions, Part 2 of 3 Topics Functions That Return a Value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Introduction to C Topics Compilation Using the gcc Compiler
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
A function with one argument
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Assignment Operators Topics Increment and Decrement Operators
Chapter 2 - Introduction to C Programming
Assignment Operators Topics Increment and Decrement Operators
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
A First Book of ANSI C Fourth Edition
UMBC CMSC 104 – Section 01, Fall 2016
Lesson #6 Modular Programming and Functions.
Introduction to C Topics Compilation Using the gcc Compiler
Functions, Part 1 of 3 Topics Using Predefined Functions
Chapter 2 - Introduction to C Programming
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Functions, Part 1 of 3 Topics Using Predefined Functions
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Assignment Operators Topics Increment and Decrement Operators
Functions, Part 2 of 3 Topics Functions That Return a Value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Functions, Part 2 of 42 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Functions that return a value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Presentation transcript:

UMBC CMSC 104 – Section 01, Fall 2016 Functions II

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

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)

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

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");

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);

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);

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 ; }

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 ;

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.

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.

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.

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 ; value1 value2 ave num1 num2 average 5 8 int int float int int float

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 ; num1 num2 average num1 num2 average 5 8 int int float int int float

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 5 OUTPUT int In AddOne: num1 = 6 In main: num1 = 5

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.

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

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 ;

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;

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;

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;

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;

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;

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);

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; }

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?

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!!! */

… 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);

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

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); }

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); }

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);

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

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;

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!

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;

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

Questions?