0% found this document useful (0 votes)
35 views13 pages

Chapter Four

Uploaded by

n64157257
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views13 pages

Chapter Four

Uploaded by

n64157257
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

CHAPTER FOUR: C Programming: - Constants, Variables and Data Types

Chapter Objectives
By the end of the chapter the learner should be able to;
 Describe the C program character set and Trigraph characters
 Describe the C Program Tokens;
Constants, Keywords, Strings, Identifiers Special symbols and Operators
 Declare and assign values to C variables.
 Differentiate between Constants and Symbolic Constants

1.1. C Program Character set


A computer program consists of instructions formed using certain symbols and words according to a
rigid rules called syntax rules (Grammar) of the programming language used. Each program instruction
must confirm precisely to the syntax rules of the language. Like all programming languages, C has its
own set of vocabulary and grammar

The characters that can be used to form words, numbers and expressions depend upon the computer on
which the program is run. The characters in C are grouped into the following categories;
1. Letters : Upper case A ……. Z and Lower casa a ……..z.
2. Digits: 0……..9
3. Special characters
, comma & ampersand
. period ^ caret
; semicolon * asterisk
; colon - minus sign
? Question mark + plus sign
‘ apostrophe < opening angle bracket (less than
“ quotation mark sign
! exclamation mark > angle bracket or greater than sign
| vertical line ( left parenthesis
/ slash ) right parenthesis
\ back slash ] right bracket
~ tilde [ left bracket
_ under score { left brace
$ dollar sign } right brace
% percent sign # number sign

C compiler ignores white spaces (Blank, Horizontal tab, Carriage return, New line Form feed) unless they
are a part of a string constant. White spaces may be used to separate words but are prohibited between the
characters of keywords and identifiers.

Trigraph characters
C has the concept of “trigraph” sequences to provide a way to enter certain characters that are not
available on some keyboards. Each trigraph sequence consists of three characters (two question marks
followed by another character
??= #number sign
??( [ left bracket
??) ] right bracket
??< { left brace
???> } right brace
??! | vertical line
??/ \ back slash
??/ ^ caret
??- ~ tilde

1.2. C Program Tokens


In a passage text, individual words and punctuations marks are called tokens. Similarly in a C program
the smallest individual units are known as C Tokens. C program has six types of tokens shown in figure
4.1 below and C is written using this tokens and the syntax of the language.

C Tokens

Key Words Constants Strings Operators

Identifiers Special Symbols


Figure 4.1 C Tokens

4.3. Reserved words / Key words and Identifiers


Reserved words (occasionally called keywords) are one type of grammatical construct in programming
languages. These words have special meaning within the language and are predefined in the language’s
formal specifications.

Every C programs word is classified as either a keyword or identifier. All keywords have the fixed
meaning and these meaning cannot be changed and acts as the building blocks for program statements.
List of ANSI C keywords are listed in table 3.2 below.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Table 4.1. ANSI C Keywords

Identifiers refer to the names of variables, functions ad arrays. These are user defined names and consists
of a sequence of letters and digits, with a letter as a first character.

Rules for Identifiers


1. First letter must be an alphabet (or underscore).
2. Must consist of only letters, digits or underscore
3. Only first 31 characters are significant
4. Cannot be a Keyword.
5. Must not contain white spaces

4.4 Constants
Constants in C Program refers to fixed values that do not change during the execution of the program.
Figure 4.2 below shows the types of constants supported by C program
Constant
Numeric Character String

Integer Real Single character String


Constant Constant constants constants
Figure 4.2 C program Constants

4.4.1. Integer Constants


An integer constant refers to a sequence of digits. There are three types of integers namely;-
1. Decimal integer: Digits 0 – 9 example +78, -321 Embedded spaces commas and non digit characters
are not permitted between digits
2. Octal integer: consists of any combination of digits from the set 0 trough 7, with a leading 0.
Example 037, 0, 0435, 0551
3. Hexadecimal integer: a sequence of digits preceded by 0x or 0X, they may also include alphabets A
through F or through f. A through F represents number 10 to 15. Examples 0X2, 0x9F, 0Xbcd

4.4.2. Real Constants


Real Constants are used to represent quantities that vary continuously, such as distance, height,
temperatures, prices etc. which integer constants are inadequate to represent. These quantities are
represented by numbers containing fractional parts example 12.58. Such numbers are called real (floating
point) constants. A real number may also be expressed in exponential (or scientific) notation example the
value 215.66 may be written as 2.1566e2 in exponential notation. e2 means multiply by 10 2

4.4.3. Single Character Constants


A single character constant contains a single character enclosed within a pair of single quote marks.
Example ‘5’, ‘x’, ‘ ‘ etc. The character constants have integer values known as ASCII values. To find out
the ASCII value for any character eg “a” use the following program

include<stdio.h>
include<conio.h>
main()
{
printf(“%d”, ‘a’);
getch();
}
The program will output 97as the output. Since each character constant represents an integer value, it is
possible to perform arithmetic operations on character constants.

4.4.4. String Constants


A string constant is a sequence of characters enclosed in double quotes. They may be letters, numbers,
special characters and blank spaces. Example “hello’, “1987”, “5+5” etc. Note ‘X’ is not the same as “X”.
A string constant does not have a ASCII value.

4.4.5. Backslash Character constants


C supports some special backslash constants are used in output functions Example ‘\n’ stands for new
line. Though having two characters they represent one character, these combinations are known as escape
sequences. Table 4.2 below gives a list of the C backslash constants

‘\a’ audible alert (bell) ‘\t’ carriage return ‘\?’ question mark
‘\b’ back space ‘\v’ vertical tab ‘\\’ backslash
‘\f’ form feed ‘\” single quote ‘\0’ null
‘\n’ new line ‘\”’ double quote
Table 4.2. C program backslash constants

4.5 Variables
A variable is a data name that may be used to store a data value. Unlike constants that remain unchanged
during the execution of a program, a variable may take different values at different times during
execution. A variable name should be chosen in a meaningful way so as to reflect its function or nature in
the program. Example price, rate, total, amount etc. Naming follows the same rules as stated in the
identifiers section. Valid variable names include;
 John, Value distance, Sum1 etc
Invalid variable names includes;
 123, (area) % etc
4.6. Data types
C program is rich in its data types. Storage representations and machine instructions to handle constants
differ from machine to machine. ANSI C supports three classes of data types;
1. Primary (or fundamental) data type
2. Derived data types
3. User-defined data types
The derived data type and the user-defined data types will be discussed in later chapters

4.6.1. Primary data types


All C compilers support five (5) fundamental data types namely Integer (int), Character (Char), Floating
point (float), Double-precision floating point (double) and Void. Figure 4.4. below show C program
primary data types. The size and range for the primary data types in a 16-bit machine are shown in table
4.5

Integer Character
Signed unsigned type Char
int unsigned int signed char
short int unsigned short int unsigned char
long int unsigned long int

Floating Point

Float double long double void

Figure 4.4. Primary data types in C

Table 4.5. Size and Range of basic data types on a 16-bit machine
Data type Range of values
char -128 to 127
int -32,768 to 32,768
float 3.4e-38 to 3.4e +38
double 1.7e-308 to 1.7e+308
4.6.2. Integer data types
Integers are whole numbers with a range of values supported by a particular machine. Integer data types
are defined in C as int. C supports three classes of integer storage, short int, int and long int in both
signed and unsigned forms.

4.6.3. Floating point types


Floating point (or real) numbers are stored in 32 bits (in all 16-bit and 32-bit machines) with 6 digits of
precision. Floating point data type is defined in C as float. When the accuracy provided by float is not
sufficient, the type double can be used to define the number.

4.6.4. Void types


Void data type has no values, and usually used to specify the void type of function which does not return
any value to the calling function example main(void)

4.6.5. Character type


A single character can be defined as character (char) type of data. Characters are usually stored in 8-bit
(one byte ) of internal storage.

4.7. Declaring variables


Variable to be used in a C program need to be declared to the C compiler. Declaration of variables does
the following two things; it tells the compiler what the variable name is and it specifies what type of data
the variable will hold. A variable must be declared before it is used in a C program. A variable can be
used to store a value of any data type. Syntax for declaring a variable
data_type v1, v2, vn;
v1, v2 and vn are names for variables and the variables are separated with commas. A declaration
statement must end with a semi-colon.
examples
int count;
int count, price
double ratio;

Declaration of variables is done immediately after the opening brace ({) in the main() function body.
Variables can also be declared outside the main() function either before or after. When declared before
the main() function they are called Global variables and can be used in all the functions in the program.
Global variables do not need to be declared again in other functions and are called external variables.
Variables declared within a function are called local variables as they are only visible and meaningful
inside the function they are declared. Example of local variable declaration;
main()
{
int code;
float x, y;
char c;

statements;
}

4.7.1. User defined Type Declaration


C supports type definition that allows a programmer to define an identifier that would represent an
existing data type. These data types can later be used to declare variable. Format;
typedef type identifier;
where type refers to existing data type and identifier refers to the new name given to the data type. The
existing data type may belong to any class of type, including the user-defined ones. This method only
changes the name of the identifier and not the data type. Eexamples
typedef int units;
typedef float marks;
Once defined the new identifiers names can be to declare variable example
units code;
marks x, y;

4.8. Declaration of Storage Class


Variables in C have not only the data type but also storage class that provides information about their
location and visibility. The storage class decides the portion of the program within which the variables are
recognized. C provides a variety of storage class specifiers that can be used to declare explicitly the scope
and lifetime of a variable. This concept is important only in multifunction and multiple file programs.
4.9. Assigning Values to Variables
Variables are created for use in the program statements. Values can be assigned to variables using the
operator ‘=’ in a C program or through reading the values from the keyboard using the scanf() function.

4.9.1. Using the ‘=’ operator


The format is as follows; variable_name = value; OR variable_name = constant;
The assignment statement implies that the value of the variable on the left of the ‘equal sign’ is set equal
to the value of the quantity on the right. Example
gross_salary = basic_salary + commission;

Variables can be assigned an initial value when declaring it in a process called initialization, using the
format;
data type variable_name = constant

4.9.2. Reading data from the keyboard (scanf())


Another way of assign value to variables is to input data through the keyboard using the scanf function.
The general format for scanf() is as follows
scanf(“control string”, &variable1, variable2, …..);

The control string contains the format of data being received, the ampersand & before the variable name
is an operator that specifies the variable name’s address. Example
scanf(“%d”, &marks);

When the computer encounters this statement, the programs stops and waits for the value marks to be
keyed in through the keyboard and the <enter key> pressed. “%d” signifies that an integer data type is
expected. The use of scanf() provides an interactive feature and makes the program more user friendly.

Program Example 4.1. Program to show use of Scan for interactive programming
#include<stdio.h>
#include<conio.h>

main()
{
int number;
printf(" Enter an integer number\n");
scanf("%d", &number);

if (number > 100) /* Statement does not end with a semi-colon */


printf("Your number is smaller than 100\n\n");
else
printf("Your number is less than 100\n\n");

getch(); /* Pause the out put on the Screen */


}
Out Put

4.10. Defining Symbolic Constants


When the use of a numeric value in a program is not very clear, especially when the same value means
different things in different places C allows the use of symbolic name to differentiate the different values
and enhance the understandability of the program. The format for defining a symbolic constant is as
follows
 #define symbolic_name value of the constant
Example
 #define PASS_MARK 50
 #define MAX 50

Symbolic names are constants and not variables and thus do not appear in the declaration section. The
rules that apply to the #define statement which defines a symbolic constants are;
 Symbolic names have the same form as variable names. Symbolic names are usually written in
CAPITAL letters to visually distinguish them from the normal variable names.
 No black space between the # and word define is permitted
 ‘#’ must be the first character in the line
 A black space is required between #define and symbolic name and between the symbolic name and
the constant.
 #define statement must not end with a semicolon.
 After definition, the symbolic name should not be assigned any other value within the program using
an assignment statement. Example MAX = 200; this is illegal
 Symbolic names are NOT declared for data type. Its data type depends on the type of constant.
 #define statements may appear anywhere in the program but before it is referenced in the program,
Usual practice is to place the #define statements at the beginning of the program.

Program Example 4.2. Program to calculate the Average of 10 number entered through the
keyboard
#include<stdio.h>
#include<conio.h>
#define N 10
main()
{
int count;
float sum, average, number;
sum = 0;
count = 0;
while(count < N)
{
printf("Enter any number ");
scanf("%f", &number);
count = count + 1;
}
average = sum/N;
printf(" N = %d Sum = %f", N, sum);
printf("Average = %f", average);
getch();
}
Out put
Chapter Review Questions
1. What is a variable and what is meant by the “value” of a variable?.
2. What is variable initialization?.
3. Find error in the following declaration statements
int x;
float letter, DIGIT;
double p, q;
n, m, z INTEGER;

4. Write a program to read two floating point numbers using scanf statement assign their sum to an
integer variable and then output the values of all the three variables,

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy