0% found this document useful (0 votes)
8 views

Data Types, Variables and Constants

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Data Types, Variables and Constants

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

1107 Principles of Programming

Data Types, Variables and Constants

Facilitators
Mr. Luyima Alex Cedric
[email protected]
0772 302775 / 0708 045 305

Mr. Mugejjera Emmanuel


[email protected]
Phone: 0703 186705 / 0772 959183

Mr. Mawebe John Bosco


[email protected]
Phone: 0773-361111 / 0702 957911

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -1-


1.5 C Tokens
The smallest element identified by the compiler in a source file is called a token. It may be a single
character or a sequence of characters to form a single item. Tokens can be classified as keywords, literals,
identifiers, operators etc. Literals can be further classified as numeric constants, character constants and
string constants.
Language specific tokens used by a programming language are called keywords. Keywords are also
called as reserved words. Reserved words / keywords are defined as a part of the programming language
therefore cannot be used for anything else. Any user defined literals or identifiers should not conflict
with keywords or compiler directives.

1.5.1 Literals
Literals are values that appear directly in a program. Numeric constants are an uninterrupted sequence
of digits (possibly containing a period). Examples of numerical values are 123, 10000 and 99.78
int age = 23; // 23 is a numeric literal
Character constants represents a single character and it is surrounded by single quotation mark ( ‘).
Characters such as ‘a’, ‘A’, ‘$’ and ‘4’ are examples of Character Constants.

char letter = ‘A’; // A is a character constant

1.5.2 Identifiers
Identifiers are referred to as names given to variables. There are four major rules that must be
considered when coming up with identifiers (variable names):
i. An identifier must begin with a letter and the rest can be letters, digits or underscores. An
identifier must not start with a number / digit. e.g. 2Age and 23sum cannot be used as identifiers.
ii. Identifiers are case sensitive, therefore the identifier abc is different from ABC or Abc.
iii. C reserved / key words such as int, float, double, void, main, include etc. cannot be used as
identifiers. Programmers cannot use any of the keywords as variable names.
iv. Identifiers should never have spaces between them e.g. an identifier cannot be “age of student”
but can be “age_of_student”.
Sometimes a C compiler may consider only the first 32 characters in an identifier. While defining
identifiers programmers should follow some of the naming standards for better readability of the
program. One such standard is the use of underscores symbol (_) to combine two words (example:
sub_total).

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -2-


1.5.3 Data Types
A data type in a programming language is a set of data with values having predefined characteristics
such as integers and characters.
The language usually specifies the range of values for a given data type, how the values are processed
by the computer and how they are stored. Storage representations and machine instructions to handle
data types differ from machine to machine.
The variety of data types available allows the programmer to select the type appropriate to the needs of
the application as well as the machine. C supports a number of data types. If they are not enough,
programmers can define their own data types.
C supports three classes of data types:

• Primitive (or basic) data types –these are the fundamental data types supported by the language.
These can be classified as integer types, floating point types and character types.

• User defined data types – based on the fundamental data types users can define their own data
types. These include type defined data types (using typedef keyword) and enumerated types (using
enum keyword).

• Derived data types – programmers can derive data types such as arrays, structures, unions and
pointers by combining several data types together.
1.5.3.1 Primitive Data Types
The C language supports five primitive data types; namely integers (int) floating point numbers (float),
double precision floating point numbers (double), characters (char) and void (void). Many of these data
types can be further extended as long int and long double. Each of these data types requires different
storage capacities and has different range of values (depending on the hardware) as shown in Table 2.2
below.

Table 2.3 – Basic C data types (on a 32-bit machine)


Data Type Size of Range of Values
Bits
Char 8 -128 to +127

Int 32 -2147483648 to 2147483647

Float 32 3.4e-38 to 3.4e+38 (accuracy up to 7 digits)

Double 64 1.7e-308 to 1.7e+308 (accuracy up to 15 digits)

Void 0 Without value (null)

Table 2.4 –Basic C data types and modifiers (on a 32-bit machine)

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -3-


1.5.3.2 Modifiers
The basic data types can be modified by adding special keywords called data type modifiers to produce
new features or new types. The modifiers are signed, unsigned, long and short. For example short int
represents fairly small integer values and require half the amount of storage as regular int numbers.
Except with void type, the modifiers can be used with all the basic data types as shown in Table 2.4

1.5.4 Variables
A variable is a value that can change. A variable is described as a reserved memory location that can
hold a value of a certain data type.
Programmers refer to a variable by its name (identifier) so that it can be accessed during the course of
the program. Programmers cannot use any of the keywords as variable names as stated in the rules that
govern the formulation of identifiers.
int age = 23; // age is a variable
1.5.4.1 Declaring Variables
In order to use a variable in C, the programmer must first declare it specifying the data type. The most
important restriction on using a variable in C is that they have to be declared at the beginning of the
program.
Declaring a variable refers to reserving named space in memory where data of a specified data type
is stored.
The syntax to declare a new variable is to first write the data type then followed by a valid variable
identifier as given in the following examples:

inta;

float total;

unsignedint number_of_students;

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -4-


char gender;
Above set of expressions declared:

• variables “a” as an integer,


• “ total” as a floating point number,
• “number_of_students” as integer (since there are no negative number of students) and
“gender” as a character (a person can either be Male ‘M’ or Female ‘F’).
Multiple variables belonging to the same data type can be defined as separate set of expressions or by
listing variable names one after the other (should be separated by a coma sign ( ,)).Consider the following
examples:

int a;
int b;

float total;

float sub_total;

above variables can also be defined


as:

int a, b;

float total, sub_total;


1.5.4.2 Initializing a Variable
After declaring a variable it may be initialized with a suitable value. In C, an uninitialized variable can
contain any garbage value therefore it is good practice that the programmer ensures that all the variables
are initialized before using them in any of the expressions.

int a; //variable a is declared as an integer


a = 10; //variable a is initialized with value 10
Initializing a variable can be done while declaring it, just after declaring it or later within the code (before
accessing/evaluating its value within an expression).

int age = 10;


1.5.4.3 Constants
The value of a constant cannot be changed after an initial value is assigned to it.The C language supports
two types of constants; namely declared constants and defined constants. Declared constants are more
common and they are defined using the keyword const. With the const prefix the programmer can
declare constants with a specific data type exactly as it is done with variables
const float pi = 3.141;
Programmers can define their own names for constants which are used quite often in a program.
Without having to refer to a variable such a constant can be defined simply by using the #define
preprocessor directive. These are called defined constants. Following expression illustrates the use of
the #define pre-processor directive.
- Ndejje University - IT 1107 / CS 1107 Principles of Programming -5-
#define pi 3.141

How a #define Works


The precise action of the #define directive is to instruct the compiler as follows: "In the source code,
replace CONSTNAMEwith literal." The effect is exactly the same as if you had used your editor to go
through the source code and make the changes manually. Note that #define doesn't replace instances of
its target that occur as parts of longer names, within double quotes, or as part of a program comment.
For example, in the following code, the instances of PI in the second and third lines would not get
changed:
#define PI 3.14159
/* You have defined a constant for PI. */
#define PIPETTE 100

Defining Constants with the const Keyword


The second way to define a symbolic constant is with the const keyword. const is a modifier that can
be applied to any variable declaration. A variable declared to be const can't be modified during
program execution--only initialized at the time of declaration. Here are some examples: const int
count = 100; const float pi = 3.14159;
const long debt = 12000000, float tax_rate = 0.21;

const affects all variables on the declaration line. In the last line, debt and tax_rate are symbolic
constants. If your program tries to modify a const variable, the compiler generates an error message, as
shown here:
const int count = 100;
count = 200; /* Does not compile! Cannot reassign or alter */
/* the value of a constant. */

A program that demonstrates the use of variables and constants.


1: /* Demonstrates variables and constants */ 2:
#include <stdio.h>
3:
4: /* Define a constant to convert from pounds to grams */ 5:
#define GRAMS_PER_POUND 454
6:
7: /* Define a constant for the start of the next century */ 8:
const int NEXT_CENTURY = 2000;
9:
10: /* Declare the needed variables */
11: long weight_in_grams, weight_in_pounds; 12
int year_of_birth, age_in_2000;
13:
14: main()
15: {
16: /* Input data from user */

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -6-


17:
18: printf("Enter your weight in pounds: ");
19: scanf("%d", &weight_in_pounds);
20: printf("Enter your year of birth: "); 21:
scanf("%d", &year_of_birth);
22:
23: /* Perform conversions */
24:
25: weight_in_grams = weight_in_pounds * GRAMS_PER_POUND; 26:
age_in_2000 = NEXT_CENTURY - year_of_birth;
27:
28: /* Display results on the screen */
29:
30: printf("\nYour weight in grams = %ld", weight_in_grams);
31: printf("\nIn 2000 you will be %d years old\n", age_in_2000);
32:
33: return 0;
34: }
Enter your weight in pounds: 175
Enter your year of birth: 1960
Your weight in grams = 79450
In 2000 you will be 40 years old
ANALYSIS: This program declares the two types of symbolic constants in lines 5 and 8. In line 5, a
constant is used to make the value 454 more understandable. Because it uses GRAMS_PER_POUND,
line 25 is easy to understand. Lines 11 and 12 declare the variables used in the program. Notice the use
of descriptive names such as weight_in_grams. You can tell what this variable is used for. Lines 18 and
20 print prompts on-screen. The printf() function is covered in greater detail later. To allow the user to
respond to the prompts, lines 19 and 21 use another library function, scanf(), which is covered later.
scanf() gets information from the screen. For now, accept that this works as shown in the listing. Later,
you will learn exactly how it works. Lines 25 and 26 calculate the user's weight in grams and his or her
age in the year 2000. These statements and others are covered in detail in the next chapter. To finish the
program, lines 30 and 31 display the results for the user.

END

THANK YOU

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -7-

You might also like