Lesson 12 · 12 of 20
Functions · C
Group code into C functions: void functions that return nothing, functions with a parameter and functions that give back a result with return.

A function is a named piece of code you can use as often as you like. print_line draws a line; in main, writing print_line(); is enough to run it. That way the line is drawn three times without repeating the code.
In front of the name goes the type of what it returns. `void` means "nothing": print_line and print_stars only print. print_line(void) takes nothing; print_stars(int count) takes a parameter, the number of stars, and its for uses it to draw 5, 3 or 4.
celsius_to_fahrenheit returns a double: `return` ends the function and hands the value back to whoever called it. That value can go straight into printf or be stored in a variable, like cold.
The functions in this example are written before main so the compiler already knows them when they are used. The next lesson shows how to put them after it.
Code · main.c
#include <stdio.h>// A function groups code under a name. void: it gives nothing back.void print_line(void) { printf("------------------------\n");}// This one receives a value: how many stars to draw.void print_stars(int count) { for (int i = 0; i < count; i++) printf("*"); printf("\n");}// This one gives a value back with return.double celsius_to_fahrenheit(double celsius) { return celsius * 9 / 5 + 32;}int main(void) { print_line(); printf("Hotel reviews\n"); print_line(); printf("Sea View "); print_stars(5); printf("City Inn "); print_stars(3); printf("Old Mill "); print_stars(4); print_line(); // The result can be used like any other value. printf("25 C is %.1f F\n", celsius_to_fahrenheit(25)); double cold = celsius_to_fahrenheit(-5); printf("-5 C is %.1f F\n", cold); return 0;}Output · cc main.c -o main && ./main
------------------------ Hotel reviews ------------------------ Sea View ***** City Inn *** Old Mill **** ------------------------ 25 C is 77.0 F -5 C is 23.0 F
Key points
- A function groups code under a name.
voidas the type: it returns nothing.- Parameters go in brackets, each with its type.
return value;ends the function and hands back the result.- Define a function before using it (or use a prototype).
Exercise
Write a double kmh_to_ms(double kmh) function that turns kilometres per hour into metres per second (divide by 3.6) and use it with 50, 90 and 120.