08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.5 Integer Numbers - int

Chapter 2 ■ C – The Basics

An int variable is used to store an integer (whole number) value. An integer value is one of 0, ±1,

±2, ±3, ±4, etc. However, on a computer, the largest and smallest integers that can be stored are

determined by the number of bits used to store an integer. Appendix C shows how integers can be

represented on a computer.

Typically, an int variable occupies 16 bits (2 bytes) and can be used to store whole numbers

in the range -32,768 to +32,767. Note, however, that on some machines, an int could occupy 32 bits,

in which case it can store whole numbers from -2,147,483,648 to +2,147,483,647. In general, if n

bits are used to store an int, the range of numbers that can be stored is -2 n-1 to +2 n-1 - 1.

As an exercise, find out the largest and smallest int values on your computer.

2.5.1 Declaring Variables

In C, a variable is declared by specifying a type name followed by the variable. For example,

int h;

declares h to be a variable of type int. The declaration allocates space for h but does not initialize it

to any value. You must not assume that a variable contains any value unless you explicitly assign

a value to it.

You can declare several variables of the same type in one statement as in:

int a, b, c; // declares 3 variables of type int

The variables are separated by commas, with a semicolon after the last one.

You can declare a variable and give it an initial value in one statement, as in:

int h = 14;

This declares h to be int and gives it a value of 14.

2.5.2 Integer Expressions

An integer constant is written in the manner we are all accustomed to: for example, 354, 639,

-1, 30705, and -4812. Note that you can use only a possible sign followed by digits from 0 to 9.

In particular, you cannot use commas as you might do to separate thousands; thus 32,732 is an

invalid integer constant—you must write it as 32732.

An integer expression can be written using the following arithmetic operators:

+ add

− subtract

* multiply

/ divide

% find remainder

29

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!