Introduction to Programming
Functions
Functions are sections of your program that can be called from somewhere else.
They're like a pre-packaged bundle of instructions that you can run at any time,
or multiple times, in your program. You've already written one function, called
main. This function is always called first thing when you run your program. You've
also called other functions, like printf. Now we can write our own new function,
and call it from main.
int compute_the_square(int x)
{
int y;
y = x * x;
return y;
}
Put the above code between #include and main, and you'll be able to call it from main.
Now try adding these lines inside your main function:
printf("5 squared is: %d\n", compute_the_square(5));
printf("10 squared is: %d\n", compute_the_square(10));
Now try computing the square of a number you get from the user. Try computing a square,
and then computing the square of the result. Try squaring something 5 times, printing out
the result of each squareing. Do you understand how this function works now?
Syntax
The syntax of defining a function follows. Type yellow text
exactly, and replace blue text with something else.
return_type function_name(argument_type argument_name, argument_type argument_name, ...)
{
instructions...
return return_value;
}
The first thing to do when defining a function is to give the return type. This is
the type of value that your function will give back to whoever called it. So if you want
a function that's going to calculate a whole number, make the return type int. Next comes
the name of the function. This is like a variable name: any combination of letters, numbers,
and underscores _ as long as it doesn't start with a number. There can be no spaces in a
function name. Finally, the list of arguments in parenthases (). Each argument needs a type
and a name (just like variables). The arguments are separated by commas. After all of that,
a pair of curly brackets {} contain the actual instructions of your function.
Okay. the compute_the_square example function has one argument. Let's make a funciton
with two arguments, that does something a little more complicated:
int power(int base, int exponent)
{
int result, counter;
if (exponent < 0)
{
printf("I can't handle negative exponents!\n");
return 0;
}
result = 1;
counter = exponent;
while (counter > 0)
{
result = result * base;
counter--;
}
return result;
}
Now you figure out how to call this function from main to show off what it can do. :)
Challenges
- Add both functions, compute_the_square and power, to a single program.
Get a number from the user, and show that compute_the_square(number) is the same as
power(number, 2). Why are these the same?
- Try to make a version of compute_the_square that uses floats instead of ints.
- Make a version of power that uses floats instead of ints.
- Expand the float version of power to handle negative exponents.
Hint: Negative exponents divide by the base instead of multiplying by it. So power(10, -5) would be 0.00001