DEV Community

Sean Watkins for Game Dev From Scratch

Posted on • Edited on

Loops and Math in C

I have over the last couple days, been learning more about the basics of C the programming language! Let me recap what I've learned for you.

I have already, similar to my sister (thalia), learned the very basics such as how to use the standard input/output library #include <stdio.h> and printf("Hello, world");.

To see more about this, please read Thalia's post.

loops.c

#include <stdio.h>

int main(void)
{
    for (int i = 0; i < 100; i++) {
        printf("Hello, Jerome. ");
    }

    int i = 0;

    while (i <= 1000) {
        printf("%d ", i);
        i = i + 1;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

I wrote a for loop to print a message 100 times, and a while loop to print the numbers from 0 to 1000 using the %d format to print integers in decimal.

In the for loop, all of the loop control is in one place, whereas in the while loop the initializer, test and increment are scattered around the code.

maths.c

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *star_name = "Proxima Centauri";
    double star_distance_ly = 4.2465;
    double c = 299792458;
    double seconds_in_year = 3600 * 24 * 365.2422;
    double light_year = c * seconds_in_year;
    double star_distance_km = star_distance_ly * light_year / 1000;

    printf("The distance to %s is %.0f km.\n", star_name, star_distance_km);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

This is probably already apparent, but maths is an extremely important part of any programming language, especially if you want to make games. This is why I thought a good next step would be to see if I could make simple calculations through C. I have, again, been watching more Kurzgesagt videos on YT. Inevitably I found many great videos on their channel about space and our universe, this got me wondering about the closest stars to our own.

This little program converts the distance to the closet star from light-years to kilometres. I used double variables; these are double-precision floating point numbers. We can print a double with %f and rounded off to a whole number with %.0f for 0 decimal places.

Next post: Basic Programming in C, by Sam
Previous post: My Simple Programs, by Thalia
Contents: Game Dev From Scratch

Top comments (0)