Variables are the glue of programs: they are the way computers remember data. But, what exactly are they and how are they used? Let’s find out!




Now you’re probably thinking: What is that? What’s “cats”, what’s “%d”? Give me simple things like last time!

Before starting, check the previous post if you haven’t already, so you can learn what #include main() and printf mean.

If you want to jump to a specific section use this table of contents:

 

What is a variable?

cats is a variable, but what exactly is a variable?

A variable is like a box

 

Imagine a variable as a box:

  • There is a label that suggests you what the content is;
  • It has a size and a material suitable for its content;
  • It contains something.

Therefore a variable has:

  • a name: it can be everything you want, but it’s usually something appropriate for the content.
    Anyway there are some rules on the naming:
    1. It can only begin with a letter of the alphabet or an underscore ( _ );
    2. It can contains numbers, but not spaces and special characters;
    3. You can’t use C or C++ keywords such as main;
    4. Lowercase and uppercase are different;
    5. Two variables can’t have the exact same name.
  • a type: which type of value do we want the variable to store? An integer, a character or others? It’s important for the computer to know this so it can reserve the right amount of memory;
  • a value: it’s what we want to save into the memory. You can initialise a variable so it already has a value when it’s created, you can assign a new value that replace the current one or you can read it. How?

 

Initialising a variable

Look at the line int cats = 0;.

This is how a variable is created and initialised: let’s explain it step-by-step.

The first word is the type of the variable, in this case int that stands for integer. We also encountered it in the previous post, when we talked about the type of a function: that time it was the type of the output of a function, this time instead it’s the type of the value that a variable contains.

Since our variable is an int it can only contain numbers without fractional component: if we try to assign a letter to it, the compiler will return an error.

There are a lot of variable types, but this are the most important in C:

  • int: an integer (a number without fractional component);
  • float: a number with fractional component;
  • double: a more precise version of float (but it requires more space in the memory);
  • char: a single character;
  • void: it’s used only for functions to indicate that there isn’t an output.Joke about Shrodinger from The Oatmeal

The second wordcats, is the name of the variable: following our line of thinking we’re probably going to put some cats into a box (our friend Schrödinger is very happy now).

That = 0 is the real initialisation of the variable (the rest was the creation). It’s optional and it tells the computer that the variable we’re creating has an initial value of 0 (but I could write any other number).

Finally here’s something that isn’t optional at all: the semicolon. We have to put a semicolon after each function call, variable initialisation, assignment or operation.

 

Assigning a value to a variable

Assigning a value to a variable is like initialising it, but it isn’t done when the variable is created, but later in the code.

It looks like this:

cats = 10;

We don’t write again the type of the variable because the computer already knows it.

We just need its name and the new value that’s going to replace the current one.

*cough cough* don’t forget the semicolon *cough cough*

 

Using a variable in operations

We can do all types of operations with variables. The process is similar to the assignment, but instead of having a value on the right side, we have an operation between fixed numbers or variables.

An example could be:

cats = 5 + 2 * cats;

Just like in maths, the computer will do first the multiplication and then the addition. If you don’t know how to solve numerical expressions, have a look at this.

Um, Zephyro, what’s * ?

It’s the symbol that most programming languages use for multiplications. Let’s see a table of the main symbols in C:

Operator name Syntax
Assignment a = b
Addition a + b
Subtraction a – b
Multiplication a * b
Division a / b
Modulo (integer remainder of a division) a % b
Increment (a = a + 1) a++
Decrement (a = a – 1) a–

In our previous example we combined assignment, addition and multiplication.

The cool thing is that two of them, increment and decrement, don’t require an assignment to work: they automatically save the new value in the variable (additions don’t do that for example).

You can do the same thing with other operators just adding an = after one of them. For example:

a += b means a = a + b

Can you spot where we used cats in an operation in today’s program?

I wrote cats--; that is a decrement of the value of cats.

How do we read a value from a variable?

 

Using a variable

To do that just type the name of the variable where you want its value to be. Simple, isn’t it?

 

Using variables as function’s inputs

As we said last week, a function can need some inputs when it’s called.

For example, printf has the following syntax:

In our example we have printf("Do you have %d cats? How many cats do you have? ", cats);:

Instead of that special character %d there will be the value of cats, so the result would be Do you have 0 cats? How many cats do you have?

What does %d mean?

It’s a special character that will be replaced by the value of its corresponding variable. The character to be use varies based on the type of variable you want to write.

Here’s another table:

Character Description
%% It just prints a %
%d Integer written using the decimal system
%i Integer written using the hexadecimal system (it works only in scanf)
%u Integer without sign
%f Float or double
%g Float or double without zeros at the end or in exponential notation
%s String
%c Character

This are the most important in my opinion, but you can check the whole list on Wikipedia.

If you read the previous post, you already know how printf works, so let’s explain what in the world is that scanf.

Just like printf writes a sentence on the command prompt, scanf can read values from it.

Its syntax is:

Remember that, contrary to printf, all variables in scanf have to be introduced with an &. I will explain you the reason of that when we’ll do pointers, so keep an eye on this website for further posts.

In today’s program, I wrote scanf("%d", &cats); to read an integer value from the command prompt and assign it to the variable cats.

What will happen when we’ll run the code?

I typed 3 after the first output

The program will print the first text on the screen and then it will wait for us to type an integer and then press Enter.

By the way I’m lying, I don’t have any pets.

 

Let’s explain the code step-by-step

So here’s the code again (I don’t want you to scroll up forever and struggle to find it):


Here’s the step-by-step explanation (with some copy/paste of the lines I explained last time for who’s too lazy to check):

The first line is #include stdio.h> and it means “this program uses the library called stdio.h“.

stdio.h contains the main input/output functions of C.

It’s the declaration (= creation) of a variable and its initialisation. It contains:

  • The type of the variable;
  • The name of the variable;
  • The initial assignment called initialisation;
  • a semicolon that tells the computer when an instruction is finished;

For more information check the previous chapters.

Let’s have a look at int main() {:

  • main is the main function of the program. It tells the computer where to start executing(=running) the code.
  • int stands for integer (=a number without fractional component, like 1, 2, 3… but not 1.5, 2.5…) and it is the type of the value that the function main returns.
    When the computer finishes executing a function it is possible to see its result: for instance, a function that multiply two numbers will give use (we say it returns) the result of the multiplication.
    main returns an integer (int) that tell us if there were errors: you’ll see that value at the end of the execution on the command prompt.
  • Inside the two brackets () we put the parameters (=the inputs) of a function. In this case main doesn’t require any parameters, so we leave it empty.
  • The last bracket { means “the function’s code starts here“. Everything we will put inside the two {}of the function main will become the core code of our program.
    Remember that can be other curly brackets inside the function main, but for every opening bracket there must be a closing one.

Printf is a function that print a text on the command prompt. In this case it will write Do you have %d cats? How many cats do you have? replacing %d with the value of cats, as we saw previously.

Scanf is a function that read values (in this case just one) written by the user from the command prompt and it assigns them to variables (in this case cats).

Each variable must always be introduced by a &. For more information check the previous chapters.

This is a decrement of the value of cats. It’s one of the operations you can do in C and one of the two that doesn’t require an assignment to work.

Do you know what? I’ve explained a lot of thing today, in fact also this time I can link to a previous chapter.

It’s the final output of the program and it works exactly like the other printf call.

You see? We used output, input, processing (the decrement of the variable) and another output to create a complete program that can interact with the user! It’s still nothing compared with what we will learn, but it’s way better than that boring Hello world! variation we did last week.

 

Let’s translate the code

In human language, this code is:

Computer, this program uses functions from the library called stdio.h

Create a variable called cats that contains integer numbers and that has an initial value of 0.

This is the main part of the program: start from here

Write on the command prompt the sentence “Do you have %d cats? How many cats do you have? ” but remember to replace %d with the value of cats

Read from the command prompt a value typed by the user and assign it to cats

Decrement the value of cats

Write on the command prompt the sentence “So you have more than %d cats!” and go to a new line, but remember to replace %d with the value of cats

This is the end of the program.

 

C and C++ comparison

In the table at the top, you can see two columns: one for C and the other for C++.

What are the differences between the two?

  1. The main input/output library of C++ is iostream, not stdio.h
  2. There is a new line using namespace std; that tells the computer that the program is using the standard (std) namespace (set of libraries).
    You can also don’t use this line of code, but then you’ll have to explicitly tell the computer whenever you call a function from the Standard Library.
  3. cout (or std::cout if you decided to not use the std namespace) is the C++ alternative to printf.
    It has a different syntax because it isn’t a function, but you can add other sentences to the first. Each time you want to do it just type >, I usually imagine cout as the command prompt and the double less-than sign as an arrow that move the content from one side to another.
  4. cin (or std::cin if you decided to not use the std namespace) is the C++ alternative to scanf.
    It has a different syntax because it isn’t a function, but you can add other variables to the first. Each time you want to do it just type >> followed by what you want to be written on the command prompt.
    To remember if it’s >, I usually imagine cin as the command prompt and the double less-than sign as an arrow that move the content from one side to another.
    One last thing: cin doesn’t require the & symbol before variable names.

Nevertheless, you can use the same C code in C++.

 

Conclusion

Now that you’ve learnt some basics about inputs, outputs and processing, you’re able to do very cool programs. Why don’t you try to use float and double instead of int (char will require its own post).

As I said in 21 Things You Must Know before Learning Programming, you should practise after reading a post, so you can learn better what you’ve read.

Before concluding I want to sum up what we’ve examined:

  1. What a variable is;
  2. How to initialise it;
  3. How to assign a value to it;
  4. Using variables in operations;
  5. How to read it;
  6. How to use variables as function’s inputs (+ how printf and scanf work);
  7. Today’s program with a step-by-step explanation;
  8. A comparison between the same code in C and in C++;

Yep, I wrote a bunch of titles ?. (There’s an emoji here, I don’t know if you can all see it)

If there’s anything I’ve missed or if you want to ask me something, write a comment below, so I can improve this blog and teach you better.

If you liked this post why don’t you share it to your friends? Learning together would be more enjoyable. There are three button right at the end: one for Twitter, one for Facebook and on for Google+

Anyway, the post is finished, have a good day and we will see the next week!

Zephyro, over!


Leave a Reply

%d bloggers like this: