Lesson 3 - Variables and the type system in the C language
Lesson highlights
Are you looking for a quick reference on C variables and type system instead of a thorough-full lesson? Here it is:
Creating int
and double
variables (for whole and decimal numbers) and
assigning values to them:
{C_CONSOLE}
int a = 56;
double b = 56.6;
printf("%d \n", a);
printf("%lf \n", b);
{/C_CONSOLE}
Reading numbers from the console:
{C_CONSOLE}
printf("Enter a number and I'll double it: ");
int a;
scanf("%d", &a);
printf("%d", a * 2);
{/C_CONSOLE}
Would you like to learn more? A complete lesson on this topic follows.
In the previous lesson, Installing NetBeans and the C compiler, we learned how to work with NetBeans, and created our first console application. In today's lesson, we're going to look at the so-called type system of the C language. We'll introduce basic data types, and we'll work with variables. As a result, we'll create 3 simple programs, including a simple calculator.
Variables
Before we start working with data types, let's make sure you understand what
a variable is. If you're already familiar with programming, please excuse the
short explanation. Surely, you remember variables from Math class (e.g.
X
), in which we could store some value, usually a number. A
variable in IT is the same exact thing. It's a place in computer memory where we
can store some data, e.g. a username, the current time or a database of
articles. This place has a certain reserved size, different variable types have
different sizes, which the variable can't exceed, e.g. integer numbers can't be
bigger than 2 147 483 647.
A variable is always of some sort of data type. It can be a number, a character, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it first to specify how this variable will be called and of what data type it will be. The programming language will establish it in the memory and be able to use it. Our computer knows, based on our declaration, how much memory the variable occupies and how to operate with that piece of memory.
Type system
There are two basic type systems: static and dynamic.
- In the dynamic type system, we're fully relieved from the fact that the variable has some data type at all. Obviously, the variables have it internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user structures or decimal numbers. The language will automatically change the inner data type according to data we're assigning into the variable. Due to a smaller amount of code, the development is usually faster in those languages. The example languages with this kind of type system are e.g. PHP or Ruby.
- On the other hand, we have the static type system. It requires us to declare the variable type, and this type is unchangeable from then on. Meaning that, if we try to store a number into a user structure, we'll get yelled at by the compiler.
C is a statically typed language. All variables must be declared as specific data types. The main disadvantage to this is that due to the declarations, a source code is a bit longer and it takes more time to write it. The main advantage is that before running, our compiler checks whether all of the data types match. Dynamic typing may look like it'd be chock full of advantages, however, we can't automatically check a source code and if we expect a user object somewhere and we get a decimal number instead, the error will be revealed only during the run-time and an interpreter will stop the program. The C language won't allow us to compile a program until it checks it for errors (this is yet another benefit to using compilers).
Let's make an example program so that you'll be able to apply this newly acquired knowledge. We will continue with the theoretic part of it all next time. Here are three basic data types:
- Numbers:
int
- Real numbers (
10.12
,...
):double
- Single characters (we'll learn to store texts later):
char
Variable printing program
We'll go ahead and declare an integer variable, and name it: a
,
store the number 56
in it and print its content into the console.
Create a new project and name it Output
(we'll create a new project
for each sample program). Don't forget to write the code inside the body of the
main()
function like we did last time, I won't copy the
main()
function here anymore.
{C_CONSOLE}
int a;
a = 56;
printf("%d", a);
{/C_CONSOLE}
The first command declares a new variable, a
, of the
int
data type. This variable will be used to store integers, i.e.
whole numbers. The second command assigns a value to the variable using the
"="
operator we all know from math classes. The last command is
already familiar to us. It'll print the content of the variable a
.
Notice the %d
sequence in the quotes, we're indicating which type
we want to print, %d
stands for whole numbers (as a decimal).
Console application
56
The same code for a real number variable would look like this:
{C_CONSOLE}
double a;
a = 56.6;
printf("%lf", a);
{/C_CONSOLE}
It's almost the same as the code for an integer. The decimal separator will
always be represented by a dot here (even if your regional separator is a
comma). Then, we change the %d
sequence to %lf
,
telling the computer we want to print a real number.
Doubler program
The previous program was a bit boring, so let's try to respond to user input
somehow. We haven't tried to read anything from the console yet. There is the
scanf()
function which allows the user to enter a text line to the
console. It'll store the value entered to a variable for us.
To try that, let's create a doubler program which will retrieve an input
number, double it and display it. Create a new project and name it
Doubler
. We'll get to its code and add the following into the
main()
function:
{C_CONSOLE}
int a;
printf("Enter a number and I'll double it: ");
scanf("%d", &a);
a = a * 2;
printf("%d", a);
{/C_CONSOLE}
The program output:
Console application
Enter a number and I'll double it: 1024
2048
This is already a little more fun. The "doubler" retrieves a number from the
user, it doubles it and writes it to the console. The first line is clear, we
simply declare a new whole-number variable a
. In the C language, we
always declare the variables at the beginning of the block.
The value from the console entered by the user is assigned to the variable
a
using the scanf()
function. We'll get into the
"&"
character later, for now, just know that
scanf()
needs it to be able to store the value to a variable. Here,
we use "%d"
sequence once again, by which we're saying that the
input should be read as a whole number. By the way, we would read/write a single
character using the "%c"
sequence.
Simple calculator
Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results of addition, subtraction, multiplication, and division.
{C_CONSOLE}
double a;
double b;
double sum;
double difference;
double product;
double quotient;
printf("Welcome to calculator!\n");
printf("Enter first number: ");
scanf("%lf", &a);
printf("Enter second number: ");
scanf("%lf", &b);
sum = a + b;
difference = a - b;
product = a * b;
quotient = a / b;
printf("Addition: %lf\n", sum);
printf("Subtraction: %lf\n", difference);
printf("Multiplication: %lf\n", product);
printf("Division: %lf\n", quotient);
{/C_CONSOLE}
The output:
Console application
Welcome to calculator!
Enter first number: 3.14
Enter second number: 2.72
Addition: 5.860000
Subtraction: 0.420000
Multiplication: 8.540800
Division: 1.154412
As you can see, we can use classic arithmetic operations in the C language
(+
, -
, \
, *
,
/
). C also defines another operation (%
) which
indicates the remainder left over from the integer division. Notice that we use
"%lf"
since we're working with real numbers here. If you're
interested in more possible formatters, feel free to go through the documentation.
In the next lesson, Solved tasks for C lessons 1-3, we'll talk some more about type systems, and introduce you all to more data types.
All of the programs are available for download in the attachment below. You should definitely try to create some programs similar to these, seeing as how you already have the knowledge necessary to do so!
In the following exercise, Solved tasks for C lessons 1-3, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 3x (212.72 kB)
Application includes source codes in language C