C Basics

Reading time ~1 minute

Libs, Defs, Args and Control Structures

File: basics.c

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

#include "fib.h"

#define SIZE 100

void        print_uint64_array  (uint64_t* list, uint64_t len);

int main(int argc, char const* argv[])
{
    if (argc != 2)
    {
        printf("expected one argument, shutting down...\n");
        return EXIT_FAILURE;
    }

    uint64_t len = (atoi(argv[1]) < 0) ? 1 : atoi(argv[1]);
    uint64_t list1[SIZE];
    uint64_t list2[len];

    for (size_t i = 0; i < SIZE; i++)
    {
        list1[i] = fib(i);
    }

    for (size_t i = 0; i < len; i++)
    {
        list2[i] = fib_rec(i);
    }

    print_uint64_array(list1, SIZE);
    print_uint64_array(list2, len);

    return EXIT_SUCCESS;
}

void print_uint64_array(uint64_t* list, uint64_t len)
{
    printf("[");
	for (size_t i = 0; i < len-1; i++)
    {
	    printf("%"PRIu64", ", list[i]);
	}
    printf("%"PRIu64"]\n", list[len-1]);
}

File: fib.h

#ifndef FIB_REC_
#define FIB_REC_ 1

#include <inttypes.h>
uint64_t fib_rec(uint64_t value);
uint64_t fib(uint64_t n);

#endif

File: fib.c

#include "fib.h"

uint64_t fib_rec(uint64_t value)
{
    if (value < 3)
    {
        return 1;
    }
    return (fib_rec(value-1) + fib_rec(value-2));
}

uint64_t fib(uint64_t n)
{
	uint64_t a = 0;
	uint64_t b = 1;
	uint64_t k = 0;
	for (uint64_t i = 0; i <=n; i++)
	{
		a = b;
		b = k;
		k = a + b;
	}
	return b;
}