# CS156 Functions: Fully Functional

Some slides from Syracuse University

# Functions

• What are functions?
• Complete blocks of code that perform a specific task
• We know how to call a function: `printf("Hello World!\n");`
• Functions can return a value, or not:
```#include <stdio.h>
#include <math.h>
int main() {
printf("square root of 5 is %f\n", sqrt(5.0));
printf("2½ cubed is %f\n", pow(2.5, 3));
return 0;
}
```
```square root of 5 is 2.236068
2½ cubed is 15.625000
```

# Not Methods

• These are functions, not methods.
• A method is a function within a class.
• C doesn’t do classes.

# Functions: A Motivating Example

• Print the area and perimeter of two rectangles.
```#include <stdio.h>
int main() {
float sideA=1.2, sideB=2.1;
float sideA2=2.2, sideB2=3.0;
printf("Area is %f\n", sideA*sideB);
printf("Perimeter is %f\n", 2*(sideA+sideB));
printf("Area is %f\n", sideA2*sideB2);
printf("Perimeter is %f\n", 2*(sideA2+sideB));
return 0;
}
```
```Area is 2.520000
Perimeter is 6.600000
Area is 6.600000
Perimeter is 8.600000
```
• Can you see the error?

# Functions

• Functions allows us to write a piece of code once and reuse it.
• Functions decrease the amount of code that needs to be written and can make code easier to understand.
• Also, functions help reduce errors like the one in the previous example.
• They are the first step towards the structured programming style.

# An Example

```#include <stdio.h>

void printAreaAndPerimeter(float a, float b){
printf("Area is %f\n", a*b);
printf("Perimeter is %f\n", 2*(a+b));
}

int main() {
float sideA = 1.2, sideB = 2.1;
float sideA2 = 2.2, sideB2 = 3.0;
printAreaAndPerimeter(sideA, sideB);
printAreaAndPerimeter(sideA2, sideB2);
return 0;
}
```
```Area is 2.520000
Perimeter is 6.600000
Area is 6.600000
Perimeter is 10.400000
```

# Some Functions We’ve Seen

• `main` — can take two arguments or none and returns an `int`
• `printf` — takes a string and a list of variables as arguments
• `scanf` — reads in values, stores them to variables

# Functions

• To call a function:
functionName(data, data, data);
• The data passed to the function can be variables, constants, or expressions:
`printf("%d %d %d", x, 9, x*3+15);`
• To declare a function:
returnType functionName(arguments);
`double power(double value, int n);`
• returnType: type we want to return (`int`, `void`, …)
• functionName: the name of the function
• arguments: declaration of argument variables
These variables contain the data passed to the function

# Functions

• How to define a function:
```returnType functionName(list of arguments) {
statement1;
statement2;
…
return expression;      // value to return
}
```
• If the function returns an `int`, its return type is `int`.
• If the function returns an `float`, its return type is `float`.
• If the function returns no value, the return type is `void`.
• Function names are follow the same rules as variable names.

# How to call a function

Examples of function calls:

```printf("hi there\n");
hypot = sqrt(a*a+b*b);
z = fun1('x', 2+2, x*37, "hello");
fun2(x, &y, 3.4-z);
```

Don't specify the types of the arguments when calling a function—only when you declare or define it.

# Function Placement

 ```Preprocessor directives function defintions int main() { declarations & statements return value; } ``` ```#include int abs(int a) { if (a < 0) return -a; return a; } int main() { int n = -25; printf("%d\n", abs(n)); return 0; } ```

# Functions

Another way to do it:

 ```Preprocessor directives function prototypes int main() { declarations & statements return value; } function definitions ``` ```#include int abs(int); int main() { int n = -25; printf("%d\n", abs(n)); return 0; } int abs(int a) { if (a < 0) return -a; return a; } ```

# Functions

```int abs(int);
int power(int base, int n);
```
• Prototypes
• No body to the function!
• Before `main` function

