[go: up one dir, main page]

0% found this document useful (0 votes)
14 views75 pages

PC - Unit-1

The document provides an overview of computer programming, covering components of a computer system, algorithms, and the transition from algorithms to programs. It explains the distinction between hardware and software, detailing input/output devices, CPU, memory types, and the classification of software into system and application software. Additionally, it discusses computer languages, their types, and the process of creating and running programs, including writing, compiling, linking, and executing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views75 pages

PC - Unit-1

The document provides an overview of computer programming, covering components of a computer system, algorithms, and the transition from algorithms to programs. It explains the distinction between hardware and software, detailing input/output devices, CPU, memory types, and the classification of software into system and application software. Additionally, it discusses computer languages, their types, and the process of creating and running programs, including writing, compiling, linking, and executing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

UNIT-I: Introduction to Programming:

Introduction to components of a computer system (disks, memory, processor,


where a program is stored and executed, operating system, compilers etc.). Idea
of Algorithm: Steps to solve logical and numerical problems. Representation of
Algorithm: Flow chart / Pseudo code with examples. From algorithms to
programs; source code, variables (with data types) variables and memory
locations, syntax and logical errors in compilation, object and executable code.
Arithmetic expressions and precedence.

COMPUTER :

It is a high speed electronic device that accepts and stores input data and
instructions, processes the data and produces the desired output.

COMPUTER SYSTEMS
A computer is a system made up of 2 major components
They are :
(1) Hardware
(2) Software

) Computer Hardware :

 These are the physical components of a computer


 It consists of 5 Parts

1) Input Devices

2) Output Devices

3) CPU

4) Primary Storage

5)Auxilary Storage (or) Secondary Storage

Block diagram of a Computer

ALU CU

Input Output
Devices Devices

Primary Memory

Secondary Memory

1) Input Devices

These are used to enter data and programs into the computer.The
most wellknown input device is the keyboard. These are for man to machine
communication.
Examples of other input devices include mouse, scanner, touch screen, a pen or
stylus, audio input.

2) Output Devices

These are used to get the desired output from the computer. The
output unit of a computer provides the information and results of a computation
to outside world .Printers and monitors are the commonly used output devices.
Other commonly used output devices are floppy disk drive, hard disk drive, pen
drive and magnetic tape drive. These are for machine to man communication

 If the output is shown on monitor then it is called as “Soft copy”


 If the output is printed on a paper using printer then it is called as “hard
copy”

3) CPU (Central Processing Unit)

 It is responsible for executing instructions such as arithmetic


calculations,comparisions among data, and controls the movement of data
inside the system.
 It consists of 3 parts
1) ALU – Arithmetic & Logic Unit
2) CU- Control Unit
3) MU-MemoryUnit

Arithmetic & Logic Unit

All calculations are performed in the Arithmetic Logic Unit


(ALU) of the computer. It also does comparison and takes decision. The ALU can
perform basic operations such as addition, subtraction, multiplication, division,
etc and does logic operations such as >, <, =,>=,<=,!=, ‘etc. Whenever
calculations are required, the control unit transfers the data from storage unit to
ALU .Once the computations are done, the results are transferred to the storage
unit by the control unit and then it is send to the output unit for displaying
results.

Control Unit

It controls all other units in the computer. The control unit


instructs the input unit, where to store the data after receiving it from the user. It
controls the flow of data and instructions from the storage unit to ALU. It also
controls the flow of results from the ALU to the storage unit. The control unit is
generally referred as the central nervous system of the computer that control
and synchronizes its working.

Memory Unit

The memory unit of the computer holds data and instructions


that are entered through the input unit, before they are processed. It preserves
the intermediate and final results before these are sent to the output devices. It
also saves the data for the later use.

The various storage devices of a computer system are divided into two
categories.

1) Primary Memory / Main Memory

2) Secondary Memory / Auxiliary Memory

4) Primary Storage

It is also called main memory.This memory is generally


used to hold the program being currently executed in the computer, the data
being received from the input unit, the intermediate and final results of the
program.It is a place where the programs and data are stored temporarily during
processing.The data gets erased when computers is turned off

Eg: RAM

The cost of the primary storage is more compared to the secondary storage.
Therefore most computers have limited primary storage capacity .
5) Secondary Storage

It is also called as auxiliary memory.It stores several


programs, documents, data bases etc.It is a place where the programs and data
are stored permanently.Programs ans data remain in the secondary storage so
that user can reuse the data even after power loss.

Eg: Hard disk, CD, DVD, Floppy etc.

The secondary memory is slower and cheaper than the primary memory.

(2) COMPUTER SOFTWARE

Software is the collection of programs (or) instructions .Computer software is


divided into 2 broad categories

i. System Software
ii. Application Software

i) System Software

System software consists of programs that manage the hardware


resources of a computer and perform required information processing tasks.
These programs are divided into 3 classes

 The oprating system


 System support software and
 System development software
Operating System

It acts as an interface between the user and the hardware of a


system.It provides services such as user interface,file access,database access
and interface to communication systems such as Internet protocols.The
primary purpose of this software is to keep the system operating in an efficient
manner while allowing the users access to the system.

Egs: MS DOS, Windows, UNIX, LINUX, etc.

System support software

This software provides system utilities and other operating services

A computer system provides utility programs to perform the tasks needed by


most users.

System utilities may be already included in our computer systems or


downloaded from the internet.

Examples of system utilities are sort programs, disk format programs,disk


clean up,system restore and file splitters.

Other operating services consist of programs that provide performance


statistics and security monitors to protect the system and data.

System development software

System Development software includes

a) Language translators – Used for converting programs into machine language


for
execution. Ex.compiler,assembler.

b)Debugging tools to ensure that the programs are error-free, and

c)CASE tools – Computer Assisted Software Engineering Tools


ii) Application Software

An application is a program or group of programs designed for the


end users to solve their problems.Application software sits on the top of the
system software because it is unable to run with out the operating system and
system utilities.

It is divided into 2 classes

 General-purpose software and


 Application-specific software
General purpose software

These are purchased from software developers and they can be


used for more than one application.They are labled general purpose because
they can solve a variety of user computing problems.

Eg: word processors, DBMS etc…

Application Specific Software

Application specific software can be used only for intended


purpose.They can be used only for the task for which they were designed ;they
cannot be used for other generalized tasks.

Ex:Accounting system, hospital management system, banking system,etc

The following fig represents the relationship between system and application
software.
In this figure,

 Each circle represents an interface point.


 The inner core is the hard ware.
 The user is represented by the outer layer
To work with the system,the typical user uses some form of application
software.The application software in turn interacts with the operating
system,which is part of the system software layer.The system software provides
the direct interaction with the hardware.Note the opening at the bottom of the
figure.This is the path followed by the user who interacts directly with the
operating system when necessary.

 Differentiate between application software and system software?



Application software System software
(1)Application software is designed for (1) System software manages the
end resources of a Computer.
users that perform specific task for
the user.
(2) Application software can not (2) System software provides direct
interaction with thecomputer
interact directly
hardware and memory locations.
with the hardware .
(3)The application software directly (3)System software serves the
serves application,which in turn serves the
the user needs. user.
(4)Application software will not work (4)System software works with out the
with help of
out the help of system software. application software.

(5) A computer can work with out (5)A computer can not work with out
application system
software software

(6)Examples of application software (6) Examples of system software


Notepad,wordpad,ms word,web operating system,device
browser, drivers,assemblers,
DBMS,etc compilers,linkers,utility software,etc

COMPUTER LANGUAGES

 A language that is used to write programs for a computer is called as


computer language.
 Computer programming languages are used to give instructions to the
computer in a language which computer understands
 Computer languages are classified into 3 types
1) Machine languages
2) Symbolic languages
3) High level languages
1) Machine languages

 In the earliest days of computers,the only programming languages


available were machine languages.It is the lowest and most elementary
level of Programming language and was the first type of programming
language to be developed.
 Machine Language is basically the only language which computer can
understand
 Each computer has its own machine language,which is made of streams of
0’s and 1’s.The symbol 0 stands for the absence of electric pulse and 1 for
the presence of an electric pulse . Since a computer is Capable of
recognizing electric signals, therefore, it understand machine Language.

The following segment of code shows an example of a machine language

00000000 00000100
0000000000000000

01011110 00001100 11000010


0000000000000010

11101111 00010110
000000000000101

Advantages :

 It makes fast and efficient use of the computer.

 It requires no translator to translate the code i.e.Directly understood


by the computer
Disadvantages:

 It is difficult for the programmer to remember the sequence of all 0’s


and 1’s.

 It is difficult to locate and fix errors in a program written In the machine


language

 These languages are machine dependent i.e. a particular machine


language can be used on only one type of computer.

2) Symbolic Languages
 It is also called as assembly language.
 It was developed to overcome some of the many inconveniences of machine
language.
 This is another low level but a very important language in which operation codes and
operands are given in the form of alphanumeric symbols instead of 0’s and l’s.
Because of this feature it is also known as ‘Symbolic Programming Language’.

 These alphanumeric symbols will be known as mnemonic codes and can have
maximum up to 5 letter combination
 e.g. ADD for addition, SUB for subtraction, START,LABEL etc.

 Since a computer does not understand symbolic language,it must be translated to the
machine language.A special program called assembler translates symbolic code into
machine language.

Assembly language program Assembler Machine Language code

Advantages :

 It is easier to understand and use as compared to machine language.


 It is easy to locate and correct errors.
 It is modified easily
Disadvantages:
 Like machine language it is also machine dependent.
 Since it is machine dependent therefore programmer Should have the knowledge of
the hardware also.
 This language is also very difficult and needs a lot of practice to master it because
very small English support is given to this language.

3) High level languages

 A set of languages which are very close to our native languages are called
“ high-level languages”.
 High-level languages are basically symbolic languages that use English words and/or
mathematical symbols rather than mnemonic codes
 Since a computer does not understand high-level languages,it must be
translated to the machine language.A special program called compiler
translates high-level languages into machine language
 Examples of high level languages are FORTRAN, COBOL, PASCAL, C, C+
+,JAVA, etc..

Compiler /
High language program Machine
Interpreter
Language code

Advantages :

 These are Similar to English with vocabulary of words and symbols.Therefore it is easier
to learn.

 They require less time to write.

 They are easier to maintain.

 They are user-friendly.

 Problem oriented rather than 'machine' based.

 It is independent of the machine on which it is used i.e.Programs developed in high level


language can be run on any Computer

Disadvantages :

 High level language programs needs a translator for conversion into


machine language
 ‘Compilers’ (or) ‘Interpreters’ are used for converting high level language
program into machine language..

CREATING AND RUNNING PROGRAMS

A program is a sequence of instructions written to perform a specified task with


a computer.It is the job of the programmer to write and test the program.

There are 4 steps in this process.

1) Writing and editing the program


2) Compiling the program
3) Linking the program with required library modules, and
4) Executing the program
1) Writing and editing the program

 The software used to write programs is known as text editor .Users can
enter, change and store character data using text editors.
 A special text editor is often included with a compiler.
 Some of the features we look in our editor are search commands to locate
and replace statements,copy and paste commands to copy or move
statements from one part of a program to another, and formatting
commads that allows us to set tabs to align statements.
 After completing writing program, save the file to disk. This file will be
input to the compiler: It is known as ‘source file’ .

2) Compiling the program

“Compiler” is a software that translates the source file into machine


language

The ‘C’ compiler is actually 2 separate programs.

a) Preprocessor

b) Translator

a) Preprocessor
The preprocessor reads the source code and prepares it for the translator.
While preparing the code it scans for special instructions known as ‘preprocessor’
commands. These commands tell the preprocessor to look for special code
libraries and make substitutions in the code, and in other ways prepare the code
for translation into machine language. The result of preprocessing is called
‘translation’ unit

Preprocessor
Source File translation unit

b) Translator

After the preprocessor prepared the code for compilation, the translator
does the actual work of converting the program into machine language. The
translator reads the translation unit and writes the resulting ‘object module’ to
a file that can be combined with other precompiled units to form the final
program. An object module is the code in machine language.

Even though the output of the compiler is machine language code, it is


not yet ready to run; that is, it is not yet executable because it does not have the
required C and other functions included.

Translator
Translation unit Object Module .obj file
00110 100
10101 010

3) Linking programs

 A C program is made up of many functions. We write some of these


functions and they are part of the source program.
 However, there are other functions, such as input/output processes and
mathematical library functions, that exist elsewhere and must be attached
to our program.
 The ‘Linker’ assembles all of these input /output functions, mathematical
library functions and some of the functions that are part of source program
into final executable program.
 It is called as executable file that it is ready for execution

.exe file
Linker
Object file executable file 1011001100
110111011
1100101010

4) Executing Programs

 Once the program has been linked it is ready for execution.


 To execute a program, we use an operating system command, such as run,
to load the program into primary memory and execute it.
 Getting the program into primary memory is the function of an operating
system program known as the loader. Loader locates the executable
program and reads into primary memory.
 When everything is loaded, the program takes control, and it begins
execution.

In a typical program execution, the program reads data for processing,


either from the user or from a file. After the program process the data, it
prepares the output. Data output can be to the user’s monitor or to a file. When
the program has finished its job, it tells the operating system, which then
removes the program from primary memory.
ALGORITHM:

 It is a step – by – step procedure for solving a problem


 If algorithm is written in English like sentences, then it is called as
‘PSEUDO CODE’
Properties of an Algorithm

An algorithm must posses the following 5 properties. They are

1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
1. Input : An algorithm must have zero (or) more number of inputs
2. Output: Algorithm must produce one (or) more number of outputs
3. Finiteness : An algorithm must terminate in countable number of steps
4. Definiteness: Each step of the algorithm must be stated clearly
5. Effectiveness: Each step of the algorithm must be easily convertible into
program statements
Example

Algorithm that prints sum of 2 numbers

1. start
2. Read 2 numbers a,b
3. Compute sum = a+b
4. Print sum value
5. Stop
Algorithm for finding the average of 3 numbers

1. start
2. Read 3 numbers a,b,c
3. Compute sum = a+b+c
4. compute avg = sum/3
5. Print avg value
6. Stop

Algorithm to compute the quotient and remainder

1. start

2. Read 2 numbers a,b


3. quotient = a/b
4. remainder = a%b
5. Print quotient
6. Print remainder
7. Stop

Algorithm to convert Celsius to Fahrenheit ( formula, F = 1.8 C + 32)

1. start
2. Read Celsius
3. f = 1.8*c+32;
4. Print f value
5. Stop

Algorithm to calculate the circle diameter, circumference, and area.


Help Raju to complete his task. Get radius as input.
1. Start
2. input radius
3. diameter=2*radius
4. area = (22/7)*radius*radius
5. circumference =2*(22/7)*radius
6. Print diameter, area, circumference
7. Stop

Algorithm to check whether the number is even or odd?

1. Start
2. read number
3. if number%2 is 0 then
Print number is even
4. Else
Print umber is odd
5. Stop

Algorithm to check whether the person is eligible to vote or not?

1. Start
2. read age
3. if age>=18 then
Print “eligible to vote”
4. Else
Print “not eligible to vote”
5. Stop

Algorithm to print numbers from 1 to 10

1. Start
2. I = 1;
3. Repeat
print i
i=i+1
Until I <=10
4. Stop

Algorithm to print sum of first 10 numbers

1. Start
2. I = 1;
3. Sum=0
4. Repeat

Sum = sum + i

i=i+1
Until I <=10
5. Print sum
6. Stop

FLOW CHART

A flowchart gives a pictorial representation of an algorithm.

A flowchart is a combination of the following symbols

1)Auxilary symbols
The auxiliary symbols shows the start and stop points, the order and sequence
of actions, and how one part of a flowchart is connected to another. These
auxiliary symbols are shown in fig:

Symbol Name
Application

Terminal Shows the beginning or ending of an


algorithm

Flow Lines Shows the action order in an


algorithm

Connector Shows connecting points in


an algorithm

Fig:Auxilary symbols

Terminal

An oval symbol shows the beginning or ending of an algorithm. When it is used


