Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Exercises
Back to top
On this page

Function exercises

These form an important part of your learning but are not formally assessed as a part of your course mark. Bring them to a demonstrator next week for feedback.

The aims at the moment are for you:

  • To be able to write simple functions.
  • To be confident with the idea of taking some code out of main() (or any other function) and making it into a separate function rather than just Copy and Pasting it.
  • To write functions (other than main()) that call other functions.

At this stage all of your functions should appear inside main.c .

Maximum function

Write a function that accepts two double arguments and returns the maximum of the two. Now write a simple main() function after this function (i.e. further down main.c than the function you have just written) that calls it for several pairs of values and prints out the result.

Add a prototype

Now reorder your functions so that main() appears before your maximum function. As it stands this causes a problem as there is no prototype: create such a prototype and place it between the #include directives and the first function.

Fizz Buzz in a function

Although it's not ideal, we all find ourselves needing to use some code that was in the middle of main(), or another function, more than once. As mentioned in the lecture it's important not to just copy and paste more than a few lines of code but to make them into a function instead.

  • Take a copy of your "Fizz buzz" code (either the if() or the switch() version).
  • Write a "dummy" function outside of main() that purports to print the correct FizzBuzz output for a given number, however leave the body of the function empty.
    • What would be a sensible name for this function?
    • What argument(s) will it need to be passed? Think of suitable name(s) and type(s)
  • Cut and Paste the logic that deals with a given number so that it is now inside you function. Call it from inside main() to make sure it works.
  • Now create another function that takes two integer arguments, a minimum and a maximum value, and contains a loop that calls you FizzBuzz function within a loop going from the minimum to the maximum value. Call this function from inside main().

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top