Sei sulla pagina 1di 45

Chapter 3

Data in C

1
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Objectives

Learn to declare variables in C.


Learn to understand the concept of data types
in C language.
Learn to use built-in data types in C.
Learn to write programs with formatted inputoutput statements.

2
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Learning Outcomes
At the end of this chapter students will be able to
write simple C programs with,
proper declaration of variables,
and the correct use of formatted input-output
statements.

Students will also be able to write programs with


user defined data types.

3
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.1 Character Set


The character set in C can be grouped into the following
categories.
Letters
Letters can be either upper case A to Z or lower case a to z.

Digits
Digits are 0 to 9.

Special characters
Most of the special characters used in C are listed in Table 3.1.

White spaces
White spaces are ignored by the compiler until they are a part of
string.
Examples - blank space, horizontal tab, carriage return, new line
and form feed.
4
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Table 3.1: List of special characters in C


Special character

Special character

Comma

&

Ampersand

Period

Caret

Semicolon

Asterisk

Colon

Minus sign

Question mark

Plus sign

'

Apostrophe

<

Opening angle

"

Quotation mark

>

Closing angle

Exclamation mark

Left parenthesis

Vertical bar

Right parenthesis

Slash

Left bracket

Backslash

Right bracket

Tilde

Left brace

Underscore

Right brace

Dollar sign

Number sign

Percentage sign
5

Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.2 Keywords and Identifiers (1/2)


Keywords
reserved words that
are used in C
language.
The following are the
keyword set of C
language.

auto

do

goto

signed

unsigned

break

double

if

sizeof

void

case

else

int

static

volatile

char

enum

long

struct

while

const

extern

register

switch

continue

float

return

typedef

default

for

short

union

6
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.2 Keywords and Identifiers (2/2)

Identifiers

refer to the name given to program elements such


as variables, arrays and functions.
must conform to the following rules.
1.
2.
3.
4.
5.

Should contain only letters, digits and underscore.


Should not exceed 31 characters in length.
Must start with a letter or underscore.
Identifier can not be a keyword of C language.
Should not have a space.

7
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.3 Constants
A constant is an item whose value does not
change during the execution of a program.
constants in C

Integer constants
Real constants
Single character constants
String constants

8
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Integer constants
is a sequence of digits.
types:
decimal integer
consists of a set of digits 0 to 9 preceded by an optional + or
- sign.

octal integer
consists of any combination of digits from 0 through 7 with an
O at the beginning.

and hexadecimal integer.


is preceded by 0X or 0x and they may contain alphabets from
A to F or a to f.
9
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Examples
Decimal Integer
123
-51
0
54321
+100

Octal Integer
O12
O576
O100

Hexadecimal
integer
0X6
0x9A
0Xbcd

10
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Real constants
consist of a fractional part in their representation
Examples:
0.0012
-0.87
435.29
+1237.0
can also be represented by exponential notation
(scientific notation) when they are very large or
very small
12.5E09
5E10
5e-12
3.2e+6

//value is 12500000000
//value is 50000000000
//value is 0.000000000005
//value is 3200000
11

Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Single character constants


represents a single character which is enclosed
in a pair of single quote symbols.
Examples:
m M 1
;
,
All character constants have an equivalent
integer value which is called ASCII value.
For example, ASCII value for A is 65, B is 66
and Z is 90,
and ASCII value for a is 97, b is 98 and z is
122
12
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

String constants
is a set of characters enclosed in double
quotation marks.
may be consisting of alphabets, numbers,
special characters and blank spaces.
Examples:
"MMU"
"1234"
"God Bless"
"!.....?"
13
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.4 Variables
is an identifier whose value can change at any
time.
is a memory location used to store a data value.
A variable name should be carefully chosen by
the programmer so that its use is reflected in a
useful way in the entire program.

14
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Examples for variables


Valid variable names
data
student_reg_num
basic_salary
basicsalary
emp_name
average1

Invalid variable names


1stName
user name
float
emp-name

//rule 1 violated
//rule 3 violated
//rule 4 violated
//rule 5 violated
15

Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.5 Built-in Data Types in C


fundamental data types which all C compilers
accept

int Integer data type


float - Floating point data type
double - Double precision floating point data type
char Character data type

16
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Integer data type


represents whole numbers with a machinedependent range of values.
denoted by the keyword int.
C has 3 classes of integer storage, namely
short int, int and long int.
unsigned numbers are always positive and
consume all the bits for the magnitude of the
number.
17
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Floating point data type


represents real numbers (with decimal point).
is denoted by the keyword float.
Double precision floating point data type is the
same as float but with longer precision. They
are denoted by the keyword double.

18
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Character data type


represents any single character acceptable to C
compilers.
is denoted by the keyword char.

19
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Table 3.2: Size and range of data types on a 16-bit machine


Data type

Size (bytes)

Range

char

128 to 127

int

-2147483648 to 2147483647

unsigned int

0 to 4294967295

short int

-32768 to 32767

unsigned short int

0 to 65535

long int

-2147483648 to 2147483647

unsigned long int

0 to 4294967295

float

3.4 e38 to 3.4 e+38

double

1.7e308 to 1.7e+308

20
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.6 Declaration of Variables in C


Every variable used in the program should be
declared to the compiler before its first usage.
This helps the compiler to reserve enough
storage in the main memory for the variables
declared.
Syntax: data_type v1, v2, v3,..., vn;
where data_type represents any one of the builtin data types explained in Section 3.5 and v1,
v2, v3, , vn are variable names.
21
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Declaration examples
int strength, age, tvs_sold;
declares variables strength, age, and tvs_sold as integer.

float mark, temperature;


declares variables mark and temperature as float.

double

moon_distance, virus_size;

declares variables moon_distance and virus_size as double.

char

gender, result;

declares variables gender and result as character.


22
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.7 User-defined Data Type


user can define an identifier that represents an
existing data type and the identifier can later be
used to declare variables.
Syntax: typedef data_type identifier;
where typedef is a keyword, data_type
represents any built-in data type and identifier
refers to the new name given to the data type.

23
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.7 User-defined Data Type: Examples


typedef int meter;
meter length, height;

// meaningful declaration
declares meter to be integer and allows meter to
be used as a user-defined data type later in the
program.

24
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Enumerated data type


A kind of user-defined data type
Syntax: enum identifier {value1, value2,
value3,..., value-n};

where enum is a keyword, and identifier is a


user-defined enumerated data type which can
be used to declare variables that have one of
the values enclosed within the braces.
After the definition, we can declare variables and
initialise variables to one of the values enclosed
within the braces above.
enum identifier V1, V2, V3,..., Vn
25
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Enumerated data type: Example


enum gender {male, female};
enum gender person;

person = male;
First C statement declared an enumerated data type
gender with possible values male and female.
The second one declares a variable person of gender
type.
Now the variable gender can have either male or female
as its values.
26
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.8 Formatted I/O


refers to getting data from the user or printing results on
the screen according to user requirements.
Input values are generally taken by using the scanf
function.
Syntax: scanf(control string, arg1, arg2,
arg3, , argn);
The control string specifies the format in which the
values are to be inputted for the variables specified by
the arguments arg1, arg2, , argn.
C expects the address (actual main memory location) of
the variables to be specified in place of arguments.
In order to find the address of the arguments, the
address operator & will be used just before the
arguments
27
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Integer format
The general format for reading an integer number is %xd
Example 1 :
scanf (%d %d, &age, &strength);
If the values input are 20 and 160, value 20 is assigned
to age and 160 to strength.
Example 2:
scanf (%2d, &age);
Here, 2 specifies the width of the field, 2 digits only.
Suppose the input data was 101, the number 10 will be
assigned to age instead of 101.
28
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Float format
The general format for reading a float number is
%f
Example:
scanf (%f %f , &mark, &temperature);

With input data 84.3 and -5.3, the value 84.3 is


assigned to mark, and -5.3 to temperature.
If the number input is a double data type, then
the conversion specifier should be %lf instead of
%f.
29
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Character format
The general format for reading a character is %c
Example:
scanf (%c, &gender);
Suppose that the input given is m, then m is
assigned to gender.

30
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Formatted output for printf


The printf function has the following general forms,
printf(message);
printf(control string, arg1, arg2,...,
argn);
address operator & need not be used just before the
arguments.
Formats used to output integer, float and character
values are %d, %f and %c respectively.

31
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Advanced formatted output for printf


printf(%[flag][field_width][.precision]
conversion_specifier, arguments list);

where conversion_specifier defines what is to be


printed (e.g. whether it is an integer, floating point
or character).
The other optional fields, namely flag, field_width
and precision, are used to control how data is to
be printed.

32
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Table 3.3: Additional conversion specifiers


Conversion specifier

Description

Displays an unsigned octal integer.

Displays an unsigned decimal integer.

x or X
h or l (lower case of L)

e or E

Displays an unsigned hexadecimal integer. X causes the digits 0-9 and the letters A-F to be
displayed and x causes the digits 0-9 and a-f to be displayed.
Places before any integer conversion specifier to indicate that a short or long integer is displayed
respectively. Letters h and l are more precisely called length modifiers.
Displays a floating point number in exponential notation (computer's version of scientific notation).
Example: 250.3 2.503 x 10 in scientific form and 2.503E+02 in exponential form. The E (or e)
stands for exponent.

Requires a string (char*) argument.


The characters in the string are printed until a NULL (\0) is encountered.

Displays the value of pointer (address).

Prints a percent sign

g or G

Displays a shorter version of floating point number by:


Exponent < -4 or Exponent >= 6: Exponential notation is used (same as %e or %E)
Exponent >= -4 or Exponent < 6: Similar to %f, but with no trailing zeros
Example: With %g notation,
8750000.0 8.75e+06
0.0000875 8.75e-05
8.7500000 8.75
0.8750000 0.875

Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

33

Printing with field width


Field width is the size of the field which data is printed.
If field width is larger than data, right justified is used by
default.
If field width is smaller than data, field width is increased
to fit the data.
Minus or plus sign, E or e in exponential form, decimal
point (in floating point number) will occupy one character
space in the field.
1.25 occupy 4 spaces in the field width
1.75E+05 occupy 8 spaces in the field width
-5000 occupy 5 spaces in the field width
34
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Printing with precision


The meaning of precision varies depending on data type.
In case of integers, it means minimum number of digits
to be printed and if data is too small, zeros are prefixed.
In the case of floating point numbers, for e and f, it
means the number of digits to appear after decimal point
whereas for g, it means the maximum number of
significant digits.
In the case of string, it means the maximum number of
characters to be written from the string.

35
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Effects of flag while printing


The flag field is used to align the data left or right
in the given field width.
With no flag (default), it will force right align
within the given field width, and only minus sign
of negative numbers are printed.
Left alignment would be effective when the flag
of is used.
The use of the flag + forces to precede the result
with a sign (+ or -) if the data to be printed are
integers or floating point numbers.
36
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Table 3.4: Some examples for field width and precision.


Formatted printf()

Output

printf( "(%2d)", i );

(123)

printf( "(%5d)", i );

( 123)

printf( "%.4d", i );

0123

printf( "%.7d", i );

0000123

printf( "%.3f", f );

123.457

printf( "%.3e", f );

1.235e+002

printf( "%.3g", f );

123

printf( "(%.11s)" , s);

(Multimedia )

printf( "(%5.4d)", i );

( 0123)

printf( "(%8.3f)", f );

( 123.457)

printf( "(%7.5s)", s );

( Multi)

printf( "(%5d), i);

( 123)

printf( "(%-5d)", i);

(123 )

printf( "(%+5.4d)", i);

(+0123)

printf( "(%+8.3f)", f);

(+123.457)

int i = 123;
double f = 123.45678;
char s[] = "Multimedia
University";

Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

37

Printing with escape sequence


Escape sequences are typically used to specify
actions such as carriage returns and tab
movements on terminals and printers
Character combinations consisting of a
backslash (\) followed by a letter or by a
combination of digits

38
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Table 3.5: Escape sequences and their purposes


Escape sequence

Action

\'

Output the single quote (') character.

\"

Output the double quote (") character.

\?

Output the question mark (?) character.

\\

Output the backslash (\) character.

\a

Cause an audible (bell) or visual alert.

\b

Move the cursor back one position on the current line.

\f

Move the cursor to the start of the next logical page.

\n

Move the cursor to the beginning of the next line.

\r

Move the cursor to the beginning of the current line.

\t

Move the cursor to the next horizontal tab position.

\v

Move the cursor to the next vertical tab position.

39
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Programming exercise
Write a C program to find area of rectangle whose sides are given
by the user.
Solution
The inputs to the problem are the sides of a rectangle, i.e. the length
and the breadth. We have to get the values of length and breadth
from the user using scanf statement. These inputs are of data type
float since sides of a rectangle is normally with fraction (floating
point format).
The expected output is the area of the rectangle which is also of
data type float. The area could be calculated by using the following
formula,
area = length * breadth.

40
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

By following top-down design technique, the three major parts of


the algorithm are given below,

Initialisation phase
No variable need to be initialised (as the values of length and
breadth will be given by the user at run time).

Processing phase
Read the values of length and breadth from the user and store
them into variables length and breadth respectively. Calculate
the area of the rectangle as length * breadth and store the result
into the variable area.

Termination phase
Display the calculated value of the variable area with
appropriate message.
41

Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

The Program
//header file required for the scanf and printf functions
#include <stdio.h>
int main( )
{
//declaration part
float length, breadth;
float area;
//reading the input and storing them into variables length
//and breadth
printf("Enter the two sides of a rectangle: ");
scanf ("%f %f", &length, &breadth);
//calculating the area as length x breadth
area = length * breadth;
//displaying the output with suitable message
printf("The area of the rectangle = %f square meters\n", area);
return 0;
}
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

42

Sample output
Enter the two sides of a rectangle: 2.3 3.2
The area of the rectangle = 7.360000 square meters

Note: The trailing zeros after the decimal point could be


eliminated by formatting the output using precision (%.2f
instead of %f) as follows,
printf("The area of the rectangle = %.2f square
meters\n",area);

The output of this printf statement will be,


The area of the rectangle = 7.36 square meters
43
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Common errors

Use of variables without having declared


earlier in the program will result in compiler
error undeclared identifier.
The address operator & is needed for scanf
function and it is not needed for printf function.
Improper use of control string will result in
incorrect output.

44
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

3.9 Summary
1. For each variable, you have to attach some data type.
The data type defines the amount of storage allocated
to variables and the values that they can accept.
2. There are two types of data, built-in and user-defined.
3. Every variable has to be declared before it is used.
4. Values to declared variables can be input from outside
the program using scanf function. The results of the
program can be output by using printf function.
5. The input to the program and the output from the
program can be formatted according to the user
requirements using features like conversion specifier,
flag, field width and precision.
45
Powerpoint slides to be used with C Programming for Beginners by HC Ling, SN Cheong, YK Teh,
LC Kwek, Emerson, Vishnu Monn B and Badrolhisham (Pearson Education, 2010)

Potrebbero piacerti anche