Section 12.1 Single Functions
You have already seen the use of a function in C, namely the
main() function! We donโt tend to think of
main() as a function but it is indeed one.
Functions allow you to group a bunch of statements together that can be called upon to execute at any point in your code. Depending on the type of function you write, you can pass information to the function and it can return information back to you.
Here is a first example of a function in C:
If you cannot see this codecast, please click here .
Aside: Video Description.
Writing functions
Calling functions
NEW SYNTAX: the following is the function prototype for a function that takes in two integers, x and y, and returns one integer (this return integer could be anything but we are going to return the sum of x and y).
int sum (int x, int y);
NEW SYNTAX: the body (that is, the set of instructions to be executed when calling the function) of the function "sum" comes after the main function ends. This is called the function definition and it starts out the same way as the prototype, except for the semi-colon ; at the end of the prototype. After that initial line come curly brackets {}, which enclose the (potentially) multi-line body of the function.
int sum (int x, int y){ };
c = sum(a,b)
Check Your Understanding Check Your Understanding
1.
Please add the correct prototype for the
square() function to the program below:
admin ..... open in new window
When your program performs correctly youโll be given a keyword to enter in Canvas.
2.
Write a function
divide() that takes two floats as arguments and returns a float, namely the first number divided by the second. Obviously, you shouldnโt be dividing by zero...
You may assume that your function is not called with such input.
admin ..... open in new window
When your program performs correctly youโll be given a keyword to enter in Canvas.