to show the beginning of an algorithm, we write the word START inside the
oval.When it is used to show the ending of an algorithm, we write the word STOP
or RETURN in the oval. A good structured flowchart should have one and only
one START and one and only one STOP .

Flow Lines

Flow lines show the order or sequence of actions in a program.They connect


symbols. Usually a symbol has some entering and some exiting lines. The START
oval has only one exiting line. The STOP oval has only one entering line.
Connectors

We use only one connector symbol, a circle with a number in it, to show
connectivity. It is used in the following situation

 When we reach the end of a column or page, but our chart is not finished.
In this case, at the bottom of the flow we use a connector to show
that the flow continues at the top of the next column or page. This condition is
shown in following fig:

2)
Primary symbols

Programmers use the primary symbols to show the instructions or actions


needed to solve the problem presented in the algorithm. With these symbols, it is
possible to represent all three structured programming constructs:sequence,
decision, and repetition.

Sequence

Flowcharts use four sequence symbols

a)Assignemnt

b)Input/Output

c)Module call

d)compound statement
a)Assignemnt Statement

The assignment statement is shown using a rectangle. Within the


assignment symbol, the assignment operator is shown as left-pointing arrow. At
the right side of the arrow is an expression whose value must be stored in the
variable at the left side.

Variable expression

Fig: The assignement statement

b)Input/Output statement

A parallelogram shows any inout or output, such as reading from a keyboard


or writing on the system console.

Fig: Input/Output symbol

c)Module-Call statement

The symbol used for a module call is a rectangle with two vertical bars inside.
The flowchart for called module must be somewhere else.

Fig: Module call symbol

In C programs, the module-call symbol is used primarily for void functions.


Functions that return values are shown as assignments or other expressions in a
sequence symbol.
d) Compound statement

In a C program, compound statements represents a block of code, code that


is enclosed in braces.In a flowchart, we use a dashed rectangle to enclose a
compound statement.

Decision or selection statements

Unlike the sequence statements, conditional statements can cause the flow of
the program to change. They allow the execution of selected statements and the
skipping of other statements.

Structured programming has two selection statements:

Two-way and multiway selection.

Two-way selection

The two-way symbol is the diamond. When it is used to represent an if…else


statement, the true condition logic is shown as the right leg of the logic flow, and
the false condition, if present, is shown on the left leg of the logic flow. Finally
the statement ends with a connector where the true and false flows join. In this
case the connector has nothing in it.

A decision always has two branches. The statement in each branch can be null
or a compound statement.
Multiway selection
Advantages of flow chart

 It is very easy to understand because the reader follows the process


quickly from the flowchart instead of going through the text.
 It is the best way of representing the sequence of steps in an algorithm
 It gives a clear idea about the problem
 Various symbols are used for representing different operations
 Arrows are used for connecting the symbols and show the flow of
execution
Symbols used in flowchart:

Name Symbol Purpose

Terminal Start /stop/begin/end

oval

Input / output Input/output of data


Parallelogram

Process Any processing to be


performed can be
represented

Rectangle

Desicion box Decision operations that


determine which of the
alternative paths to be
followed

Diamond

Connector Used to connect


different parts of
flowchart
Circle

Flow Joins 2 symbols and


also represents flow of
execution
Arrows

Pre defined process Modules (or)subroutines


specified else where

Douuble sided rectangle

Page connector Used to connect


flowchart in 2 different
pages

Pentagon

For loop symbol Shows initialization,


condition and
incrementation of loop
Hexagon variable.

Document Shows the data that is


ready for printout

Printout
Example

Flowchart for finding the average of 5 numbers

Start

Read 3 Numbers
a,b,c

Compute sum
a+b+c

Compute avg
sum/3

Print avg value

Stop

INTRODUCTION TO ‘C’ LANGUAGE

‘C’ is a high –level programming language developed in 1972 by Dennis Ritchie at AT & T Bell
Laboratories

It was primarily developed for systems programming i.e. for designing operating systems ,
compilers etc

Importance of ’C’ Language

1. It is a robust language, whose rich set of built-in functions and operations can be used to
write any complex program

2. It is a middle level language because the ‘C’ compiler combines the capabilities of an
assembly language with the features of a high-level language and therefore it is well suited for
writing both system software and business packages.
3. ‘C’ Programs are efficient and fast

4. C is highly portable, that is c programs written for one computer can be run on another with
little (or) no modification.

5. ‘C’ Language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules (or) blocks.

6. ‘C’ program has the ability to extend itself.

It was named ‘C’ because it is an offspring of BCPL (Basic Combined Programming Languages)
which was popularly called ‘B’ language.

Explain the structure of a C program?

Preprocessor Directives

Global Declarations

void main( )

Local declarations

Statements

} // end of main

Other functions required

Fig: Structure of C program

Every C program is made of one or more preprocessor commands, a global declaration section ,
and one or more functions.

Preprocessor directives are special instructions to the preprocessor that tell it how to prepare
the program for compilation. One of the most important of the preprocessor commands used in
every program is include. The include command tells the preprocessor that we need
information from selected libraries known as header files.
Global declaration section comes at the beginning of the program. This declaration is visible to
the entire program.

The work of the program is carried out by its functions. A C program can contain many number
of functions but one and only one function must be named main. The main() is a special
function used by the C system to tell the computer where the program starts.Every program
must have exactly one main function. If we use more than one main function, the compiler
cannot understand which one marks the beginning of the program. Always the execution starts
from the main function.

All functions in a program, including main, are divided into two sections:

1) The declaration section and

2) The statement section

The declration section is at the beginning of the function. Declarations inside a function are
known as local declarations because they are visible only to the function that contains them.

The statement section follows the declaration section. It contains the instructions to the
computer, such as add two numbers. In C, these instructions are written in the form of
statements.

---------------------------------------------- 0 ------------------------------------------------

Example

#include <stdio.h>

int main(void)

printf(“Hello World”);

return 0;

} //end of main function

Preprocessor commands

The preprocessor commands come at the beginning of a program. All preprocessor commands
start with a pound sign(#); Preprocessor commands can start in any column, but they
traditionally start in column1.
The preprocessor command #include <stdio.h> tells the compiler to include the standard
input/ouput library file in the program. We need this library file to print a message to the
terminal. Printing is one of the input/output processes identified in this library.

main

The executable part of the program begins with the function main, which is identified by the
function header shown below :

int main (void)

int says that the function will return an integer value to the operating system; main is the name
of the function and it has no parameters(here the parameter list is void).

The function main starts with an open brace ({) and terminates with a close brace (}). All the
statements between these two braces form the function body. The function body contains a set of
instructions to perform the given task.

In the above example with in the main there are two statements: one to print the message “Hello
World” and one to terminate the program.

The print statement uses a library function(printf) to do the actual writing to the monitor. To
invoke or execute this print function(printf) we must call it. All function call statements consist
of the name of the function (in this case printf) , followed by a parameter list (in thi case “Hello
World”)enclosed in parentheses. The \n at the end of the message tells the computer to go to the
next line in the output.

The last statement in the program, return 0, terminates the program and returns control to the
operarting system.

Comments :

Comments are used in the program to enhance its readability and understanding. They are
mainly used for documentation. A comment can be inserted any where in the program.
Comments are not executable statements and therefore anything between the comments is
ignored by the compiler. Since comments do not affect the execution speed and the size of a
compiled program, we should use them liberally in our programs.

C language allows two types of comments

1) Single Line comment


2) Block comment
1)Single Line comment :

The second format, the single line comment, uses two slashes (//) to identify a comment. This
format does not require an end- of-comment token; the end of line automatically ends the
comment. Programmers generally use this format for short comments.

Ex

// This is a whole line comment

1) Block comment :

It is a multi line comment used to comment several lines. It is also called as format block
comment

because it uses opening and closing comment tokens. A token is one or more symbols
understood by the compiler. The opening token is /* and the closing token is */ .Everything
between the opening and closing comment tokens is ignored by the compiler. The tokens can
start in any column, and they do not have to be on the same line. The only requirement is that
the opening token must precede the closing token.

Ex:

/* This is a block comment that

Covers two lines */

Although comments can appear anywhere in the program, they cannot be nested i.e we cannot
have comments inside comments. Once the compiler finds an opening token, it ignores
everything until it finds a closing token. Therefore, the opening token of the nested comment is
not recognized.

The error is shown in fig

/* This is a block comment that

Covers/* two lines */ here */

----------O-----------
Character set

The characters that can be used to form words, numbers and expressions depends upon the
computer on which the program is run. The characters in C are grouped into the following
categories:

1)Letters

Ex: Uppercase A----Z

Lowercase a----z

2)Digits

All decimal digits 0----9

3)Special characters

Ex: , . : ; ? ‘ “ \ ! < > { } [ ] #

4)White spaces

Ex: Blank space, Horizontal tab, Carriage return, New line

The compiler ignores white spaces unless they are a part of string constant. White spaces may
be used to separate words, but are prohibited between the characters of keywords and
identifiers.

C Tokens

In a C program the smallest individual units are known as C tokens. C has six types of tokens
shown in following fig. C programs are written using these tokens and syntax of the language.
Keywords

Every C word is classified as either a keyword or an identifier.

All keywords have fixed meanings and these meanings cannot be changed.

Keywords serve as basic building blocks for program statements.

All keywords must be written in lower case.

Keywords, also known as reserved words, include syntactical words, such as if and while.

auto double int struct break

else long switch case enum

register typedefchar extern return

union const float short unsigned

continue for signed void default

goto sizeof volatile do if

static while

ANSI C Keywords

-----------------------------------------------------0----------------------------------------------------------

What is an identifier? What are the naming rules for identifiers in C?

Identifiers

Identifiers refer to the names of variables, functions and arrays. These are user defined names
and each identified object in the computer is stored at a unique address.

Naming rules for identifiers(variables, functions, arrays) :

1) First character must be alphabetic character or underscore.

2)Must consist of only letters, digits or underscore.

3)First 63 charactes of an identifier are significant. But first eight characters are treated as
significant by many compilers

4)Cannot use a keyword for naming identifiers.


5)Must not contain white space.

Example:

Valid names Invalid names

a $sum

student_name 2names

_anyname sum-salary

int_min int

_float stdnt nbr

C is case sensitive. This means that even though two identifiers are spelled the same, if the case
of each corresponding letter does not match, C thinks of them as different names. Under this
rule num, Num, NUM are three different identifiers.

--------0-----------

Variable

It is the name given to a memory location that may be used to store a data value.

A variable may take different values at different times during execution of a program.

A variable name may be chosen by the programmer in a meaningful way so as to reflect its
function (or) nature in the program . Eg: sum, avg , total etc.

Each variable in a program must be declared and defined. Declaration gives a symbolic name
and definition reserves memory for the variable.

Variable declaration:

After designing suitable variabe names, we must declare them to the compiler. Declaration does
two things:

1)It tells the compiler what the variable name is

2)It specifies what type of data the variable will hold.

Syntax for declaring a variable is as follows

data-type v1,v2,----------vn;
A variable’s data-type can be any one of the data types, such as character, integer or real. A
variable cannot be type void. v1,v2,--------vn are the names of variables. Variables are seperated
by commas. A declaration statement must end with a semicolon.

Example int number,total;

Variable definition (or) Variable initialization:

The process of giving initial values to variables is called initialization.

After declaring a variable define the variable by using assignment (=) operator as follows

Syntax: variable-name = constant;

An assignment statement implies that the value of the varialbe on the left of the ’equal ssign’ is
set equal to the value of the quantity on the right

Example: number = 10;

We can initialize a variable at the same time that we declare it. This takes the following form

Syntax: data-type variable_name = constant;

Example: int number = 10;

Many compilers display a warning message when a variable is accessed before it is initialized.

-----------------------------------0----------------------------------------------------------

Constants

Constants in C refer to fixed values that do not change during the execution of a program. Like
variables constants have a type. C supports several types of constants as illustrated in fig:
Integer constants

An integer constant refers to a sequence of digits. It should not contain a decimal point. There
are three types of integers namely

1) decimal integer,
2) octal integer and
3) hexadecimal integer.

Decimal integers consist of a set of digits, 0 through 9, preceeded by an optional – or + sign

Valid examples of integer constatnts are : 123, -321, 0, +78

An octal integer constant consists of any combination of digits from the set 0 through 7, with a
leading 0.

Some examples of octal integer are: 037,0,0435,0551

A sequence of digits preceded by 0x or oX is considered as hexadecimal integer. They may also


include alphabets A through F or a through f. The letter A through F represent the numbers 10
through 15.

Following are the examples of valid hexadecimal integers:

0X2,0X9F,0Xbcd,0x

Embedded spaces, commas and nondigital characters are not permitted between digits.
Examples of some invalid integer constatnts are 20,000 $100

Real constants

Integer numbers are inadequate to represent quantities, such as distances, heights,


temperatures, prices and so on. These quantites are represented by numbers containing
fractional parts like 17.548. Such numbers are called real constants.

Some examples of real constants are:

0.0083 -0.75 435.56 +247.0

These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part. It is possible to omit digits before the decimal point, or digits after
the decimal point, For example , the following are all valid real numbers

215. .95 -.71 +.5


A real number may also be expressed in exponential(or scientific)notation. For example, the
value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102. The
general form is

mantissa e exponent

The mantissa is either a real number expressed in decimal notation or an integer. The exponent
is an integer number with an optional plus or minus sign. The letter e separating the mantissa
and the exponent can be written in either lowercase or uppercase.

Exponential notation is useful for representing numbers that are either very large or very small
in magnitude. For example, 75000000 may be written as 7.5E7 or 75E6.

Similarly -0.000000368 is equivalent to -3.68E-7.

Floating-point constants are mormally represented as double-precision quantities. However the


suffix f or F may be used to force single-precision and l or L to extend double precision further.

Single character constants

A single character constant contains a single character enclosed within a pair of single quote
marks. Examples of character constants are: ‘5’ ‘X’ ‘‘

The last constant is a blank space. Character constants have integer values known as ASCII
values. For example the following statement would print the number 97, the ASCII value of the
letter a.

printf(“%d”, ‘a’);

Similarly the following statement would output the letter ‘a’

Printf(“%c”, 97);

ASCII values of alphabets are

a to z : 97-122

A to Z : 65 -90

String constants

A string constant is a sequence of characters enclosed in double quotes. The characters may be
letters, numbers, special characters and blank space. Some of the examples of string constants
are :

“Hello!” “1987” “WELL DONE” “5+3” “X”


It is important to note that a single character constant ‘X’ is not equivalent to the single
character string constant “X”. Further a string character constant does not have an equivalent
integer value, while a single character constant has an integer value.

------------------------------------------------------0------------------------------------------------------

Data Types

Data type specifies the set of values and the type of data that can be stored in a variable.

ANSI C supports 3 classes of data types.

Primary(or fundamental or basic or built-in) data types

Derived data types

User-defined data types

1. Primary (or fundamental or basic or built-in) data types

All ‘C’ compilers support 5 fundamental data types

They are

Integer (int)

Character (char)

Floating – point (float)

Double precision floating point (double)

void
1.Integral data type

Integral data types are used to store whole numbers and characters

It is further classified into

a) integer data type


b) character data type

a) Integer data type

Integers are whole numbers with a range of values supported by a particular machine

In order to provide some control over the range of numbers and storage space , C has 3 classes
of integer storage namely, short int, int and long int in both signed and unsigned forms.

Signed integers (+ve or _ve) use first bit for storing the sign of the number and remaining bits
for the magnitude of the number.

Unlike signed integers, unsigned integers use all the bits for the magnitude of the number and
are always positive.

We declare long and unsigned integers to increase the range of values.

The use of qualifier signed on integers is optional because the default declaration assumes a
signed number.

Integer Data type

Type size (in bytes) Range Control string

Short int (or) 1 -128 to 127 % hd


signed short int

Unsigned short int 1 0 to 255 % hu

int (or) signed int 2 -32768 to 32767 %d

unsigned int 2 0 to 65535 %u

Long int (or) 4 -2147483648 to %ld


signed long int 2147483647

Unsigned long int 4 0 to 4294967295 %lu


b) character data type

A single character can be defined as a character(char) type data.

Characters are usually stored in 8 bits of internal storage.

The qualifier signed or unsigned may be explicitly applied to char. The use of qualifier signed
is optional because the default declaration assumes a signed character.

These characters are internally stored as integers.

Each character has an equivalent ASCII value

eg: ‘A’ to ‘Z’ has ASCII values from 65 to 90

‘a’ to ‘z’ has ASCII values from 97 to 122

Character data type

Type Size (in bytes) Range Control string

Char (or) signed 1 - 128 to +127 %c


char

Unsigned char 1 0 to 255 %c

2. Floating – point Data types

Floating-point numbers are defined in C by the keywod float. float data type gives 6 digits of
precision after decimal point.

A double data type number uses 64 bits(or 8 bytes) giving a

For 12 digits of accuracy, ‘double' is used.

For more than 12 digits of accuracy, ‘long double’ is used..

Floating point data type


Type Size (in bytes) Range Control string

Float 4 3.4 E – 38 to 3.4 E + 38 %f

Double 8 1.7 E – 308 to 1.7 E +308 %lf

long double 10 3.4 E – 4932 to 1.1 E +4932 %Lf

---------------------------------------0------------------------------------------------------

Input / output

There are number of input/output functions in C based on the data types. The I/O functions are
classified inot two types

1)Formatted I/O functions

2)Unformatted I/O functions

Formatted I/O functions

The formatted I/O functions read and write all types of data values. They require conversion
symbol to identify the data type. Hence they can be used for both reading and writing of all data
values. The formatted functions return the values after execution. The return value is equal to
the number of variables successfully read/written.

Unformatted I/O functions

The unformatted I/O functions only work with the character data type. They do not require
conversion symbol for identification of data types because they work only with the character
data type. There is no need to convert the data. In case, values of other data types are passed to
these functions, they are treated as the character data. The unformatted functions also return
values, but the return values of unformatted function is always the same.

In C, data is input to and output from a stream. A stream is a source of or destination for data. It
is associated with a physical device, such as terminal, or with a file stored in auxiliary memory.

C used two forms of streams : text and binary.


A text stream consists of a sequence of characters divided into lines with each line terminated by
a new line(\n).

A binary stream consists of a sequence of data vlues such as integer, real, or complex using their
memory representation.

A terminal(keyboard, monitor) can be associated only with a text stream because a keyboard
can only send a stream of characters into a program and a monitor can only display a sequence
of characters. A file on the other hand can be associated with a text or binary stream.

Formatting Input / Output funcitons

The C language privides two formatting functions

(1) printf for output formatting and

(2) scanf for input formatting

The printf function converts data stored in the program into a text stram for output to the
monitor;

The scanf function converts the text stream coming from the keyboard to data values and stores
them in program variables.

In other words, the printf and scanf functions are data to text stream and text stream to data
converters. Text streams often represent different data types such as ineger, real and Boolean.

Output formatting function: printf

The ouput formatting function is printf . The printf function takes a set of data values, converts
them to a text stream using formatting instructions contained in a format control string, and
sends the resulting text stream to the standard output. For example, an integer 234 stored in the
program is converted to a text stream of three numeric ASCII characters( ‘2’ , ‘3’ and ‘4’ ) and
then is sent to the monitor. What we see on the monitor is these three characters, not the integer
234.
The general format of printf statement is :

printf(“control string” , arg1, arg2,------argn);

Control string consists of three types of items:

1)Characters that will be printed on the screen as they appear.

2)Format specifications that define the ouput format for display of each item.

3)Escape sequence characters such as \n, \t, and \b.

The control string indicates how many arguments follow and what their types are. The
arguments arg1,arg2,--------argn are the variables whose values are formatted and printed
according to the specifications of the control string. The arguments should match in number,
order and type with the format specifications.

A format specification(conversion specification) has the following form:

% flag minimumwidth precision size conversioncode

The conversion specification contains a start token(%), a conversion code, and upto four
optional modifiers.

Only the field-specification token(%) and the conversion code are required(mandatory).

Conversion codes are used to describe data types. Converison code to describe integer data
type is (d), floating point is (f) and character data type is (c) .

The size modifier is used to modify the type specified by the conversion code. There are four
different sizes: h,l(el), ll (el el) and L.

The h is used with the integer codes to indicate a short integer value.

The l(el) is used to indicate a long integer value.

The ll(el el) is used to indicate a long long integer value; and

The L is used with floating-point numbers to indicate a long double value.

Precision modifier specifies the number of decimal places to be printed (if a floating-point
number is being printed). The precision modifier has the fomat

.m
where m is the number of decimal digits. If no precision is specified, printf prints six decimal
positions.

Minimum width modifier is used to specify the minimum number of positions in the output. If
the data requires more space than specified width , then printf overrides the width. It is very
useful to align output in columns.

When both width and precision are used, the width must be large enough to contain
the integral value of the number, the decimal point, and the number of digits in the decimal
position.

The Flag modifier is used for four print modifications: justification, padding, sign and numeric
conversion variants.

Justification controls the placement of a value when it is shorter than the specified width.
Justification can be left or right. The default is right justification. To left justify a value, the flag is
set to minus(-).

Padding defines the character that fills the unused space when the value is smaller than the
print width. Character can be a space, any symbol or zero. If there is no flag defined for padding,
the unused width is filled with spaces.

Sign flag defines the use or absence of a sign in numeric value. We can specify one of three
formats: default formatting, print signed values, or prefix positive values with a leading space.

Default formatting inserts a sign only when the value is negative.

When the flag is set to plus(+), signs are printed for both positive and negative values.

If the flag is space, then positive numbers are printed with a leading space and negative
numbers with a minus sign.

printf never supplies a newline automatically and therefore multiple printf statements may be
used to build one line of output. A new line can be introduced with the help of a new line
character ‘\n’

Output formatting examples

1)printf(“%d%c%f”, 23, ’z’, 4.1);

23 z 4.100000

2)printf((“%d %c % .2f”, 23, ’z’, 4.1);

23 z 4.10
Input formatting function: scanf

The standard input formatting function in C is scanf. This function takes a text stream from the
keyboard, extracts and formats data from the stream according to a format control string, and
then stores the data in specified program variables.

Syntax

Scanf(“format control string”--------,input parameter list)

Like the control string for printf, the control string for scanf is enclosed in a set of quotation
marks and contains one or more conversin specifications that describe the data types and
indicate any special formatting rules and/or characters.

Conversion specification

Conversion specification contains a start token(%), a conversion code, and upto three optional
modifiers. Only the field specification token and(%) and the conversion code are required.

% flag Maximumwidth size conversioncode

There is only one flag for input formatting, the assignment suppression flag(*). The assignment
suppression flag(*) tells scanf that the next input field is to be read but not stored. It is
discarded.

The following scanf statement reads an integer, a character, and a floating-point number from
the input stream. The character is discarded. The other fields are read, formatted, and stored.

scanf(“ %d %*c %f”, &x , &y);

Note that there is no matching address parameter for the data to be discarded.

The Maximum width modifier specifies the maximum number of characters that are to be read
for one format code. When a width specification is included, therefore, scanf reads until the
maximum number of characters have been processed or until scanf finds a whitespace character.
If scanf finds a whitespace character before the maximum is reached, it stops.

The size modifier is used to modify the type specified by the conversion code. There are four
different sizes: h,l(el), ll (el el) and L.

The h is used with the integer codes to indicate a short integer value.

The l(el) is used to indicate a long integer value.

The ll(el el) is used to indicate a long long integer value; and
The L is used with floating-point numbers to indicate a long double value.

Conversion codes are used to describe data types. Converison code to describe integer data
type is (d), floating point is (f) and character data type is (c) .

Input parameres

For every conversion specification there must be a matching variable in the address list. The
address list contains the address of the matching variable. Addresses are indicated by prefixing
the variable name with an ampersand (&). In C the ampersand is known as the address operator.
Using the address operator, if the variable name is price, then the address is &price.

The first conversion specification matches the first variable address, the second
conversin specification matches the second variable address, and so on. It is also very important
that the variable’s type match the conversion specification type.

---------------------------------------------0---------------------------------------------------------

OPERATORS AND EXPRESSIONS

C supports a rich set of built-in operators. An operator is a symbol that tells the computer to
perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables.

C operators can be classified inot number of categories. They include

Arithmetic operators.

Relational operators.

logical operators.

Assignment operators.

Increment and decrement operators.

Bitwise operators.

Conditional operators.

Special operators.
1). Arithmetic operators

C provides all the basic arithmetic operators. These can operate on any built-in data type
allowed in C.These operators are used for numerical calculations (or) to perform arithmetic
operations like addition, subtraction etc.

Note that C does not have an operator for exponentiation.

Integer Arithmetic

Operator Description Example a =20, b=10 output

+ Addition a+b 20+10 30

- Subtraction a-b 20-10 10

* multiplication a*b 20*10 200

/ Division a/b 20/10 2 (quotient)

% Modular division a%b 20%10 0 (remainder)

Here a and b are variables and are known as operands.

When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer arithmetic. Integer
arithmetic always yields an integer value.

During integer division, if both the operands are of the same sign, the result is truncated
towards zero. If one of them is negative, the direction of truncation is implementataion
dependent. Integer division truncates any fractional part.

That is, 6/7=0 but -6/7 may be zero or -1(Machine dependent)

The modulo division operator produces the remainder of an integer division. The modulo
division operator(%) cannot be used on floating point data.During modulo division, the sign of
the result is always the sign of the first operand(the dividend).

That is -14 % 3 = -2

-14 % -3 = -2

14 % 3 = 2
Program:

main ( )

int a= 20, b = 10; Output

printf (“ %d”, a+b); 30

printf (“ %d”, a-b); 10

printf (“ %d”, a*b); 200

printf (“ %d”, a/b); 2

printf (“ %d”, a%b);

Real Arithmetic

An arithmetic operation involving only real operands is called real arithmetic. A real operand
may assume values either in decimal or exponential notation. Sice floating point values are
rounded to the number of significant digits permissible, the final value is an approximation of
the correct result.

If x, y, and z are floats, then we will have,

x = 6.0 /7.0 = 0.857143

y = 1.0 / 3.0 = 0.333333

z = -2.0 / 3.0 = -0.666667

The % operator cannot be used with real operands.

Mixed-mode arithmetic

When one of the operands is real and the other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is of the real type, then only the real operation is
performed and the result is always a real number. Thus

15/10.0 = 1.5

Where as 15/10 = 1
2)Relational operators :

Comparisions can be done with the help of relational operators. An expression such as

a < b or 1 < 20

containing a relational operator is termed as a relational expression. The value of a relational


expression is either one or zero. It is one if the specified relation is true and zero if the relation is
false.

For example 10 < 20 is true but

20 < 10 is false

C supports six relational operators. These operators and their meanings are shown in table

Operator Description Examble a =10, b=20 output

< less than a<b 10 < 20 1

<= less than (or) a<=b 10 <= 20 1


equal to

> greater than a>b 10 > 20 0

>= greater than (or) a>=b 10 >=20 0


equal to

== equal to a= =b 10 == 20 0

!= not equal to a! = b 10 ! =20 1

A simple relational expression contains only one relational operator and takes the following
form:

ae-1 relational operator ae-2

ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables, or
combination of them.

Given below are some examples of simple relational expressions and their values:

4.5 <= 10 TRUE

4.5 < -10 FALSE


-35 >= 0 FALSE

10 < 7+5 TRUE

a+b = c+d TRUE only if the sum of values of a and b is equal to the sum of values of c and
d.

When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evalueated first and then the result is compared. That is, arithmetic
operators have a higher priority over relational operators.

Relational expressions are used in decision statements such as if and while to decide the action
of a running program.

Relational operator complements

Among the six relational operators, each one is a complement of another operator.

> is complement of <=

< is complement of >=

== is complement of !=

Program

main ( )

{
Output
int a= 10, b = 20;

printf (“ %d”, a<b);


1
printf (“ %d”, a<=b);
1
printf (“ %d”, a>b);
0
printf (“ %d”, a>=b);
0
printf (“ %d”, a = =b);
0
printf (“ %d”, a ! =b);
1

}
3. Logical Operators

C has the following three logical operators.

&& ------ logical AND

|| ------ logical OR

! ------ logical NOT

The logical operators && and || are used when we want to test more than one condition and
make decisions .

An example is a > b && x == 10

An expression of this kind, which combines two or more relational expressions is termed as a
logical expression or a compound relational expression. Like a simple relational expression , a
logical expression also yields a value of one or zero according to the truth table shown below

Logical AND ( && )

exp1 exp2 exp1&&exp2

T T T

T F F

F T F

F F F

Logical OR( || )

exp1 exp2 exp1||exp2

T T T

T F T

F T T

F F F
Logical NOT (!)

exp !(exp)

T F

F T

T ------ non zero value (1)

F ------- zero value

Operator Description Example a =10, b=20,c=30 output

&& logical AND (a>b) && (a<c) (10>20) & & (10<30) 0

|| logical OR (a>b) | | (a<c) (10>20) ||(10<30) 1

! logical NOT ! (a>b) ! (10>20) 1

The logical expression a >b && x==10 is true only if a>b is true and x==10 is true. If either of
them are false, the expression is false.

Some examples of the usage of logical expressions are

1 if(age > 55 && salary <1000)

2 if(number < 0 || number > 10)


Program:

main ( )

int a= 10, b = 20, c= 30; Output


0
printf (“ %d”, (a>b) && (a<c));
1
printf (“ %d”, (a>b) | | (a<c));
1
printf (“ %d”, ! (a>b));
}

4. Assignment operators

Assignment operators are used to assign the result of an expression to a variable. In addition to
= , C has a set of shorthand assignment operators of the form

v op= exp;

Where v is a variable , exp is an expression and op is a C binary arithmetic operator. The


operator op= is known as the shorthand assignment operator.

The assignment statemet v op= exp; is equiavalent to v = v op (exp);

Example : x += y; is equivalent tp x = x + y;

Shorthand assignment operators

The use of shorthand assignement operators has three advantages:

1. What appears on the left-hand side need not to be repeated and therefore it becomed easier
to write

2. The statement is more concise and easier to read.

3. The statement is more efficient.

Types

simple assignment

compound assignment

Operator Description Examble

= Simple a=10
assignment

+ =, - =, Compound a+=10  a=a+10


assignment
* =, / =, %= a-=10  a=a-10
Program:
Output
main ( )
10
{ int a= 10,;
20
printf (“ %d”, a);

printf (“ %d”, a+ =10);

5. Increment and decrement operator:

C allows two very useful operators increment and decrement operators ++ and --.

The operator ++ adds 1 to the operand, while - - subtracts 1. Both are unary operators and take
the following form:

++m; or m++ is equivalent to m = m + 1;

- -m; or m- - is equivalent to m = m-1;

We use the increment and decrement statements in for and while loops extensively.

While ++m and m++ mean the same thing when they form statements independently. They
behave differently when they are used in expressions on the right-hand side of an assignment
statement. Consider the following:

m = 5;

y = ++m;

In this case, the value of y and m would be 6. Suppose, if we rewrite the above statement as

m=5;

y = m++;

then, the value of y would be 5 and m would be 6.

A prefix operator(ex: ++ m) first adds 1 to the operand and then the result is assigned to the
variable on left.

A postfix operator(ex: m ++) first assigns the value to the variable on the left hand and then
increments operand.

Rules for increment( ++) and decrement (--) operators


Increment and decrement operators are unary operators and they require variable as their
operands.

When postfix ++ (or --) is used with a variable in an expression, the expression is evaluated first
using the original value of the variable and then the variable is incremented ( or decremented)
by one.

When prefix ++ (or --) is used in an expression, the variable is incremented ( or decremented)
first and then the expression is evaluated using the new value of the variable.

main ( )
Program
{
main ( )
int a= 10, z;
{ Output
Output z= a++;
int a= 10, z; z=10
z=11
printf (“z= %d”,
z= ++a a = 11
a =11 z);
printf (“z= %d”, z); printf (“a=%d”,

printf (“ a=%d”, a); a);

} }

Program:
main ( )
main ( )
{
{
int a= 10, z;
int a= 10, z; Output
Output z= a--;
z= --a z=10
z=9
printf (“z= %d”,
printf (“z= %d”, z); a=9
a =9 z);
printf (“ a=%d”, a);
printf (“a=%d”,
a);

}
}

6. Bitwise Operators

Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on operand).

Bitwise operators manipulate data at bit level. These operators are used for testing the bits or
shifting them right or left. Bitwise operators may not be applied to float or double.

the one’s complement is a unary operator.

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

<< Left shift

>> Right shift

~ One’s complement

Bitwise and operator

The bitwise and(&) is a binary operator that requires two integral operands. It does a bit- by-bit
comparision between the two operands. The result of the comparision is 1 only when both bits
are 1; it is 0 otherwise.

Bitwise AND

a b A &b

0 0 0 8 4 2 1

0 1 0 a =12 1 1 0 0

1 0 0 b =10 1 0 1 0
eg: let a= 12, b=10
1 1 1 a &b 1 0 0 0
a&b = 8
Bitwise incluseive or operator

The bitwise or operator(|) is a binary operator that requires two integral operands. It does a bit-
by-bit comparision between the two operands. The result of the comparision is 0 if both
operands are 0; it is 1 otherwise.

Bitwise OR
8 4 2 1
a b a|b
a =12 1 1 0 0
0 0 0
b =10 1 0 1 0
0 1 1
a|b 1 0 1 0
1 0 1

1 1 1 a | b = 14 a|b

Bitwise Exclusive or operator

The bitwise exclusive or operator is a binary operator that requires two integral operands. It
does a bit-by-bit comparision between the two operands. The result of the comparision is 1 only
if one of the operands is 1; it is 0 if both operands’ bits are 0 or 1—that is, if they are both the
same.

Bitwise XOR

a b a ^b 8 4 2 1

0 0 0 a =12 1 1 0 0

0 1 1 b =10 1 0 1 0

1 0 1 a ^b 0 1 1 0

1 1 0
a^b=6
Program

main ( )

int a= 12, b = 10; Output


8
printf (“ %d”, a&b);
14
printf (“ %d”, a| b);
6
printf (“ %d”, a ^ b);

One’s complement operator

The one’s complement operator is a unary operator applied to an integral value. It complements
the bits in the operand. The result is 1 when the original bit is 0; it is 0 when the original bit is 1.

Bitwise Shift-left operator

The bitwise shift left is a binary operator that requires two integral operands. The first operand
is the value to be shifted. The second operand specifies the number of bits to be shifted. With
this operator the leftmost digits are lost and zero digits are added on the right. If the value of a
variable is left shifted one time, then its value becomes double the original value.

eg: a = 10 then a<<1 = 20

32 16 8 4 2 1
a=10
1 0 1 0

a<<1 1 0 1 0 0 Fill it with ZERO

a<<1 = 20
Bitwise Shift-Right operator

The bitwise shift right operator is a binary operator that requires two integral operands. The
first operand is the value to be shifted. The second operand specifies the number of bits to be
shifted.

If the value of a variable is right shifted one time, then its value becomes half the original value

eg: a = 10 then a>>1 = 5

8 4 2 1
a=10
1 0 1 0

a>>1 0 Discard it
0 1 0 1

a>>1 = 5

Ones complement

If converts all ones to zeros and zeros to ones

Eg: a = 5 then ~a=2 [only if 4 bits are considered]

8 4 2 1
a=5
1 0 1

~a
0 1 0

~a = 2

Program

main ( )

int a= 20, b = 10,c=10; Output


40

11
printf (“ %d”, a<<1);

printf (“ %d”, b>>1);

printf (“ %d”, ~c);

1’s complement = [65535 – given no]

7. Conditional operator (? :)

It is also called ternary operator and is available in C to construct conditional expressions of the
form

Syntax:

exp1 ? exp2 : exp3

where exp1, exp2 and exp3 are expressions.

The operator (? :) works as follows: exp1 is evaluated first , if it is nonzero(true), then the
expression exp2 is evaluated and becomes the value of an expression. If exp1 is false, exp3 is
evaluated and its value becomes the value of the expression. Note that only one of the
expressions (either exp2 or exp3) is evaluatd. For example consider the following statements.

a = 10;

b = 15;

x = (a > b) ? a : b;

In this example x will be assigned the value of b. This can be achieved using the if --- else
statements as follows:

If ( a > b)

x = a;

else

x = b;

Program

main ( )

{ int z;

Output
1
z = (5>3) ? 1:0;

printf (“%d”,z);

8) special operators

C supports some special operators such as comma operator, ampersand operator(&), pointer
operator(*), size of operator, member selection operators( . and ->).

a) coma: ( , )

The comma operator can be used to link the related expressions together. A comma-linked list
of expressions are evaluated left to right and the value of right-most expression is the value of
the combined expression.

For example the statement

value = ( x = 10, y = 5, x + y);

First assigns the value of 10 to x, then assigns 5 to y, and finally assigns 15 (i.e 10 + 5) to value .
Since comma operator has the lower precedence of all operators, the parentheses are necessary.

eg; a=10, b=20

b) Address:(&)

It is used to get the address of a variables.

C) Sizeof ( ) :

The sizeof is a compile time operator and, when used with an operand, it returns the number
of bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.

Examples:

m = sizeof(sum);

n = sizeof(long int);

k = sizeof(235L);

It is also used to to allocate memory space dynamically to variables during the execution of a
program.

Program:
main ( )

int a=10;

float b=20 ;

printf (“ a= %d b=%f’, a,b );

printf (“ Adderss of a =%u “ &a ) ;

printf (“ Adderss of b =%u” &b ) ;

printf (“Size of a = %d ” , sizeof (a) ) ;

printf ( “ Size of b = %d ” . sizeof (b) ) ;

} a b
10 20.00
Out Put :

a=10 b=20.00 1234 5678

Adderss of a =1 2 3 4

Adderss of b = 5 6 7 8 Only for this example

Size of a = 2 bytes Size of b = 4 bytes

-----------------------------------------o------------------------------------------------------------------

EXPRESSIONS

An expression is a sequence of operators and operands that reduces to a single value .

Expressions can be simple or complex. A simple expression contains only one operator. For
example 2+5 is a simple expression whose value is 7. Similarly, -a is a simple expression. A
complex expression contains more than one operator. An example of a complex expression is
2+5*7. An expression always reduces to a single value.

We can divide simple expressions into six categories based on the number of operands, relative
positions of the operand and operator, and the precedence of operator.

An operand is a data item on which an operation is performed.

An operator indicates an operation to be performed on data

eg; z = 3+2*1
z=5

Types Expression

Primary Postfix prefix unary binary ternary

1. Primary expressions

A primary expression consists of only one operand with no operator. In c, the operand in the
primary expression can be a name, a constant or a parenthesized expression. A primary
expression is evaluated first in a complex expression.

Names

A name is any identifier for a variable, a function, or any other object in the language.

Ex: a b12 price INT_MAX

Literal constants

The second type of primary expression is the literal constant. A constant is a piece of data whose
value cannot be changed during the execution of the program.

Ex: 5 123.98 ‘A’ “welcome”

Parenthetical expressions

The third type of primary expression is the parenthetical expression. Any value enclosed in
parentheses must be reducible to a single value and is therefore a primary expression. This
includes any of the complex expressions when they are enclosed in parentheses. Thus, a
complex expression can be enclosed in parentheses to make it a primary expression.

Ex: (2 * 3 + 4) (a = 23 + b * 6)

2. Postifix expressions:

Psetfix expression consists of one operand followed by one operator. The operator will be after
the operands in a postfix expression
Postfix increment

In the postfix increment, the variable is increased by 1. Thus a++ results in the variable a being
increased by 1. The effect is same as a=a+1

Eg:

z=a++ ===> z= a

a = a+1

Postfix decrement

In the postfix decrement, the variable is decreased by 1. Thus a-- results in the variable a being
decreased by 1. The effect is same as a=a-1

Eg:

z=a-- ===> z= a

a = a-1

3. Prefix expressions

In prefix expressions the operator comes before the operand.

Prefix increment

In the prefix increment, the variable is increased by 1. Thus ++a results in the variable a being
increased by 1. The effect is same as a=a+1

Eg: z=++a ===> a = a+1

z= a

Prefix decrement

In the prefix decrement, the variable is decreased by 1. Thus --a results in the variable a being
decreased by 1. The effect is same as a=a-1

Eg:

z=-- a ===> a= a - 1
z=a

4. unary expression:

A unary expression, like prefix expression, consist of one operator and one operand. The
operator comes before the operand.

Sizeof

The sizeof operator tells the size, in bytes, of a type or primary expression. We can use the sizeof
operator with the integer type as shown below.

sizeof(int)

It is also possible to find the size of primary expression. Here are two examples

sizeof -345.23 sizeof x

Unary plus/minus

The unary plus operator does not change the value of the expression. If the expression’s value is
negative, it remains negative.; if the expression’s value is positive, it remains positive.

Thr unary minus operator changes the sign of a value algebraically.—that is to change it from
plus to minus or minus to plus.

Cast operator

The third unary operator is cast operator. The cast operator converts one expression type to
another. For example, to convert an integer to a real number, we would use the following unary
expression.

float (x )

5. Binary expression

It contains 2 operands and one operator. There are many binary expressions.

Multiplicative expressions:

Multiplicative expressions include the multiply, divide and modulus operators. These operators
have the highest priority among the binary operators and are therefore evaluated first among
them.

The result of a multiply operator (*) is the product of the two operands. The operands can be
any arithmetic type (integral or floating – point)
Ex: 10 * 3 // evaluates to 30

22.3 * 2 // evaluates to 44.6

The result of a divide operator (/) depends on the type of the operands. If one or both operands
is a floating- point type, the result is a floating-point quotient. If both operands are integral type,
the result is the integral part of the quotient.

Ex: 10 / 3 // evaluates to 3

22.3/2 // evaluates to 11.15

The modulus operator (%) divides the first operand by the second operand and returns the
remainder.

Both operands must be integral types and the operator returns the remainder as an integer type.

Ex: 10 % 3 // evaluates to 1

22.3 % 2 //error

Additive expressions:

In additive expressions, the second operand is added to or subtracted from the first operand.
The operands in additive expressions can be any arithmetic types (Integral or floating-point).
Additive operators have lower precedence than multiplicative operators, therefore they are
evaluated after multiplicative expressions.

Ex: 3 + 7 // evaluates to 10

3 – 7 // evaluates to -4

Assignment expressions

The assignment expression evaluates the operand on the right side of the operator (=) and
places its value in the variable on the left.

There are two forms of assignment : simple and compound

Simple assignment

Ex: a = 5 b= x + 1 I=I+1

Compound assignment
A compound assignment is a shorthand notation for a simple assignment. It requires that the
left operator be repeated as part of the right expression.

Examples of compound assignement operators are += , -= , *= , /= , %=

Ex: x *= 3 //evaluates to x = x * 3

6. Ternary expression

It contains 3 operands and one operator

Eg ; Exp1? Exp2 :Exp3

If Exp1 is true ,Exp2 is executed. otherwise Exp3 is executed.

The operator (? :) works as follows: Exp1 is evaluated first , if it is nonzero(true), then the
expression Exp2 is evaluated and becomes the value of an expression. If Exp1 is false, Exp3 is
evaluated and its value becomes the value of the expression. Note that only one of the
expressions (either Exp2 or Exp3) is evaluatd. For example consider the following statements.

a = 10;

b = 15;

x = (a > b) ? a : b;

In this example x will be assigned the value of b. This can be achieved using the if --- else
statements as follows:

If ( a > b)

x = a;

else

x = b;

EXPRESSION EVALUATION, PRECEDENCE AND ASSOCIATIVITY

Precedence of operators refers to the order in which they are operated in a program. The
following table provides a list of the precedence of operators.
Operator Precedence Chart

Operator Type Operator Associativity

Primary Expression () Fucntion call


left-to-right
Operators [] Array element reference

+ Unary plus

- Unary minus

++ Increment

-- Decrement

! logical negation
Unary Operators right-to-left
~ ones complement

* Pointer reference

& address

Sizeof size of an object

(type) Type cast(conversion)

ithmetic operators * multiplication left-to-right

/ division

% modulus

+ addition

- subtraction

<< left shift

>> right shift


< less than

<= less than or equal to

> Greater than

>= Greater than equal to

== Equality

!= In equality

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

&& Logical AND

|| Logical OR

?: Conditional expression

*=

/=

%= Assignment operators

+=
-=

&=

^=

|=

<<=

>>=

, comma operator

It is important to note the following:

 Precedence rules decide the order in which different operators are applied.
 Associativity rules decides the order in which multiple occurrences of the same level
operator are applied.

Expression Evaluation

Expressions are evaluated by the ‘C’ compiler based on precedence and associativity rules.

If an expression contains different priority operators then precedence rules are considered.

C = 30 - 10 * 2

2
2

1
3

Here, 10*2 is evaluated first since ‘*’ has more priority than ‘-‘ and ‘=’
If an expression contains same priority then assoiciativity rules are considered i.e. left right (or
right to left)

eg: z= a*b/c

z = 40 * 20 / 10

8
2
z
8
3

Here ‘*’ and ‘/’ have same priority so, left to right associativity is considered

Eg: x =5 *4 + 8/2 x = 5 * 4 + 8 / 2

1 2

x = 24

Parenthesis has highest priority and comma has least priority among operators

Rules for evaluation of expression

1) First, parenthesized sub-expression from left to right are evaluated.

2) If parentheses are nested, the evaluation begins with the innermost sub-expression

3) The precedence rule is applied in determining the order of application of operators in


evaluating sub-expression

4) The associativity rule is applied when two or more operators of the same precedence level
appear in a sub-expression

5) Arithmetic expressions are evaluated from left to right using the rules of precedence.
6) When parentheses are used, the expression within parentheses assumes highest priority

Type Conversions (or) Type casting

Converting one data type into another is the concept of type conversion.
C permits mixing of constants and variables of different types in an expression.
Thre are 2 type conversions
1. Implicit type conversion
2. Explicit type conversion
Implicit type conversion is automatically done by the compiler by converting smaller data type
into a larger data type. If the operands are of different data types, the lower type is automatically
converted to the higher type before the operation proceeds.

Eg: int i,x;

float f;

double d;

long int l;

x = l / i + i - f - d

long float

long float

float

Float

Double
int double

Here, the above expression finally evaluates to a’double’ value

The sequence of rules that are applied while implicit type conversion is as follows:

All short and char are automatically converted to int; then

1. if one of the operands is long double, the other will be converted to long double and the result
will be long double

2. else, if one of the operands is double, the other will be converted to double and the result will
be double.

3. else, if one of the operands is float, the other will be converted to float and the result will be
float.

4. else, if one of the operands is unsigned long int, the other will be converted to unsigned long
int and the result will be unsigned long int .

5. else, if one of the operands is long int, the other will be converted to long int and the result
will be long int .

6. . else, if one of the operands is unsigned int, the other will be converted to unsigned int and
the result will be unsigned int.

The final result of an expression is converted to the type of the variable on the left of the
assignment sign before assigning the value to it. However the following changes are introduced
during the final assignment.

Float to int causes truncation of the fractional part.

Double to float causes rounding of digits.

Long int to int causes dropping of the excess higher order bits.
Explicit type conversion is done by the user by using (type) operator

Rather than let the compiler implicitly converts data, we can convert data from one type to
another ourself using explicit type conversion. Explicit type conversion uses the unary cast
operator.
To cast data from one type to another, we specify the new type in parentheses before the value
we want converted. For example to convert an integer, a, to a float, we code the expression
shown below.

(float)a

Note that in this operation, the value stored in a is still of type int, but the value of the expression
is promoted to float.

Eg: int a,c;

float b;

c = (int) a + b

int float

float

int

Here, the resultant of ‘a+b’ is converted into ‘int’ explicitty and then assigned to ‘c’

Program:

main ( )

{
Output
printf (“%d”, 5/2);
2
printf (“%f”, 5.5/2);
2.75
printf (“%f”, (float) 5/2);

You might also like