diff --git a/02_control_structures/Makefile b/02_control_structures/Makefile index 1d0e24c7cfeb871a9e24a7447f63d3fa67b7c3ea..c1531e1f367f0e4c27e6aeec17f509f86c98ef60 100644 --- a/02_control_structures/Makefile +++ b/02_control_structures/Makefile @@ -5,7 +5,7 @@ CXX = g++ CFLAGS = -Wall -O3 .PHONY: all -all: loops +all: loops functions # Here I'm using some of Make's built in variables: $@ and $<. The former gets substituted with the # name of the target. In this case, that's "loops". The latter gets substituted with the first @@ -14,6 +14,9 @@ all: loops loops: loops.c $(CC) $(CFLAGS) -o $@ $< +functions: functions.c + $(CC) $(CFLAGS) -o $@ $< + .PHONY: clean clean: - rm loops + rm loops functions diff --git a/02_control_structures/functions.c b/02_control_structures/functions.c new file mode 100644 index 0000000000000000000000000000000000000000..52e5cf63ea37f8028d2258c8f07256c8b9253bcf --- /dev/null +++ b/02_control_structures/functions.c @@ -0,0 +1,46 @@ +#include <stdio.h> + +int is_even(int x) { + return x % 2 == 0; +} + +int is_odd(int x) { + return x % 2 == 1; +} + +int is_prime(int x) { + for (int i = 2; i <= x / 2; ++i) { + if (x % i == 0) { + return 0; + } + } + return 1; +} + +int factorial(int x) { + int result = 1; + for (int i = 2; i <= x; ++i) { + result *= i; + } + return result; +} + +int n_choose_k(int n, int k) { + // Note: if you actually want to compute binomial coefficients, there are better ways to do it. + // This method will overflow except for very small n and k. + return factorial(n) / (factorial(k) * factorial(n - k)); +} + +int main(void) { + int two_is_even = is_even(2); + int three_is_odd = is_odd(3); + int four_is_prime = is_prime(4); + int five_factorial = factorial(5); + int six_choose_four = n_choose_k(6, 4); + + printf(two_is_even ? "two is even\n" : "two is odd\n"); + printf(three_is_odd ? "three is odd\n" : "three is even\n"); + printf(four_is_prime ? "four is prime\n" : "four isn't prime\n"); + printf("5! = %i\n", five_factorial); + printf("6 choose 4 = %i\n", six_choose_four); +} diff --git a/02_control_structures/loops.c b/02_control_structures/loops.c index 2e9710d55a39d342712d6d17a8173773aa92b7a7..9fe31910f95c78a3f59a584c8f07589a942d0ec2 100644 --- a/02_control_structures/loops.c +++ b/02_control_structures/loops.c @@ -28,6 +28,7 @@ int main(void) { while (1) { printf("another while loop: %i\n", i); + // This one is pretty obvious, but it's arguably the most important control structure. if (i == 2) { printf("leaving the while loop\n"); break;