Commit 0ed71eeb authored by Erik Strand's avatar Erik Strand
Browse files

Add a demo of functions

parent a72b398f
......@@ -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
#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);
}
......@@ -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;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment