1. Technology

C Tutorial Lesson Two - Handling Numbers

Learn how to use Numbers in your Programs


Numbers are vital to most procedural languages. Whether you want to do complicated arithemetic, generate lotto numbers or count how many atoms there are on a pinhead, you need some way to store and manipulate numbers.

In C there are two types. Ints and floats. There are other variants of these two types which hold bigger numbers, or only unsigned numbers but they are still ints or floats.

An int is a whole number without any fractional part like 47. There is no decimal point or numbers after it. You can't have 4.5 babies or execute a loop 32.9 times. You can of course have $25.76 but for that you need a float. So when you create your program, you must decide what is an appropriate type.

Why Decide?

Why not just store everything as floats, as some scripting languages do? Because it's inefficient, floats take up more memory and are generally slower than ints. Also you cannot compare two floats to see if they are equal, whereas with ints you can.

To manipulate numbers you have to store them in memory. Because the value can be easily changed, it's called a variable. The compiler that reads your program and converts it into machine code needs to know what type it is, ie whether it's an int or a float, so before your program uses a variable, you must declare it.

Here's an example.

 int Counter =0;
 float BasicSalary; 

You'll notice that the Counter variable is set to 0. This is an optional initialization. It's a very good practice to initialize variables. If you don't initialize and then use them in code without having set a value then you will end up with a random value that will most likely 'break' your code. The value will be whatever was in memory when the program was loaded.

Related Types

What is the biggest number an int can store?. Well it depends on the type of CPU but for the next few years it will most likely remain as 32 bits. Because it can hold almost as many negative values as positive, the range of values is -2,147,483,648 to +2,147,483,647.

There is a shorter int type, coincidentally called short int which use 16 bits (2 bytes). This holds numbers in the range -32768 to +32767. If you need to save memory by using large arrays of ints, it might be worthwhile using a short int. It will not be any quicker, despite being half the size. 32 Bit CPUs fetch values from memory in blocks of 4 bytes at a time. Ie 32 bits (Hence the name- 32 Bit CPU!). So fetching 16 bits still requires a 32 bit fetch.

NoteSome computer languages refer to 16 bits as a []b]Word

On the next page you'll learn how to do simple arithmetic.

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C Programming
  5. C Tutorials
  6. C Tutorial - Lesson two Handling Numbers

©2014 About.com. All rights reserved.