Variables2

More on Variables #

Modulus - Remainder after division #

There is one more operator that is useful to us when using ints, the modulus or mod operator: %. The modulus operator provides us with the remainder after division. As we don’t have a decimal point when using ints it is useful to be easily able to get the remainder after division. This is useful in a number of scenarios but one that comes up repeatedly is converting between unit types, for example converting a value like 90 minutes, to 1 hour and 30 minutes:

#include <stdio.h>

int main(void)
{
    int total_minutes = 90;
    int hours = total_minutes / 60;
    int minutes = total_minutes % 60;
    printf("%d minutes is %d hour(s) and %d minute(s)",total_minutes,hours,minutes);
    return 0;
}

The output of the above program is:

90 minutes is 1 hour(s) and 30 minutes(s)

Numbers with decimal points #

We now come to the concept of numbers with decimal points. These are called floating point numbers and we have access to two different types in C. float and double. Floating point numbers are so called because the position of the decimal point is not fixed, it can move in a manner similar to how we represent numbers using scientific notation with whole numbers and indices that are also whole numbers.

We won’t use the float type as all of the internal calculation that C performs on floating point numbers are done as a double. If you are in a space restricted environment and the usage of doubles takes too much resources then you can consider using float. We will cover aspects of floating point numbers relating to precision at a later point in the course.

The format specifier for scanf and printf when using floats is %f and for doubles it is %lf (long float!), as %d was taken for ‘decimal integer’. You can also use the format specifier to reduce the number of decimal places output, for example %.2lf will limit the output to 2 decimal places but it won’t alter the value of the double variable.

An example of a program using doubles to perform a calculation:

#include <stdio.h>

int main(void)
{
    double money, price,change;
    printf("Please enter how much cash you have: ");
    scanf("%lf",&money);
    printf("Please enter how much the item costs: ");
    scanf("%lf",&price);
    change = money - price;

    printf("Your change is %lf",change);
    return 0;
}