```int abs(int a) {
if ( a < 0 )
return -a;
return a;
}
int power(int base, int n) {
int p = 1;
for (int i=1; i<=n; i++)
p *= base;
return p;
}
```
• Definitions
• Full function with header and squigglies.
• Body of function defined
• After `main` function

# Declaration and Definition - Example

```    // Function declarations (alias prototypes)
void printAreaAndPerimeter(float a, float b);

int main() {
…
}

void printAreaAndPerimeter(float a, float b){
printf("Area is %f\n", a*b);
printf("Perimeter is %f\n", 2*(a+b));
}
```

# Functions

```    #include <stdio.h>

int power(int base, int n);

int main( ) {
int a, b, p;

printf("Enter the base ");
scanf("%d", &a);
printf("Enter the exponent ");
scanf("%d", &b);
p = power(a, b);
printf("The power is  %d\n ", p);
return 0;
}

int power(int base, int n) {
int p = 1;
for (int i=1; i<=n; i++)
p *= base;
return p;
}
```

# Function Arguments

Declaring a function prototype:

```returnType functionName(list of arguments);
```
• Arguments are the items enclosed in parenthesis in the call statement of a function
• Arguments are also called parameters
• Arguments are passed by value

# Function Arguments: passed-by-value

```#include <stdio.h>
int power(int base, int n);
int main( ) {
int a = 5, b = 2, p;
p = power( a, b);
…
}
int power(int base, int n) {
int p = 1;
for (int i=1; i<=n; i++)
p *= base;
return p;
}
```
• Function `main` has three variables: `a`, `b`, `p`
• Function `power` has three variables: `base`, `n`, `p`
• `base``a`
• `n``b`
• If `a` = 5 and `b` = 2, `base` gets a copy of 5 and `n` gets a copy of 2

# Passing Arguments

```void foo(int a, int b){
a = 3;
b = 10;
}
int main(){
int a=2, b=0;
foo(a,b);
return 0;
}
```
• C uses pass-by-value style functions. All arguments are copied, and the copies are passed into the function.
 Memory `main` `a` 2 `b` 0 `foo` `a` 3 `b` 10
• Better to use different variable names to avoid confusion.

# Passing Arguments

```void changeA(int a) {
printf("changeA:a=%d\n", a);
a = 1000006;
printf("changeA:a=%d\n", a);
}

int main(){
int a = 12;
printf("a=%d\n", a);
changeA(a);
printf("a=%d\n", a);
}
```
```a=12
changeA:a=12
changeA:a=1000006
a=12
```
• Any modification to the arguments does not affect the values of the variables used in the function call.

# Functions with No Arguments

• Not all functions need to take arguments or return a value.
```// define a function with no arguments or return value
void doNothing(){
}

int main() {
doNothing();
return 0;
}
```
• This can be useful for printing a large block of fixed output to the screen.

# Commenting Functions

• To keep code with functions understandable it is useful to provide comments describing the input, output, and purpose of a function.
• The comments should describe the type of the input and any constraints the input should obey.
• These comments are usually placed just before the declaration of the function.
• The function body itself should also be commented

# Commenting Functions

```// Prints the area and perimeter
// PRE: a and b are floating-pt numbers
// POST: area and perimeter values printed, nothing returned
void printAreaAndPerimeter(float a, float b) {
float area = a*b;
float perimeter = 2*(a+b);
printf("Area of (%f,%f) is %f, perimeter is %f\n",
a, b, area, perimeter);
}
```
• Inputs designated with either Input: or Pre: (Pre-conditions)
• Outputs designated with either Output: or Post: (post-conditions)

# Commenting Functions

```/*
* Multiplies two numbers and returns product
* Input: num1 and num2 are integers to be multiplied
* Output: product returned
*/
int multiply(int num1, int num2 ) {
return num1 * num2 );
} // end multiply
```
• Inputs designated with either Input: or Pre: (Pre-conditions)
• Outputs designated with either Output: or Post: (post-conditions)

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-03-08T14:07

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA