Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

3-1

Chapter
3

Constants, Variables & Data Types

3.1. Introduction
kind of data consisting of numbers,
is designed to process certain
A programming language known as "information. The
task of processing of
useful output
characters and strings to provide called "program". These
instructions
executing a sequence of pre-instructions
data is accomplished by known as "syntax rules"
and words according to some rigid rules
are formed using certain symbols and grammar. In this chapter
we
C has its own vocabulary
or "grammer". Like any
other language,
variables and data types.
discuss the concepts of constants,

3.2. Character Set


In C language a character set is used to form words, Note
use a
which are then Some computer systems might
vanables, keywords, constants and expressions mast
In C characters diferent character set however
combined to form statements and instructions. values for 0 to 127
Use the same
ww
are grouped into following categories wwwwww w

Table 3.1
A,B,...... Y, Z
1. Alphabets Uppercase
a,b,. .y, Z
Lowercase
9
2. Digits All decimal digits 0,1,2.....8,
)_+-={}l?7;|
3. Special Symbols *!@# %^& *
new line
4. White Spaces tab, blank spaces, carriage return,

3.3. CTokens in
tokens. Similarly,
In a marks are called these these
passage text,
« individual words and punctuation
written with
the help of

kens. There
smallest individual unit is called C-token. C programs are
are shown
here are six types of tokens as
Or tokens in C language. C has
-2 Constants, Variables & Data TyDee
pes

CTOKENS

KEYWORDS OPERATORS

CONSTANTS STRINGS

SPECIAL
IDENTIFIERS SYMBOLS
Figure 3.1
3.4. Keywords and Identifiers
3.4.1. Keywords
Keywords are the words whose meaning is
to
compiler .The keywords cannot be used asalready
C explained Definition
variable Definition
because if we do so we are names
trying to assign a new meaning to the Keywords are the words whose
keyword.Keywords are called reserved
words. All keywords must meaning
meaning isis already
already defined
defined in
n the
be written in lowercase.
In C there are 32 Compiler
keywords. These are
Table 3.2
auto
double int
break else struct
case
enum
long switch
char register typedef
extern
const return union
float
continue short unsigned
for
default goto
signed void
do sizeof volatile
if
static while
3.4.2. Identifiers
dentifiers refer to the
name of
ise
uCea names and consist variables, functions, arrays, strings, e at
an
1aenuiier must an of alphabets, digits structures, aracter
alphabet. No special symbol both in upper and lower cases. The
nist
Examples: rsd, bs_salary is used as identifier
(except unaetoe
Constants,
Variables
&Data Types 3-3

3.5. Constants

constant is a data storage location used by your program whose value does not change
C
A
ino the execution of the program. Constants are classified into two categories.

cONSTANTS

NUMERIC CHARACTER

SINGAL
REAL STRING
INTEGER CHARACTER

Figure 3.2

DO use constants to make your programs easier to read.


a value to a constant after it has already
been initialized.
DON'T try to assign

3.5.1. Numeric Constants


or
the digits (0,1,2...9). Numeric may constants
These the constants those are formed from
are
are of two types-
-ve. Numeric constants
may be +ve or
may not have a decimal point. They
3.5.1.1 Integer Constants
used in C programs. Decimal integers, octal
Integer constants the sequence digits that are
are
constants. Decimal integers
are
the three types of numeric
integers and hexadecimal integers are
sign. You can use
an optional + or
Decimal digits can be preceded by
formed from digits 0-9.
between the digits.
spaces, comas special characters
and
Examples:-6474,897-98,0.
into following categories
Integer constants are divided from 0-7. These
constants are

constants consists
of combination of digits
a) Octal integer
character).
auways preceded by leading o or O(English
0-9 and
Examples :-025,05245,00,-035. combination of digits from
are represented by characters A-F
respectively.
D) Hexadecimal integer constants represented by
10-15 are
chara A-F alone. Digits from oX or ox.
ETS from or
preceeded by
OX or Ox or

are always
a l integer c o n s t a n t s
Examples:-Ox44,0X9889,0X123A etec. from 0-9

represented by
combination of digits
constants are
Decimal integer
Example 23,566
3-4 Constants, Variables & Dataa Types
T
Rules for constructing integer constant
1. An integer constant must have at least one digit.
2. It must not have a decimal point.
3. It can be either positive or
negative.
4. It is assumed to be positive, if there is no sign
specified.
5. Spaces and commas are not allowed with in it.
6. It can have values from 32768 to +32768
Examples of valid integer constants are: 346,134,3201,-665
3.5.1.2 Real constant
Real constants are used to
represent the
quantities are distances, weights, heights andquantities
that vary rapidly. The
examples of suh
prices. Real constants contain fractional
accurately represent such quantities. Real constants are also called parts
constants are further as
floating point
of two types: real constants in fraction form and real constants constants. Red
form. in exponentia
The fractional form real
constants are similar to
Some valid real constant in integer constants with added decimal
fractional form precision
Rules for
are
constructing real constants in fraction form 120.588,8484.345 and 97.25.
Real constants are also
called
namely, fractional and exponential floating
form.
point constants. They can be divided into two fo
constructing real constants Following are the rules that must be followed
1. It must expressed fractional form.
in w
have at least one
2. It must have a digit.
decimal point.
3. It could be
either positive or negative.
4. Positive is
considered as default
5. Commas and spaces are not sign.
Examples of some real constantsallowed in a real constant.
are
Real constants fractional
forms 54.564,-65.235, and 5555.78.
numbers. Due to this, real constants in are not adequate for
written as 5.5E9 when exponential form representing very
are used. For
small and very
very Sma
andexponent. The partrepresented in
exponential form, example, » 0000
appearing before "E" is called as constant contains two pat antis
a real
can

Exponent. ed
Mantissa and the part after it called
For example, in constant
valid examples of real 125.3e5, 125.3 is the
constants in
exponential mantissa part and 5 is the
part. So

Rules for constructing real constants in form are 4.le12, -56.3e3 etc. expone
1. The mantissa and the exponent Exponent form
part must be
2. The mantissa may be
negative or
positive.
separated by character e.
3. The exponent must contain
4. The default sign for both
number, which must
be an integer of any
mantissa and the sign
5. It can have values from exponent is positive.
range -3.4e38 to
Examples: +2.8e-4, 2.3e2, -0.5e-1. 3.4e38.
Variables & Data Types
Constants, 3-5
3.5.2. Character constants
In addition to numeric constants, the programs also need to deal with characters and strings.
In.
The character const nstants are used to express quantities like name, place or gender. They can be a
s i n g l e c h a r a c t e r or a group of characters or back slash character constants.

character
constant
3.5.2.1. Single
A single character constant contains a single character. They are enclosed with in single quotation
narks. A character constant
can be either single alphabet, a single digit or a single special symbol
a

and it must be enclosed in single inverted commas. A character constant can


t of c character set
a single character.
contain
onlyExamples: 'a','d','1,'2'.
character constant
3.5.2.2. String enclosed with in double quotation
characters is called string. These constants are
A group of
marks.
Examples:- "Mandeep","Handa","7898","5+7".

3.6. Variables
will frequently want your program Definition
As programmer, you
a
if
"remember" a value. For example, your program
requests a A variable is a quantity whose
to
value from the user, or if
it calculates a value, you
will want to value may vary during execution.
remember it somewhere so you
can use it later. The way your t is a store house for a data item
remembers things is by using
variables. Itis the name given to the stored.
program value is
be assigned different
values at various places location where the
A variable can
be declared before it is
used in a
in the program. A variable must
program.
Example: int b; integer value." A
hold one
called b that is able to
want to create a space store a value
This line says, "I integer). You can
type (in this case, int, an
b) and a
vanable has a name (in this case,
in b by saying something like:
b 5; like:
YOU can use the value in b by saying something
printf("od", b);
for variables
n C, there are several standard types
i n t - integer (whole number) values
float floating point values
as "m" or "Z)
Char single character values (such
Rules for creating Variable character ().
underscore
letters, digits, and the
can contain is also a legal first
character.
ame letter. The
underscore
character of the n a m e must be a
rst rerer
but its use is not Count
recommended. count and
lowercase letters).
Thus, the names

(that is, upper- and


to ers
ttwo different or u c
variables. word that is part
A keyword is
a
variable names.
can't be used as
lano rds
language.
3.6
Constants, Variables & Data TyYDes

DO use variable names that are descriptive.


DO adopt and stick with a style for naming your variables.
DO understand the number of bytes that variable types take for your computer.
DO initialize variables when you declare them whenever possible.
DON'T start your variable names with an underscore unnecessarily.
DONT name your variables with all capital letters unnecessarily.
DON'T use a variable that hasn't been initialized. Results can be unpredictable.
DON'T use a float or double variable if
you're only storing integers. Although they will work,
using them is inefficient.
DON'T try to put numbers into variable
types that are too small to hold them.
DONT put negative numbers into variables with an
unsigned type.
3.7. Data Types
When programming, we store the variables in our
computer's memory, but the computer has to know what kind of Note
data we want to store in them, since it
is not going to
Data types tells the computer how
same amount of occupy the many bytes to be reseved and whal
memory to store a simple number than to store
single letter or a large number. This can be atype of data can be stored. e

help of data types.


achieved with the
Data
type is the
The memory in our description of the
is the minimum amount of
computers is organized in
bytes. A byte nature and range of data that can be
memory that we can manage in C. A stored in variable.
byte can store a relatively small amount of
integer between 0 and 255). In addition, thedata:
one single character or
a small
computer
integer (generally
come from
grouping several
can
manipulate more complex data
types th
bytes,
such as long numbers or non-integer numbers.
Data types are
categorized into following category
DATA TYPES

PRIMARY VOID DERIVED


USERDEFINED

INTEGER FLOAT CHARACTER ARRAYS


STRUCTURE
POINTERSs UNIONS
ENUM
TYPEDEF
SHORT SIGNED FLOAT SIGNED
SHORT UNSIGNED DOUBLE UNSIGNED
LONG SIGNED LONG DOUBLE
LONG UNSIGNED
Figure 3.3
Constants Vanabies & Data Types
3.7
Primary Data Type
1. This data type can be used to point to a single value. It represents the smallest unit of information
that can be stored in a variable. It is also called simple or fundamental or basic data type. t can
be categonzed as :

(a) Integer Data Type


)Real Data Type
c)Character Data Type
(a) Integer Data Type: Integer data types are used to store numeric data items. They can
store whole numbers as well as numbers with fraction. The data types of this categories are
integerint). short integershort int) and long integertlong int). In additionto these types
unsigned int. unsigned short int and unsigned long int data types also fall under this category.
int occupies one word in memory. The length of the words may vary and it is typically 16
or 32 bits.
Example int i=20:
Integer data types are divided into 4 category
(a) short signed int
b) short unsigned int
(c) long signed int
(d) long unsigned
(b) Real Data Type : programming sometimes we want to store the vaule in fractions for
In
C allows this with the
example we want to enter the salary of the employee. programming
data types are used to store numbers with
help of floating point data type. Floating point
fractions.
Example float a=110000.562
Float data type is divided into three categories
(a) float
(b) double
(c) long double
store character data items. The
C) Character Data Type Character data types are used to
:
mark('A). Char and unsigned
values to be stored in them are enclosed in single quotation

char are the two character data types.


Character data type is oftwo types
(a) signed char
(b) unsigned char
2Derived Data Type or Structured DataType between
structured data types. The main difference
called
Ved data types are also as
derived data type can handle more
tnan

ental and derived data type is that a variable otf


at a time where as a variable of fundamental
data types can handle only one vialuea
data
a e pointers. The details of these
data types in this category are arrays, Strings,
tvnee
Ypes are discussed in the
following chapters.
3 User Defined Data
Thes Type contain user specified
values. T hey
the They
edata types that are defined by is used to declare user defined data type
user.
contain
e rdefined values. Enum keyword
3.8 Constants, Variables & Data
Tv
User defined data types provides a way to define your own data types and alsocan da
value of a variable or an identifier stores into the main memory. There are two
types
es ofof
define uethe
defined data types. These are Enumerated and typedef data type.
Enumerated data type
It is designed specifically for variables that can take small set of possible values, The .
that a variable of enumerated data type can take are listed by the
programmer. The advan
value
of enumerated data type is that it makes the listing more readable
especially when antage
the pro.
is more complicated and multiple programmers are working on it.
The format of Enumerated data
rogran
type is

enum name Optional

vall, val2, vals,............valn;


Where name is the name of the
enumerated data type and vall, val2,.....valn are
varnable of type name can take.
Enumeration name is optional. For values tha
example, enum day.
sunday, monday, tuesday, wednesday,
thursday, friday, saturday
In above declaration, keyword enum is followed
followed by set of values enclosed in by optional enumeration name day
curly braces na
called enumerators.
By default, the value of first separatedby commas. The set of values u
enumerators are assigned the enumerator is assigned0, and the
value of enumerator that subseq
value one more than the
follows it. In our
example
Saturday is assigned 6. Sunday assigned value 0, Monday is
is immeula
assigned
value 1 ana s
Program: To illustrate the use of
#includestdio.h> Enumerated data type
#include<conio.h>>
main )

enum day

sunday, monday, tuesday,


dofweek; wednesday, thursday, friday, saturday
dofweek=monday;
printf( Day of Week is %d",
getch): dofweek);

Output
Day of Week is 1
Constants, ariables & Data Types
3.9
umerated data type
Program:
#include<stdio.h>

#include<conio.h>

main ()

enum

red. green, blue, yellow, white, black


Jcolor:
for(color=red;color<=black:color++)

printf(" n *d", color)


getch);

Output
0

the
enumerators can be modified explicitly by initializing
The default integer values of
enumerators with new values.

Program: Enumerated datatype.


#include<stdio.h>
#include<conio.h>
main ()

enum day

Thursday, Friday, Saturday


Sunday =5, Monday, Tuesday, Wednesday,

enum day dofweek;


dofweek=monday:
print(" Day of Week is %d ", dofweek)
getch();

Output is
Day of Week is 6
remaining
In above pro value 5, the
explicitly the
example, Sunday is assigned
values
ues
incrementprogramming
by 1.
3-10
Constants,
iables &Data
typedef Data Type Type
It allows defining new data types that are equivalent to existing data
The format for type.
typedef data type
typedef type name;
Where type is either built in data
the type. type or user defined data type and name is the
new nama
The typedef keyword tells the
type.
compiler to
recognize the word name
as
synonymous
Example. The following C statement illustrates the use of
typedef float
typedef data type.
real;
redefine the data type float to
real.
Program: To illustrate the use of
#include <stdio.h>
typedef
typedef float real;
main()

real a,b,c,sum;
printf("Enter the value of a,b,c"):
scanf(%f%f%f",&a,&b,&c);
sum =a+b+c;

printf("Sum-%f',sum);
#include <stdio.h>
main ()

typedef enum
unday, Monday, Tuesday, Wednesday, Thursday, Friday,
day: a
day dofweek;
dofweek=monday;
printf" Day of Week is %d", dofweek);
Output
Day of Week is 1
4. Void Data
Void data Type
type represents
empty or null.
Vanables & Data Types
Constants, 3-11
t VOU have a summary of the basic fundamental data types in C, as well as the range of

values that can be represented with each one :


Table 3.3

Data Type Bytes Default Range Represent


signed char 1 -128 to 127 hc

0 to 255 Toc
Unsigned char
short signed int 2 -32768 to 32767 %d

short unsigned int 2 O to 65535

4 2147483648 to 2147483647 old


long signed int
0 to 4294967295 olu
long unsigned int
3.4e38 to +3.4e38 Tof
Float
-1.7e308 to +1.7e308
Double 8
-1.7e4932 to +1.7e4932 %Lf
long double 10

Things to Remember
is called character set.
Collection of alphabets, digits, special
symbols and white spaces
execution of a program.
value that do not change during
A constant refers
to a

In C the smallest unit are called tokens. 32 keywords(Reserved


not be changed .C has
eywords have fixed meaning which
can

words). erc.
functions ,arrays, strings
aentifiers refer to the names of variables,
or underscore(-).
be an alphabet
C irst character of an identifier must
Numeric constants can be integer and real.

Integer constant may be in Octal or Hexadecimal form. store any


vaue.

location that has been used to


to a
I S name given
memory

Data type represents the type of value carried in the variable.


There
here are four basic data float, double.
types i.e. character, integer, constans.
Character const
Constants can be single character constants
or string

Four fundament
dnentals data are available in
types
Ci.e. int, float,
char, douoi

Enum is used to define


user defined data type.
Void data
type represents null.
3-12 Constants, Variables & Data Types
Solved Questions
Very Short Questions
Q.1. What do you mean by a constant?
Ans. A constant refers to the value which do not
change during the execution of progam
Q.2. How many types of constants are supported by C?
Ans. There are basically two types of constants i.e. numeric and
string.
Q.3. What do you mean by data type?
Ans. A data type defines the amount of
memory required by a variable.
Q.4. How many keywords supported by C language
Ans. Csupports 32
keywords.
Q.5. Which data type is used to store very long
Ans. Unsigned long int.
positive value?
Q.6. What is difference between 'B° and "B°"?
Ans. B' is called character where as "B" is called string.
Short Questions
Q.1. Explain the character set of
Ans. In
C language?
C language a character set is used to form words, variables,
expressions which then combined to form keywords, constants a
statements and instructions. In C
are
grouped into following category- charace
Table 3.4
1. Alphabets
Uppercase A,B,...... Y,Z
Lowercase a,b,........y.z
2. Digits All decimal
3. Special Symbols
digits 0,1,2........8.9
@#% & * ()_+ -= {} ?/;
4. White Spaces
tab, blank spaces, carriage return, new line

Q.2. What is a variable? What are the rules what have to follow to declare a e

Ans. The variable is the name varia


given to memory location where our constant stores.
value of variable is vary
during the execution of the program.
Rules for constructing a variable.
The name can contain
letters, digits, and the underscore character ( .
The first character
of the name must be a letter. The underscore is also a legal
character, but its use is not recommended.
maters
Count refer to (that is. upper- and lowercase letters). Thus, the names count
two different variables.
Variables & Data Types 3-13
C o n s t a n t s

Ckeywords can't be used as variable names. A keyword is a word that is part ofthe
C language.
mean by data type ? Explain the basic data types ?
3 , What do you
Data type defines the amount of memory required by a variable, There are differet
Ans.
data types available in C language. Each data type have its own significance. For example
it of int type. and if we
If we want the to enter the total number of students .We declare
want to enter the salary of an employee it must be in float type.

DATA TYPES

J
PRIMARY VOID DERIVED USER DEFINED

ARRAYS STRUCTURE
INTEGER FLOAT CHARACTER POINTERS UNIONS
ENUM
TYPEDEF

SHORT SIGNED FLOAT SIGNED


SHORT UNSIGNED| DOUBLE UNSIGNED
LONG SIGNED LONG DOUBLE
LONG UNSIGNED

Figure 3.44

Integer Data type :


can store whole numbers as
Integer data types are used to store
numeric data items.They
short
well as number with fraction. The data types
of this categories are integerfint),
int.
in addition to these types unsigned
mteger(short int) and long integer(long int). int occupy
short int and unsigned long int data types also fall under this category.
unsigned 16 or 32 bits.
one word in The length of the words may vary and it is typically
memory.

Example int i=20;


integerdata types are divided into4 category:
(a) short signed int
(b) short unsigned int
(c) long signed int
(d) long unsigned
want

Real data type for


example
we

fractions floating
In programming som store the vaule in the helpof
ome time we want to nep
to enter the allows this
with the
with
fractions.

C programming
i data salary ofthe employee.
point used to store
n u m b e r s

type. Floating point data types are


Constants, Variables & Data Types
Example float a=110000.562
Float datatype divided into three category
(a) float (b) double (c) long double

Character data type


Character data types are used to store character data items. The values to be stored in
them are enclosed in single quotation mark("A'). Char and unsigned char are the two
character data types.
Character data type is of two types
(a) signed char (b) unsigned char

Derived data types


Derived data types are also called as structured data
fundamental and derived data type is that a types. The main difference between
variable of derived data type can handle
more than one value at a time
where as a variable of fundamental data
only one value at a time. These are also called data types can handle
types. The data types in this
are
arrays, Strings, pointers. category
User defined data
type
These are the data that
types are defined
They contains user defined values. Enumby user .They contain user specified values.
the
keyword is used declare user defined data type.
Void Data type
Void data type
represents empty or null.
Next you have a
summary of the basic fundamental data
of values that can be types in C, as well as the range
represented with each one:
Table 3.5
Data 1ype Bytes Default Range
signed char Represent
-128 to 127
Unsigned char oc
O to 255
short signed int Toc
2 -32768 to 32767
short unsigned int Tod
2 O to 65535
long signed int Tou
4
2147483648 to 2147483647
long unsigned int %ld
4 O to 4294967295
Tolu
Float 4
-3.4e38 to +3.4e38
Double 8
-1.7e308 to +1.7e308 %If
long double 10
-1.7e4932 to +1.7e4932 %Lf
Data Types
Vaniables & 3-15
C o n s t a n

Q4 How
ow many ways are there in C to represent an integer?
CC language a interger can be represented in the following ways :
Ans.

Data Type Bytes Default Range Represent


short signed int 2 32768 to 32767 od

short unsigned int 2 0 to 65535 Tou

long signed int 4 2147483648 to 2147483647 %ld

long unsigned int 4 0to4294967295 Tolu

Differentiate between a keyword and an identifier?


Q.5.
Ans.
Identifier
Keyword

reserved words. 1. Identifiers are the name given to various


1. Keywords are elements of a program such as variables,
arrays, functions etc

2. There meaning is not defined to compiler


C
already defined to C
2. Their meaning is
compiler. 3. Identifiers can be any
number because they
3. There are 32 keywords in C language.
as per user requirement.
can be constructed
construct an
There are various rules to
.There are no rules to construct a keyword4. identifier name
but they are fixed in a language. well upper case
as
are

S. 5. Both lower case as


Only lower case are used as keyword. used as identifier and
both have different

meaning.
are SUM, sum, xx etc
.
me example 6. Some example
are int, float case etc.

and variable?
Q.6. between constant
What is the difference
Ans.
Variable

Constan the execution ofthe


Variables varies during
Amstant value does not change during the 1.
ecution of program. program.

in memory
location
location
es not store in a memory. 2. It stores to memory
3. CaR is a name given
Mant 3. Variable
is stored
quantity which is fixed. where
constant

4. example X=3x+5y X=3x+5y


4. For example and y are
variables
x
in this statermet In this
statement

Tnent 3 and 5 are constants.

You might also like