learn c with me - week 2 - variables, operators, input operations, and comments

Table of contents

  1. variables
  2. operators
  3. exercise
  4. scanf function
  5. comments
  6. further learning
  7. final thoughts


cat in a cat carrier

Pretty sad cat in a pretty nice cat carrier

variables

Remember last week's Hello, world program?
It was nice, however, it was quite simple. Indeed, every other more advanced piece of code relies heavily on the variables, which are one of the fundamental code blocks. Variables are like boxes for storing certain information for later usage and I am willing to say that without them writing scalable and interactive code would be impossible.
How can we create one?
Every variable has 2 things; the first is the type and the second one is the name and let's start with it.
While C doesn't enforce many rules on naming variables here are the few you need to follow:

Ideally, variable names should be self-explanatory, mnemonic, and easy both to type and remember, so the best practice is to avoid mixing similar letters like 'I' (capital 'i' letter) and 'l' (lowercase 'L' letter) or numbers with letters like 'O' (capital letter 'o') and '0' (number zero). You should use digits in variable names really in the last resort.

If we now have a name for the variable, we need to decide what type it will be.

Variables are the small silly storage boxes living in the computer's memory, we can use them to store values for later usage, but here is the trick - they are different shapes and sizes.
Probably you wouldn't put vegetables in the cat carrier, store sand in a mesh container designed for storing fruits, or use a 5L bottle to store a cup of coffee especially if you have to bring a few different cups of coffee to share with your friends. It would be just economically wrong. The same with computer memory. You have to know in advance what data will be stored to allow the compiler to choose the most optimal option for you both in terms of size and performance. Working on predefined data types also makes your program more predictable and easier to maintain because you know what to expect from different variables and functions.
Remember the main function from week 1? Even the main function has a type! (an integer type, to be more precise).

At the hardware level, all data looks the same no matter of type, but the types are the things helping us to display and work on them properly. Having to define data type in advance might seem inflexible, but it's the feature that makes C more flexible. Without data types, the 100001 would be just 33, but thanks to them it can be anything from 33 to '!' to 4.624284932 (i guess), 0x21, and so on. If you are curious how it varies among binary, decimal, floating point numbers, and hexadecimal values, you can play with this website.
So what are the options?
Well, we have a few of them

  1. int - probably the simplest data type intended to store integer (whole) numbers
  2. char - data type intended to store exactly 1 ASCII character (or escape sequence), but storing small numbers inside is possible too
  3. float - suitable for storing floating point numbers, which means that everything which is not a whole number
  4. double - the same as float but with two times greater precision which is the preferred option if you are dealing with more mission-critical calculations

There are way more data types, but they are just variations of these 4, so I will leave the table with more details at the end of the post, along with format specifiers and their size in bytes.
After we successfully decided which type of variable we want and how we will name it, now we can create it.

        
int sillyPrime;
char coolCharacter;
        
    

That's it. We just created our first variable storing probably some cool number, but wait… It's empty!
Yes. Our variable exists, but it's completely empty. It's time to assign some value to it.

assignment operator

To assign (or basically change) the value of the variable, we need to use an assignment operator and the value we want to put inside the variable. In C and many other programming languages the assignment operator is the equality sign (this -> '='), so please keep it in mind and be careful to not mismatch it with the relational equality operator, which is made out of two equality signs (this -> "==").
Assigning the value to a variable is simple.

        
variable = newValue;
sillyPrime = 65537; //65537 is the integer number, so we can put it inside the sillyPrime variable.
coolCharacter = 3.14159; //This is NOT the character! Trying to put pi inside a box made for characters will lead to some problems.
coolCharacter = 'A'; //This is the character, so it will fit nicely into the coolCharacter box.
        
    

The assignment operator is just beginning. There is a whole rabbit hole of different operators created for different purposes!

operators

As mentioned before, there are a lot of different operators, so for the needs of today's post, I will dive into arithmetical operators. The list of them is ceaseless, but I am sure we will get someday into all of them.

arithmetical operators

Their working principle is simple. You need two values and an arithmetical operator between them to get the result of the operation. Here's the list of them and a simple explanation.

  1. + operator is used to add 2 values together and get the sum of them (2 + 5 will be 7)
  2. - operator is used to subtract 2 values and get the difference between them (11 - 6 will be 5)
  3. * operator is used to multiply 2 values and get the product of them (7 * 3 will be 21)
  4. / operator is used to divide 2 values and get their quotient (360 / 12 will be 30)
  5. % operator is used to get the remainder after division (9%2 will be 1 because 9/2 is 4 with remainder 1)
        
int a = 5;
int b = 10;
int c;

c = a + b;
//now the value of c is 15
c = b - a;
//now the value of c is 5
c = a * b;
//now the value of c is 50
c = b / a;
//now the value of c is 2
c = b % a;
//now the value of c is 0
        
    

Can we combine arithmetical and assignment operators? Yes!

At some point in your life, you will have to change the value of the variable, based on its previous content, so there are a few shortcuts you should use to make both your life simpler and your code more readable. Here they are:

  1. +=
  2. -=
  3. *=
  4. /=
  5. %=

They work pretty much the same way as the previous ones, but now you don't need the left hand value (the value on the left side from the arithmetical operator). Here's how they work:

  1. x += y; works the same way as x = x + y;
  2. x -= y; works the same way as x = x - y;
  3. x *= y; works the same way as x = x * y;
  4. x /= y; works the same way as x = x / y;
  5. x %= y; works the same way as x = x % y;

We can go even further. If you would like to increase or decrease the value of the variable exactly by 1 here are the other shortcuts:

  1. increment++;
  2. decrement–;

Things become a bit trickier here because they can be used both as a prefix and as a postfix to the variable. To better illustrate this I prepared some code:

        
#include <stdio.h>
int main(void)
{
    int x = 10;
    int y = 10;
    int prefix = ++x;
    int postfix = y++;
    printf("The prefix result: %d, the postfix result: %d\n", prefix, postfix); 
    return 0;
}
        
    

Output:

        
The prefix result: 11, the postfix result: 10
Program ended with exit code: 0            
        
    

At the end of this program's execution, both x and y will be 11 because we incremented both of them by 1, the difference between the prefix and postfix variable is that in the prefix variable we first incremented x to 11, and put its copy into prefix box, while on the other hand in postfix variable, we first put a copy of the y value (which was 10 at the time) to the postfix box and just after it we incremented y itself by 1, so it's now 11, but postfix value is still 10 because the variables are now independent of each other.

exercise

I think we are in good shape to do a simple exercise. We will create a program to convert the melting temperature of helium from Kelvin to Fahrenheit for all our american friend's needs.
Before we write our very first line of code, let's take a quick look at how we should create such a program.

  1. What problem do we want to solve?
  2. How do we want to solve this problem?
  3. What data types and variables do we need to use?
  1. We want to convert temperature from Kelvin to Fahrenheit
  2. We will solve this problem by using the formula for temperature conversion;
    The formula is: F = (K - 273.15)\*9/5 + 32
  3. We will need a box to store the input value and the result of the operation; as we can see from the formula above, we need to use a floating point number to store the result, not just because we are subtracting -273.15 from Kelvin temperature, but also because we are multiplying this number by 9/5 which is very likely to result in floating point number as a product. It is worth remembering that if we perform operations on numbers where the potential result may be a floating point number, that is where we should use float or double to store the result.

Now I think we are prepared well enough to solve this task.
As always, let's start with the main function

        
int main(void)
{
    return 0;
}
        
    

Now, let's create variables both to hold the melting point of helium which is .95K and to store the result of the conversion

        
int main(void)
{
    float heliumMeltingPoint, fTemperature;
    heliumMeltingPoint = 0.95;
    fTemperature = (heliumMeltingPoint - 273.15) * 9/5 + 32;
    return 0;
}
        
    

The last thing to do is to return the result we just calculated and check if everything works properly. To do this let's add the printf function and use the %f as a placeholder for the fTemperature value, passed along with the text to the printf function.

        
#include <stdio.h>
int main(void)
{
    float heliumMeltingPoint, fTemperature;
    heliumMeltingPoint = 0.95;
    fTemperature = (heliumMeltingPoint - 273.15) * 9/5 + 32;
    printf("The melting point of Helium is %fF\n", fTemperature);
    return 0;
}
        
    

So far it works good

        
The melting point of Helium is -457.959991F
Program ended with exit code: 0       
        
    

It would be nice to be able to show just the first 2 decimal values, to make output more readable. To do this, we have to put .2 between the % symbol and the f letter standing for float, as it's the data type we want to print.

        
#include <stdio.h>
int main(void)
{
    float heliumMeltingPoint, fTemperature;
    heliumMeltingPoint = 0.95;
    fTemperature = (heliumMeltingPoint - 273.15) * 9/5 + 32;
    printf("The melting point of Helium is %.2fF\n", fTemperature);
    return 0;
}
        
    

Now we can roughly translate it to "Print formatted text and put fTemperature value with 2 digits precision in the place of %"

        
The melting point of Helium is -457.96F
Program ended with exit code: 0  
        
    

It's nice and things, but it would be quite tedious to change the code every time we want to convert the temperature of anything other than the melting point of helium, wouldn't it?

scanf function

scanf is another function in the C standard library, which can be used to get input from the user. The usage is pretty straightforward and some kind of similar to the printf function;

        
scanf("%formatCode", &target);   
        
    
        
int number;
scanf("%d", &number);   
        
    

First, we have to provide the data type we want to gather from the user ("%d", where d stands for decimal integer) and the target for which function should look to put the gathered value (in this case &number because we want to get the decimal number from the user and well, put it inside number variable, while the ampersand (this -> '&') is required to tell the compiler that number variable is already stored in the memory).

Thanks to this, we can make our code more scalable and convenient because instead of changing the value, recompiling, and running the code we just changed, now it is possible to check different values every time the program is run just by typing it.

Let's update the code and see if it works

        
#include <stdio.h>
int main(void)
{
    float kTemperature, fTemperature;
    printf("Please type the Kelvin value to be converted: ");
    scanf("%f", &kTemperature);  
    fTemperature = (kTemperature - 273.15) * 9/5 + 32;
    printf("Converted %.2fK to %.2fF successfully.\n", kTemperature, fTemperature);
    return 0;
}
        
    

Now, instead of a hardcoded helium melting point, we have the kTemperature variable used to store the user's input, which is also used as an argument in the printf function to show the final results of conversion.

The last nice thing we can do with this program is to add comments explaining the code.

comments

Attaching comments to the code is useful, especially if we cooperate with other people, or just want to make it more straightforward for ourselves in the future to understand why and how we solved a particular problem. At the moment in C, there are two types of comments.
Classical, multi-line comments:

        

/*this is the comment*/

/*this is also
a comment*/

        
    

They are pretty nice, especially if you are familiar with CSS. They start with /* and end with */.

On the other hand, we have C++ style comments, which were first introduced in C99 and allow us to write simple, single-line comments like this:

        

//this is a single-line comment
//this is another single-line comment

        
    

The single line comments are more widely adopted, while many modern languages like c++, or javascript support both types of comments. To keep things nice and unified, I will stick to single-line (//) comments.
Note: In languages like go, the multi-line comments (/* */) are typically used to quickly disable problematic lines of code, that slow down or completely break our program.

As our code is pretty much self-explanatory, except for the conversion part, it's a good occasion to comment on it and attach other potentially useful info like the author of this piece of code and its purpose.

        

/*
Simple program for converting Kelvin temperature to Fahrenheit temperature created for needs of sapphic-cafe.neocities.org blog.
Author: Laura
*/
            
#include <stdio.h>
int main(void)
{
    float kTemperature, fTemperature;
    printf("Please type the Kelvin value to be converted: ");
    scanf("%f", &kTemperature);  
    fTemperature = (kTemperature - 273.15) * 9/5 + 32; //In this expression user input is converted using F = (K - 273.15) * 5/9 + 32 formula.
    printf("Converted %.2fK to %.2fF successfully.\n", kTemperature, fTemperature);
    return 0;
}
        
    

further learning

I highly recommend you to watch this playlist on computer science since it's very well made.

Also, as promised at the beginning here's the comprehensive list of data types in C, along with their size and format codes.
Note: The range and size of some data types may vary, depending on the operating system and compiler you use.

Data Type Size (bytes) printf and scanf Format Range
int 4 %d -2147483648 to 2147483647
unsigned int 4 %u 0 to 4294967295
float 4 %f N/A (floating-point)
double 8 %lf N/A (floating-point)
char 1 %c -128 to 127
signed char 1 %c -128 to 127
unsigned char 1 %c 0 to 255
short 2 %hd -32768 to 32767
unsigned short 2 %hu 0 to 65535
long 4 or 8 %ld -2147483648 to 2147483647 (32-bit system)
unsigned long 4 or 8 %lu 0 to 4294967295 (32-bit system)
long long 8 %lld -9223372036854775808 to 9223372036854775807
unsigned long long 8 %llu 0 to 18446744073709551615

Other interesting formatting codes:

printf format purpose
%o display number in octal format
%e or %E display float number in scientific notation
%g or %G display float number in %e or %f, depending which one will be shorter
%x or %X display number in hexadecimal format
%% prints '%' symbol
%p prints pointer address (more about pointers in the future!!)

final thoughts

If you are still here, congratulations, maybe you have learned something useful from this. Unfortunately due to the tremendous amount of assignments at school, I don't have as much time for writing as I would like to, so I wasn't able to cover as much as I would like, but hopefully, it will change in the next weeks. As always I wanted to thank everyone who read this before official publishing and every feedback is appreciated.

Remember to take your meds and don't sit too much.
Laura