0% found this document useful (0 votes)
24 views33 pages

CH 2

Uploaded by

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

CH 2

Uploaded by

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

CHAPTER TWO

TOKENS
• The smallest element in the C language is the token.
• Tokens can be:
 Keywords
 Names (identifiers)
 constants
 Character constants
 String constants
 Special characters
 Operators

1
Keywords
• Sometimes called reserved words.
• Have special meaning to the compiler, cannot be used as
identifiers (variable, function name) in our program.
• Should be typed in lowercase.

2
Identifiers
• Words used to represent certain program entities (variables,
function names, etc).
Example: int my_name;
• my_name is an identifier used as a program variable

• Rules for naming identifiers


1. it can only be alphabets(both lower and upper case), digits and
underscores( _ ). eg. area, my_name
2. first character must be a letter or underscore
eg x2,_x,2x,(not allowed)
3. special characters except underscore are not allowed
4. maximum 31 characters in length
5. keyword are not allowed
6. it should not have impeded blanks
3
Q. Which of the following are invalid identifier
variable names and give reason
A. name
B. reg_no
c. 5y
d. small value
e. x&y
f. _name
g. float
h. Float

4
constants
• It is a value that never changes during program
execution
Types of constants
a)integer constants
b)Real /floating point constant
c)Character constant
d)String constant

5
Integer constant
I).Decimal integer constant formed using the digit (0-9)
and does not begin with 0.
Eg 123,459,26
II). Octal integer constant (base 8) it is formed from the octal
number system 0 to 7 with leading 0(zero)
Eg 017,01,055
III),hexadecimal integer constants (base 16) is formed from
the hexadecimal number system 0 to 9 and A to F with
leading ox
Eg 0xA,OX35,0xFFB
6
Exercise: Which of the following are invalid integer constants

A) 2A5
B) 2315
C) 0127
D) 0A00
E) 377
F) 0xKK
G) 0xab
7
Real (floating point)Constants
• They never contain a comma.
• Examples:
a) 98.6
b) -55.2
c) 1.3e-5 1.3 *10-5
d) 1.3E-5

8
Character Constants
• Singular!
• One character defined character set.
• Surrounded on the single quotation mark.
• Examples:
– ‘A’
– ‘a’
– ‘$’
– ‘4’
String Constants

• A sequence of characters enclosed in double quotes as “…”.


• Considered a single item.
• Examples:
– “UMBC”
– “I like ice cream.”
– “123”
– “CAR”
– “car” 9
Special characters
Semicolons, colons, commas, apostrophes, quotation marks, braces,
brackets, and parentheses.
; : , ‘ “ [ ] { } ( ) @ &%

Operators
• Tokens that result in some kind of computation or action when
applied to variables or other elements in an expression.
• Example of operators:
• +=-/
• < > = <= !=
• && | !

10
Data Types in C Language
• It is a term refers to the kind of data used in the program.
• Used to
• describe a user defined variables to the compiler.
• identify what type of data the compiler will process.
• Specify the size of data to process in the machine.
• A programming language is proposed to help programmer to
process certain kinds of data and to provide useful output.
• C has different data types for different types of data and can be
broadly classified as:
1. Primitive (or basic) data types
2. User defined data types
3. Derived data types

11
1. Primitive (or basic) data types
• There are 4 basic data types :
– char
– int
– float
– double
Data type declaration size example
character char 1 byte char ch=‘u’;
integer int 2 byte int age=38;
float (real) float 4 byte float height=1.82;
double double 8 byte double x=12e-5;

• char
– equivalent to ‘letters’ in English language
– single character
– keyword: char
char my_letter; 12
my_letter = 'U';
Contd…
• int
– used to declare numeric program variables of integer type
– whole numbers, positive and negative
– keyword: int
int number;
number = 12;
• float
– fractional parts, positive and negative
– keyword: float
float height;
height = 1.72;
• double
– used to declare floating point variable of higher precision or higher range
of numbers
– exponential numbers, positive and negative
– keyword: double
double valuebig;
valuebig = 12E-3;

13
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

14
2. 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)

3. Derived data types


• Programmers can derive data types such arrays, structures, union
and pointers by combining several data types together.

15
DECLARATIONS
Variables
• A variable has a value that can change .
• It is a memory location that can hold a value of a certain data type.
• Programmers refer to a variable by its name so that it can be
accessed during the course of the program.
• Programmers cannot use any of the keywords as variable names.
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.
• The syntax to declare a new variable is to first write the data type the
followed by valid variable identifier.
Syntax:
Data type identifiers; 16
Examples
int a;
float b;
char ch;
• Multiple variables belonging to the same data type can
be defined as a separate set of expression or by listing
variable names one after the other (should be separated
by a coma sign (,). like:
int x;
int y; int x,y;
float total;
float average; float total, average;

17
Initializing a variable
• Initializing a variable can be done while declaring it, just after
declaring it or later with in the code (before accessing /evaluating
its value within an expression)
• In initializing a variable any of the following three approaches are
valid.
1. int a;
a=10;
Or
2. int a=10;
Or
int a;
------
a=10;
18
• Which of the following declaration are illegal
int 44;
int Last;
int if;
integer abc;
char c1;
FLOAT y;
Float Float;

19
Constants
• The value of a constant can not be changed after
an initial value is assigned to it.
• The C language supports two types of constants
namely:
Declared constants and
Defined constants

20
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.
• Example
const float pi = 3.14;

Define constants
• Programmers can define their own names for constants which are
used quite often in a program with out having to refer to a variable
• such a constant can be defined simply by using the
#define preprocessor directive.
Example
#define pi 3.14
21
Input output (I/o)statments
1. output statements
I).putchar() used to write a single character to the screen
Syntax: putchar(variable name)
eg putchar(ch);
II) pintf() : this is used to display the value on the screen.
syntax: printf ( "<control string>", <list of variables> ) ;
Control string can be :
a. format string(conversion specifiers)
%f for printing real values, %d for printing integer values,
%c for printing character values, %s for printing string values
b. List of messages
c.Escape characters
Examples:
1) Printf(“deberezeit ”); o/p= deberezeit 3)Printf(“a”);
2)Printf(duc\n deberzeit); o/p= duc 4)Printf(“bcd”); o/p =abcd
deberzeit
22
comment
A comment is used to write some thing which are not part of the
program.
There are two Types of comment
1. single line comment (//)
2. multiline comment (/* */) 23
2. Input statements

I) getchar() it is used to read a single character from the keyboard


syntax: variable name=getchar();
eg. ch=getchar();
II) scanf () it is also an input funcion that supports mixed types of input data from
the keyboard.
Syntax: scanf(“Conversion Identifier ”,list of address separated by commas)
• Common Conversion Identifier used in printf and scanf functions.
printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s

• Example :
int age;
printf(“Enter your age:”);
scanf(“%d”, &age); 24
Storage Classes
• Every C variable has a storage class and a scope.
• The storage class determines the part of memory where storage is
allocated for an object and how long the storage allocation continues
to exist.
• It also determines the scope which specifies the part of the program over which a
variable name is visible, i.e. the variable is accessible by name.
• The scope of a variable is the part of a program where the variable
can be manipulated. The scope can be global or local.
• Global variables are typically declared before the main function.
They can be accessed from anywhere in the program.
• Local variables are valid and visible within a particular block (a
block is a set of C statements enclosed within brackets { .}). Once
the control flow is outside the block, the variable no longer exists
• There are four storage classes in C are automatic, register, external,
and static.
25
Automatic Variables
• They are declared at the start of a block.
• Memory is allocated automatically upon entry to a block and freed
automatically upon exit from the block.
• The scope of automatic variables is local to the block in which they are
declared, including any blocks nested within that block.
• For these reasons, they are also called local variables.
• No block outside the defining block may have direct access to automatic
variables
• Automatic variables may be specified upon declaration to be of storage class
auto.
• auto is the default storage class for local variables
• Example:
int Count;
auto int Month;
• The example above defines two variables with the same storage class.
• auto can only be used within functions, i.e. local variables.

26
Register Variables
• Register variables are a special case of automatic variables.
• Automatic variables are allocated storage in the memory of the computer; however,
for most computers, accessing data in memory is considerably slower than
processing in the CPU.
• These computers often have small amounts of storage within the CPU itself where
data can be stored and accessed quickly.
• These storage cells are called registers.
• Normally, the compiler determines what data is to be stored in the registers of the
CPU at what times. However, the C language provides the storage class register so
that the programmer can ``suggest'' to the compiler that particular automatic
variables should be allocated to CPU registers, if possible.
• register is used to define local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the register size
{
register int Miles;
}
• Register should only be used for variables that require quick access - such as
counters.
27
External Variables
• All variables we have seen so far have had limited scope (the block in
which they are declared) and limited lifetime (as for automatic variables).
• However, in some applications it may be useful to have data which is
accessible from within any block and/or which remains in existence for
the entire execution of the program.
• Such variables are called global variables, and the C language provides
storage classes which can meet these requirements; namely, the external
and static classes.
• External variables may be declared outside any function block in a source code file
the same way any other variable is declared; by specifying its type and name.
• The scope of external variables is global.
• extern defines a global variable that is visible to ALL object modules.
• Example:
extern int count;

28
Static - Storage Class
• static is the default storage class for global variables. The two
variables below (count and road) both have a static storage class
static int Count;
int Road;
main()
{
printf("%d\n", Count);
printf("%d\n", Road);
}
• static means that the object is not accessible by all parts of the
program.
• If the object is declared outside a function, it is accessible only by
the functions of the same file.
• It has a file scope
29
C program structure

#include<stdio.h>
void main()
{ beginning of the progrm
declaration of variables;
Excutable Statements and functions
} end of the progrm

Simple C Program
/* A first C Program*/
1. #include <stdio.h>
2. void main()
3. {
4. printf("Hello World \n");
5. } 30
Line 1: #include<stdio.h>
• As part of compilation, the C compiler runs a program called the
C preprocessor. The preprocessor is able to add and remove code
from your source file.
• In this case, the directive #include tells the preprocessor to
include code from the file stdio.h.
• This file contains declarations for functions that the program needs
to use. A declaration for the printf function is in this file.

Line 2: void main()


• Every program must have a function called main. This is where
program execution begins.
• A C program can contain many functions but must always have
one main function.
• The parenthesis following the reserved word “main” indicate that
it is a function.
31
Line 3: {
• This opening bracket denotes the start of the program.
• A left brace (curly bracket) -- { -- begins the body of every function.

Line 4: printf("Hello World \n");


• Printf is a function from a standard C library that is used to print
strings to the standard output, normally your screen.
• The compiler links code from these standard libraries to the code
you have written to produce the final executable.
• The "\n" is a special format modifier that tells the printf to put a
line feed at the end of the line.
• If there were another printf in this program, its string would print on
the next line.
Line 5: }
This closing bracket denotes the end of the program.

Then the o/p becomes: Hello World 32


// program to find sum of two nos /* program to find sum of two nos
#include <stdio.h> input from keyboard */

#include<conio.h> #include <stdio.h>

void main() #include<conio.h>

{ void main()

int x,y,sum; {

clrscr(); int x,y,sum;

x=10;//initalization clrscr();

y=5;//initialization printf(“\n enter x,y”);

sum=x+y; scanf(“%d%d”,&x,&y”);

printf(“sum=%d”,sum); sum=x+y;

getch(); printf(“sum=%d”,sum);

} getch();
}
33

You might also like