Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 9

Introduction to Programming

Using C
AN INTRODUCTION TO VARIABLES

What is a Variable?

An area of memory set aside at run-time to hold a value The area of memory is given a name which can be used to refer to the value that is stored there The name of the variable must begin with either a letter or an underscore character any number of letters, digits and underscores may follow Variable names cannot contain spaces Often variables have capital letters for a change in word instead of a space so that a variable can be given a meaningful name (the camels hump) style of naming variables eg, myAge
2

Types of Variables: Character Variables (char)


Values of this type take up one byte (8 bits) of memory. Usually stores a single character ie. A letter, a digit, a punctuation mark any of the characters present on the keyboard and some special characters as well (such as newline and tab). Arrays of characters (several characters which are contiguous in memory) are known as strings.

Integer Variables

These are positive and negative whole numbers.


On most systems they take up two bytes of memory. A variable declared as an integer can hold a value of between -32768 and +32767.

Float Variables

Float values are real (or floating point) numbers such as 10.2 and 12.333.

These are numbers with two parts an integer part before the decimal point and a fractional part after the decimal point. Generally, they take up four bytes and have a precision of 6 or 7 digits so a value entered as 1234567890.0 will lose precision and be stored as 1234560000.0.

Double Variables

Double values take up twice the storage space of float values (up to 8 bytes). Allows a much greater precision so calculations involving millions of pounds will need to use double precision if accuracy to the nearest penny is needed.

Declaring Variables

Variables have to be declared before they are used to ensure that at run-time memory will be set aside to store the values of variables. Keywords used to declare variables are: char, int, float and double.

Example Variable Declarations


int char char float double

age //whole numbers initial //single character surname[15] //character strings height //numbers with a dec pt cost //large high precision no

Escape Sequences

These all begin with \ and are used for inserting special characters (which are not printable into the format string, eg:\n \t newline tab

\a
\b

audible bell
backspace

You might also like