Fundamentals of Computer and Programming in C: (CSE - 101 F)

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 339

Fundamentals of Computer and

Programming in C
(CSE -101 F)
Prepared By:
Ms.Aanchal Aggarwal
[email protected]
A.P in CSE department

CSE/IT

1/338

Syllabus
CSE-101-F

Fundamentals of Computers & Programming in C

Section A
An Overview of Computer System and Operating Systems:
Fundamentals :- Evaluation of computers, Hardware organization of a computer, Introduction to
microprocessor, generations of microprocessors, Commonly used CPUs, Input/Output devices,
Input/Output ports and connectors.
Operating System Basics: Introduction to Operating system, Functions of an Operating Systems,
Classification of Operating Systems, Basic introduction to DOS, UNIX/LINUX OS, Windows XP.
Section B
Basic Introduction to System Software and Programs:Machine Language, Assembly Languages, Low level languages, High level Languages, Types of high level
languages, Compiler, Interpreter, Assembler, Loader, Linker, Relationship between Compiler, Interpreter,
Loader and Linker.
Basic Introduction to Computer Networks :Data Communication, modulation, Network devices, LAN, LAN topologies, WAN, OSI Reference model,
Introduction to Internet and protocols : TCP/IP Reference model, Backbone network, Network connecting
devices, Hypertext documents, HTTP, DNS, Network Security.

CSE/IT

2/338

Syllabus
Section C
An Overview of C:
Constants, Variables and Data types, operators and Expressions, managing I/O operations, Decision Making and
branching, Decision Making and looping, Arrays, Character Arrays and Strings, User Defined Functions.
Structure and Union in C :
Defining structure, declaring variables, Accessing structure members, structure initialization, copying and
comparing structures variables, operations on individual members, Array of structure, structure with
structure,unions, size of structure.
Section D
Pointers in C :
Introduction, Understanding Pointers, Accessing the address of a variable, Declaring Pointer Variables,
Initialization of Pointer Variables, Accessing a variable through its pointer, Chain of Pointers, Pointer
Expressions, Pointer Increments and Scale Factors, pointers and Arrays, Pointer and Character Strings,
Arrays of Pointers, Pointers as Function Arguments, Functions Returning Pointers, Pointers to Functions.
Dynamic Memory Allocation and File Management in C :Introduction, Dynamic memory allocation, allocating a block of memory: Malloc, allocating multiple blocks of
memory: Calloc. Releasing the used space: Free, Altering the size of block: Realloc, Defining and opening file,
closing file, I/O operation on files, error handling during I/O operations, Random Access to files and
command line arguments.

CSE/IT

3/338

Assessment Criteria
Total : 150 Marks
Theory Exam : 100 Marks
Marks of Class Work:50
Sessional
:15 Marks
Pre-University
:15 Marks
Attendance
:10 Marks
Class Performance :10 Marks

CSE/IT

4/338

Background

Basics of computer
Knowledge of operating systems
Knowledge of programming languages
Knowledge of compilers and interpreters

CSE/IT

5/338

References
Fundamental of Computers and Programing with
C, by A. K. Sharma, Dhanpat Rai Publications, New
Delhi.
Fundamental of Information Technology, by
A.Leon & M.Leon.
Computer Networks ,4th Edition, by Andrew S.
Tanenbaum
Programming in C, by Lipschutz, SCHAUM
SERIES OUTLINES
CSE/IT

6/338

Guidelines and
Instructions for students
Examiner will set 9 questions in total.
Two questions from each section and one question
covering all sections which will be Q.1.
Q.1 is compulsory and of short answer type.
Each question carries equal mark (20 marks).
Students have to attempt 5 questions in total.
75% Attendance is compulsory.
Within the semester 3 Assignments and 11 Tutorials
would be given.
CSE/IT

7/338

Assignments
Assignment 1:
1. Explain constants,variable and data types in c
2. Explain User Defined Functions.
3. Differentiate between Structures and union
Assignment 2:
1. What are Pointers.Explain with example
2. Explain the use of malloc(),calloc(),realloc()
3. Explain Command line arguments
CSE/IT

8/338

Tutorial-1
Q1.C is a middle level language. Comment on it.
Q2.What are the different operators available in C.
Q3.Explain the syntax of IF, IF-ELSE, Construct in
detail.
Q4.Explain the syntax of switch case with

example.

CSE/IT

9/338

Tutorial-2
Q1.Explain the different loops available in c with an
example.
Q2.Explain user defined function with an example.
Q3.Difference between call by value and call by
reference.
Q4.Explain the different inbuilt functions available in c.

CSE/IT

10/338

Tutorial-3
Q1.Explain pointers with Character string.
Q2.Explain pointer to function.
Q3. What is the O/P:
Main(){int j,a[]= {10,20,30,40,50}
For (j=0;j<5;j++)
{ printf(%d,a);
A++;
}}

Q4.Write a C program to find Average of element using


array.
CSE/IT

11/338

Section -A

CSE/IT

12/338

An Overview of Computer

Evolution of Computers
Hardware organization of computer
Introduction to microprocessor
Generations of microprocessors
Commonly used CPUs
Input/Output devices
Input/Output ports and connectors.

CSE/IT

13/338

Evolution of Computers

The need for a device to do calculations along with growth in commerce


and other human activities explain the evolution of computers. Having the
right tool to perform right has always been important for human beings. In
this post, I have mentioned some important history in the evolution of
computers.
In the beginning, when the task was simply counting or adding, people
used either their fingers or pebbles along lines in the sand in order to
simply the process of counting, people in Asia minor built a counting
device called ABACUS, the device allowed users to do calculations using a
system of sliding beads arranged on a rack.
With the passage of time, many computing devices such as Napier bones
and slide rule were invented. It took many centuries for the advancement in
computing devices. In 1642, a French mathematician, Blaise Pascal
invented the first functional automatic calculator. The brass rectangular box
also called Pascaline, used eight movable dials to add sums and eight
figures only.
CSE/IT

14/338

Cont

CSE/IT

15/338

Cont

The real beginning computer was made by an English mathematician


Charles Babbage in 1822. He proposed a engine to perform difference
equations, called a difference engine. It would print results automatically.
However, Babbage never quite made a fully functional difference engine,
and in 1833, he quit working on it to concentrate on analytical engine.
The basic design of the engine included input devices in the form of
perforated cards containing operating system as a store for memory of
1,000 numbers up to 50 decimal digits long. It also contained a controlled
unit that allowed processing instructions at any sequence, output device to
produce printed results. Babbage borrowed the idea of punch cards to
encode the instructions in the machine from the Joseph Marie jacquards
loom.

CSE/IT

16/338

Cont
A computer as shown in Fig. performs basically five major operations or
functions irrespective of their size and make. That are: 1) It accepts data or instructions by way of input
2) It stores data
3) It can process data as required by the user
4) It gives results in the form of output
5) It controls all operations inside a computer

CSE/IT

17/338

Hardware Organization of
Computer
1.
2.
3.
4.
5.

Central Processing Unit (CPU)


Memory
Input device
Output device:
Mass storage device

CSE/IT

18/338

Input Device

An input device presents data to the processing unit in a machine-readable


form. Although the keyboard is a common input device for a small
computer, a system may also support various other input devices such as
Optical Character Recognition (OCR), Magnetic Ink Character
Recognition (MICR), mark sense reader, etc

CSE/IT

19/338

Output Device

Output devices receive information from the CPU and present it to the user
in the desired Form. Output devices include
display screen
loudspeakers,
printers, plotters, etc.

CSE/IT

20/338

CPU

This part of the computer that executes program instructions is known as


the processor or Central Processing Unit (CPU).
In a microcomputer, the CPU is based on a single electronic component,
the microprocessor chip, within the system unit or system cabinet. The
system unit also includes circuit boards, memory chips, ports and other
components.
A microcomputers system cabinet will also house disk drives, hard disks,
etc., but these are considered separate from the CPU.
The CPU has two parts
The Control Unit (CU) and the Arithmetic Logic Unit (ALU).
In a microcomputer, both are on a single microprocessor chip.

CSE/IT

21/338

Memory Unit

Memory - also known as the primary storage or main memory - is a part of


the microcomputer that holds data and instructions.
Part of the contents of the memory is held only temporarily, that is, it is
stored only as long as the microcomputer is turned on.
When you turn the machine off, the contents are lost. The capacity of the
memory to hold data and program instructions varies in different
computers. The original IBM PC could hold approximately several
thousand characters of data or instructions only. But modern
microcomputers can hold millions or even billions of characters in their
memory

CSE/IT

22/338

Control Unit
The control unit tells the rest of the computer system how to carry out a
programs instructions.
It directs the movement of electronic signals between memory which
temporarily holds data, instructions and processes information - and the ALU.
It also directs these control signals between the CPU and input/output devices.

CSE/IT

23/338

ALU

Arithmetic Logic Unit, usually called the ALU, performs two types of
operations
arithmetical
logical.
Arithmetical operations are the fundamental mathematical operations
consisting of
addition, subtraction, multiplication and division.
Logical operations consist of comparisons. That is two pieces of data are
compared to see whether one is
equal to, less than, or greater than the other.

CSE/IT

24/338

Introduction to
Microprocessor

Microprocessor incorporates most or all of the functions of a computer's


central processing unit (CPU) on a single integrated circuit (IC, or
microchip). The first microprocessors emerged in the early 1970s and were
used for electronic calculators, using binary-coded decimal (BCD)
arithmetic on 4-bit words. Other embedded uses of 4-bit and 8-bit
microprocessors, such as terminals, printers, various kinds of automation
etc., followed soon after. Affordable 8-bit microprocessors with 16-bit
addressing also led to the first general-purpose microcomputers from the
mid-1970s on.
Since the early 1970s, the increase in capacity of microprocessors has been
a consequence of Moore's Law, which suggests that the number of
transistors that can be fitted onto a chip doubles every two years. Although
originally calculated as a doubling every year, Moore later refined the
period to two years. It is often incorrectly quoted as a doubling of
transistors every 18 months.

CSE/IT

25/338

P1 (086) First-Generation
microprocessors

The first generation of processors represents the series of chips from Intel
that were found in the first PCs. IBM, as the architect of the PC at the time,
chose Intel processors and support chips to build the PC motherboard,
setting a standard that would hold for many subsequent processor
generations to come.

CSE/IT

26/338

8088 and 8086


microprocessors

Intel introduced a revolutionary new processor called the 8086 back in


June of 1978. The 8086 was one of the first 16-bit processor chips on the
market; at the time virtually all other processors were 8-bit designs. The
8086 had 16-bit internal registers and could run a new class of software
using 16-bit instructions. It also had a 16-bit external data path, which
meant it could transfer data to memory 16 bits at a time.
The address bus was 20 bits wide, meaning that the 8086 could address a
full 1MB (220) of memory. This was in stark contrast to most other chips
of that time that had 8-bit internal registers, an 8-bit external data bus, and
a 16-bit address bus allowing a maximum of only 64KB of RAM (216).

CSE/IT

27/338

80186 and 80188


microprocessors

After Intel produced the 8086 and 8088 chips, it turned its sights toward
producing a more powerful chip with an increased instruction set. The
company's first efforts along this line - the 80186 and 80188 - were
unsuccessful. But incorporating system components into the CPU chip was
an important idea for Intel because it led to faster, better chips, such as the
286. The relationship between the 80186 and 80188 is the same as that of
the 8086 and 8088; one is a slightly more advanced version of the other.
Compared CPU to CPU, the 80186 is almost the same as the 8088 and has
a full 16-bit design. The 80188 (like the 8088) is a hybrid chip that
compromises the 16-bit design with an 8-bit external communications
interface. The advantage of the 80186 and 80188 is that they combine on a
single chip 15 to 20 of the 80868088 series system components - a fact
that can greatly reduce the number of components in a computer design.
The 80186 and 80188 chips were used for highly intelligent peripheral
adapter cards of that age, such as network adapters

CSE/IT

28/338

8087 Coprocessor

Intel introduced the 8086 processor in 1976. The math coprocessor that
was paired with the chip-the 8087-often was called the numeric data
processor (NDP), the math coprocessor, or simply the math chip. The 8087
is designed to perform high-level math operations at many times the speed
of the main processor. The primary advantage of using this chip is the
increased execution speed in number-crunching programs, such as
spreadsheet applications.

CSE/IT

29/338

COMMANLY USED CPU


CPU (Central Processing Unit)
The CPU is the brain of the computer. Sometimes referred to simply as the
processor or central processor, the CPU is where most calculations take
place. In terms of computing power, the CPU is the most important element
of a computer system

CSE/IT

30/338

Slot 1, Slot A, Socket 7,


Socket 478

CPU socket
is the connector that interfaces between a computer's motherboard and
the processor itself. Most CPU sockets and processors in use today are
built around the pin grid array (PGA) architecture, in which the pins on
the underside of the processor are inserted into the socket, usually with
zero insertion force (ZIF) to aid installation. In contrast to this, a
couple current and upcoming sockets use a land grid array (LGA) in
which the pins are on the socket side instead and come in contact with
pads on the processor.
Slot
based processors are cartridge shaped and fix into a slot that looks
similar to expansion slots.
General
In general sockets and slots are used so that the Processor and the
motherboard of a computer are able to communicate with each other.
And it depends on the processor on what type of socket or slot that it
might use.
CSE/IT

31/338

Slot 1, Slot A, Socket 7,


Socket 478

Slot 1, Slot A, and Socket 7 are all various types of CPU (Central
Processing Unit) Interfaces. Interfaces are the connection points between
the motherboard and any add on or changeable components including
processor chips, peripherals, extension cards, etc. There are two main
types of interfacesslots and sockets.
Slot style interfaces accept Single Edge Contact (SEC) cartridges. An SEC
is a way to package microprocessors so that there is a slim single edge
which connects to the interface, allowing for perpendicular mounting to the
motherboard.
Socket style interfaces work on a principle or plug and socket similar to
that of a common wall socket. The component to be plugged into the
interface will have a Pin Grid Array (PGA)-a square chip package with a
pin pattern often of high density.
In the evolution of motherboards and CPU interfaces, the socket style
interface was the preference among manufactures until the mid to late 90s
when slots became the preferred interface. Although both are present in
the market, the current shift is back toward socket style CPU interfaces.
CSE/IT

32/338

Dual Processor

A computer that contains two CPUs. Dual processor systems (DP systems)
have two independent CPU chips and differ from a dual core system (DC
system), which has two processors built into the same CPU chip.
Not all operating systems or programs (for example Word) are able to
support dual processors.

CSE/IT

33/338

Quad Processor

A quad processor system is any system with 4 CPUs working in parallel.


Typically, all 4 CPUs are of the same type.
Quad processor systems are uncommon for home computer users.

CSE/IT

34/338

INPUT DEVICES

Parts of Computer, which are used to feed data and commands are called
Input Devices
Some Input Devices are:
Keyboard
Mouse
Joy Stick
Scanner
Voice Input System

CSE/IT

35/338

Cont
Keyboard is the most commonly used Input Device. The keys on the
keyboard can be classified as follows:
Alphabetic keys
Numeric keys
Function keys
Symbols keys
Special keys

CSE/IT

36/338

Cont
Mouse is a pointing device which is used to draw, move and resize the
picture and words. It has a small ball inside ,which when rolls, moves the
rollers, which move the pointer on the screen of monitor. it has two buttons
on the top

CSE/IT

37/338

Cont
A joystick consists of vertical bar. It can be rotated in various directions.
This rotation moves the cursor to the desired position.

CSE/IT

38/338

OUTPUT DEVICES

Output devices are the devices which are used to get final result of work
done on computer.
Following are some Output Devices:
Monitor or Visual Display Unit
Printers
Speakers

CSE/IT

39/338

Cont

Every Computer has a television like device. It is called monitor or visual


display unit. It is used to display information to us.

CSE/IT

40/338

Cont

These days a lot of printers are available in the market which can be
divided as follows:
Impact Printers
Non-Impact Printers

CSE/IT

41/338

Cont
Speakers are used to listen sounds from a computer system. When you are
watching a cartoon film, the picture appears on the monitor, but you can
hear cartoon character talking only if speakers are attached to your
computer

CSE/IT

42/338

INPUT/OUTPUT PORTS

This is the standard input and output facilities in Isis. Input from and
output to any endpoint is handled using the same mechanism known as a
port, which allows the same procedures to be used for reading, writing, and
other operations, regardless of where the data is coming from or going to.
It will usually not be necessary to look at anything in this list, and of
course, nothing in the list should ever be modified manually.

CSE/IT

43/338

Cont
One can do the following - :
Open a port
Close a Port
Read and Write Data
Port Position
Port Status
Port Queries
Port Utilities

CSE/IT

44/338

CONNECTORS

The part of a cable that plugs into a port or interface to connect one device
to another. Most connectors are either male (containing one or more
exposed pins) or female (containing holes in which the male connector can
be inserted). Every house or office today is equipped with a multitude of
connectors. Connectors are devices used for mating and de-mating
electrical power connections. Connectors are responsible for power
transfers and information transfers among machines and people that are
spread over different locations.
All electronic devices require a constant source of power to function and
like all electronics even computers require power to function. Computer
PSU is a term given to any the wires that that convert lethal electricity into
usable and safe electricity. Each PSU requires connectors to function and
this article is going to elaborate on the connectors used in these power
supplies.

CSE/IT

45/338

Cont

CSE/IT

46/338

Introduction to Operating
system

Introduction to Operating System


Functions of an Operating System
Types of an Operating System
Introduction to DOS ,UNIX/LINUX OS, Windows XP

CSE/IT

47/338

Introduction to Operating
System

The operating system is the core software component of your computer.


It performs many functions and is, in very basic terms, an interface
between your computer and the outside world. In the section about
hardware, a computer is described as consisting of several component parts
including your monitor, keyboard, mouse, and other parts.
The operating system provides an interface to these parts using what is
referred to as "drivers". This is why sometimes when you install a new
printer or other piece of hardware, your system will ask you to install more
software called a driver.

CSE/IT

48/338

Functions of an Operating
System
Resource management
The resource management function of an OS allocates computer resources
such as CPU time, main memory, secondary storage, and input and output
devices for use.
Data management
The data management functions of an OS govern the input and output of the
data
and
their
location,
storage,
and
retrieval.
Job (task) management
The job management function of an OS prepares, schedules, controls, and
monitors jobs submitted for execution to ensure the most efficient
processing. A job is a collection of one or more related programs and their
data standard means of communication between user and computer.

CSE/IT

49/338

Cont

CSE/IT

50/338

Types of an Operating
System

Windows XP Professional Edition


Windows XP Home Edition
Windows 2000
Windows ME
Windows 98
Windows NT
Windows 95
DOS
UNIX/LINUX

CSE/IT

51/338

Introduction to MS-DOS

An operating system is a set of interrelated programs that manage and


control computer processing.The Microsoft Disk Operating System,
MS-DOS, is a traditional microcomputer operating system that
consists of four major components.

The Operating-system loader


- It brings the operating system from the startup into RAM.
- Bootstrapping

The MS-DOS BIOS


- BIOS stands for Basic Input/Output systems
- Loaded from the file IO.SYS during initialization.
- Layer that sits between operating system kernel and
hardware.

CSE/IT

52/338

Cont
The User Interface (shell)
- Conventional program that allows the user to interact with the
operating system.
- Default MS DOS user interface is a shell program called
Command.com

The MS-DOS Kernel

- Heart of the operating system

- it is a proprietary program supplied by Microsoft corporation.

CSE/IT

53/338

MS-DOS Kernel
The kernel provides a collection of hardware-independent
services called system functions.
- File Management
- Memory Management
- Device Input and Output
- Process control

CSE/IT

54/338

File Management

Block Devices are accessed on a sector basis. The MS- DOS kernel
through the device driver sees a block as a logical fixed size array of
sectors. the device driver in turn translates the logical sector requests
from the MS DOS into physical locations on the block device.
MS DOS file system is divided into four parts
- Boot Sector
- Always at the beginning of a partition.
- Contains OEM identification, a loader routine , and a BIOS
parameter block

CSE/IT

55/338

Cont
- File Allocation Tables (FAT)
- Provides a map to the storage locations of files on the disk by
indicating which
clusters are allocated to each file.
- Second copy of FAT as back up.
- Free cluster is found by scanning the FAT for a zero value.
- Root directory
- Root directory entries are 32 bytes long.
- Each entry includes a filename and extension, size, starting FAT
entry, the time and date the
file was created and the files attributes.

CSE/IT

56/338

UNIX

UNIX is multi-user and multi-tasking operating system.


Multi-tasking: Multiple processes can run concurrently.
Example, different users can read mails, copy files, and print all at once.

CSE/IT

57/338
57

Logging In UNIX

Enter login name and password !


System password file: /etc/passwd (usually).
You can change password using the command: passwd.

CSE/IT

58/338
58

UNIX Shell

After a successful login, the shell program is run. The default shell of
bingsuns: tcsh
bingsun2% ps
PID TTY TIME CMD
2159 pts/2 0:00 tcsh
Shell is a command line interpreter that reads user commands and executes
them.

CSE/IT

59/338
59

Unix Shells

Common Shells: Bourne shell, the C shell, and the Korn shell.
The shell on bingsuns is tcsh (tc shell).
Users can switch between shells, using the commands bash, csh, ksh, sh.
Control D (^d) to return back to original shell, or just use the command:
exit.

CSE/IT

60/338
60

Some shell commands

Most Important command: man (manual pages).


Help: unix commands, C functions.
Usage: man <command/function>
Try man man !
Example:
man ls, man passwd, man printf.

CSE/IT

61/338
61

Some shell commands (cont)

pwd: working directory (/u0/users/2/kliu1).


ls: list contents of directory
mkdir <dir-name>: make directory
rmdir <dir-name>: remove an empty directory
rm r <dir-name>: remove a directory with all the contents
cd <directory>: change directory, ~/ means your home directory
cp <source> <target>: copy command.

CSE/IT

62/338
62

File System

Hierarchical arrangement of files and directories.


Top level: root or /
e.g.: cd /
Current directory, .. One level higher directory
e.g.: cd . No change for it is current directory
or cd .. Change to parent directory.

CSE/IT

63/338
63

File System (cont)

Pathname: absolute and relative.


Absolute pathname: /u0/users/2/kliu1
Relative pathname: abc.

CSE/IT

64/338
64

UNIX Editors

Different editors: emacs, pico, vi


emacs <filename>
pico <filename>
vi <filename>

CSE/IT

65/338
65

Starting Windows XP
Windows XP
Starts when computer is turned on
Elements of the desktop
Icon
Pointer
Desktop
Date/Time control
Taskbar
Start button
Notification area

CSE/IT

66/338

Starting Windows XP

shows the Windows XP desktop


CSE/IT

67/338

Starting Windows XP

Windows XP desktop uses a graphical user interface


Graphical user interface (GUI)
Displays icons to represent items stored on the computer
Icons: Pictures of familiar objects

CSE/IT

68/338

The Windows XP Desktop

Desktop
Area that appears on the screen when Windows XP starts
A workspace for projects and tools
Uses default settings when the computer is first started
Default settings: settings preset by the operating system
Appearance can be changed by the user

CSE/IT

69/338

Using a Pointing Device

A pointing device
Helps the user interact with objects on the computer screen
Comes in many shapes and sizes

Mouse
Most common pointing device

CSE/IT

70/338

Anatomy of a Window

Controls
Located in a window
Graphical or textual objects used for
Manipulating the window
Using the program
Examples
Menu bar
Sizing buttons
Status bar
Title bar
Toolbar
Workspace

CSE/IT

71/338

SECTION-2
Basic Introduction to System Software and Programs
Basic Introduction to Computer Networks

CSE/IT

72/338

Basic Introduction to System


Software and Programs
1. Introduction to Programming Language
2. Characteristics of good Programming Language
3. Machine Language
3.1) Advantages of Machine language
3.2) Disadvantages of Machine language
4. Low Level Language
5.High Level Language
6.Compiler
7.Interpreter
8.Assembler
9.Loader
10.Linker
CSE/IT

73/338

Introduction to Programming
Language

The term programming language usually refers to high-level languages,


such as BASIC, C, C++, COBOL, FORTRAN, Ada and Pascal.
High-level programming languages, while simple compared to human
languages, are more complex than the languages the computer actually
understands, called machine languages. Each different type of CPU has
its own unique machine language.
Lying between machine languages and high-level languages are
languages called assembly languages. Regardless of what language you
use, you eventually need to convert your program into machine language
so that the computer can understand it.
There are two ways to do this:
1) compile the program.
2) interpret the program

CSE/IT

74/338

Characteristics of good
Programming Language
1. Clarity of source code the extent to which inherent language features
support source code that is readable and understandable and that clearly
reflects the underlying logical structure of the program.
2. Complexity management (architecture support) the extent to which
inherent language features support the management of system complexity,
in terms of addressing issues of data, algorithm, interface, and architectural
complexity.
3. Concurrency support the extent to which inherent language features
support the construction of code with multiple threads of control (also
known as parallel processing).
4. Distributed system support the extent to which inherent language features
support the construction of code to be distributed across multiple platforms
on a network.
5. Maintainability the extent to which inherent language features support the
construction of code that can be readily modified to satisfy new
requirements or to correct deficiencies.
CSE/IT

75/338

Cont
6. Mixed language support the extent to which inherent language features
support interfacing to other languages.
7. Object-oriented programming support the extent to which inherent
language features support the construction of object-oriented code.
8. Portability the extent to which inherent language features support the
transfer of a program from one hardware and/or software platform to
another.
9. Real-time support the extent to which inherent language features support
the construction of real-time systems

CSE/IT

76/338

Machine Language
The lowest-level programming language (except for computers that utilize
programmable microcode) Machine languages are the only languages
understood by computers.
While easily understood by computers, machine languages are almost
impossible for humans to use because they consist entirely of numbers.
Programmers, therefore, use either a high-level programming language or
an assembly language. An assembly language contains the same
instructions as a machine language, but the instructions and variables have
names instead of being just numbers.

CSE/IT

77/338

Advantages of Machine
language

It is a most efficient in term of storage area use and execution speed and
it also allows programmer to utilize the computer's potential for
processing data.
The only advantage is that program of machine language run very fast
because no translation program is required for the CPU.
In machine language, the very basic and specific commands may be
used, like to where the specific data will be stored, how operations and
functions be carried out. and since it is in a code the machine can
understand, it may not need a compiler.

CSE/IT

78/338

Disadvantages of Machine
Language
1. It is very difficult to program in machine language. The programmer has to
know details of hardware to write program.
2. The programmer has to remember a lot of codes to write a program which
results in program errors.
3. It is difficult to debug the program

CSE/IT

79/338

Assembly language

Machine languages consist entirely of numbers and are almost impossible


for humans to read and write. Assembly languages have the same structure
and set of commands as machine languages, but they enable a programmer
to use names instead of numbers.

Each type of CPU has its own machine language and assembly language,
so an assembly language program written for one type of CPU won't run
on another. In the early days of programming, all programs were written in
assembly language.

CSE/IT

80/338

Comparison Between
Assembly & Machine
Language

Machine language is the actual bits used to control the processor in the
computer, usually viewed as a sequence of hexadecimal numbers (typically
bytes).
Assembly language is a more human readable view of machine language.
Instead of representing the machine language as numbers, the instructions
and registers are given names (typically abbreviated words, or mnemonics,
eg ld means "load").
An assembly language program (ie a text file) is translated to machine
language by an assembler. A disassembler performs the reverse function.
Machine language faster than assembly language even than assembly
language depend upon machine language

CSE/IT

81/338

Advantage of Assembly
language

Assembly language is a symbolic representation of a processor's native


code.
Using machine code allows the programmer to control precisely what
the processor does. It offers a great deal of power to use all of the
features of the processor.
The resulting program is normally very fast and very compact. In small
programs it is also very predictable. Timings, for example, can be
calculated very precisely and program flow is easily controlled.
It is often used for small, real time applications.

CSE/IT

82/338

Disadvantage of Assembly
language

The programmer needs to have a good understanding of the hardware


being used. As programs become larger, assembly language get very
cumbersome.
Maintenance of assembly language is notoriously difficult, especially if
another programmer is brought in to carry out modifications after the
code has been written.
Assembly langauge also has no support of an operating system, nor does
it have any complex instructions. Storing and retrieving data is a simple
task with high level languages; assembly needs the whole process to be
programmed step by step.
Mathmatical processes also have to be performed with binary addition
and subtraction when using assembly which can get very complex.
Finally, every processor has its own assembly language. Use a new
processor and you need to learn a new language each time.

CSE/IT

83/338

High Level Language

Programs written in high-level languages are translated into assembly


language or machine language by a compiler. Assembly language programs
are translated into machine language by a program called an assembler.
Every CPU has its own unique machine language. Programs must be
rewritten or recompiled, therefore, to run on different types of computers.
A programming language such as C, FORTRAN, or Pascal that enables a
programmer to write programs that are more or less independent of a
particular type of computer. Such languages are considered high-level
because they are closer to human languages and further from machine
languages. In contrast, assembly languages are considered low-level
because they are very close to machine languages

CSE/IT

84/338

Advantages of High Level


Language

In high level languages we can write programs in English like manner


and is more convenient to use. Programmer can perform complex task
by using high level languages with less efforts.
There are different high level languages such as FORTRAN (Formula
Instructions), BASIC (Beginners All Purpose Symbolic Instruction
Code), COCOL (Common Business Oriented Language), PASCAL, C+
+, Visual Basic, VB. Net etc.
High level languages have many advantages. High level languages are
very similar to nature language such as English so they are very easy to
learn and use. For higher level languages programmers needs not to
learn about internal structure of the computer.

CSE/IT

85/338

Cont

High level language programs require less time and efforts that due the
preparation cost of the program.
High level programs are very easy to maintain than lower level
languages. In lower level languages instruction are difficult and very
hard to locate, correct and modify but in high level languages it is very
easy to understand and modify when desired.
In high level languages programmer needs not to write all steps because
computer take cares of all small error. Compilers of high level languages
automatically catch and point out the errors made by the programmers.

CSE/IT

86/338

Disadvantages of High
Level Language

Though it is much easier to code in a high level language, oftentimes


access to more low-level functionalities are lost. For instance, the ability
to communicate directly with the compiler and alter code before it gets
transferred into machine code is lost.
To make it more easier for the programmer to understand and write
code. High level programming languages like C, C++ and Java give you
comfort and a pool of options because they basically use a syntax that is
similar to the everyday English we speak. Coding a computer today is
just one step below to talking to a human. It is that easy. Now, why are
low-level programming languages important? Low level programming
languages are important because of space and speed. If you write a
program in a high level language, say Java, first the Java Compiler will
compile it to byte code. Now, this byte code is again compiled during
run time to assembly code(low level) which in turn is again converted to
executable code.But, when you write low level code, it is directly
converted into executable code avoiding all the other steps. This will
incredibly save you space and increase speed.
CSE/IT

87/338

Types of High Level


Language
a) BASIC- In computer programming, BASIC is a family of high-level
programming languages. The original BASIC was designed in 1964. At
the time, nearly all use of computers required writing custom software,
which was something only scientists and mathematicians tended to do. The
language and its variants became widespread on microcomputers in the late
1970s and 1980s. BASIC remains popular to this day in a handful of
highly modified dialects and new languages influenced by BASIC such as
Microsoft Visual Basic
b) COBOL - COBOL is one of the oldest programming languages. Its name is
an acronym for COmmon Business-Oriented Language, defining its
primary domain in business, finance, and administrative systems for
companies and governments

CSE/IT

88/338

Types of High Level


Language
c) FORTRAN - Fortran is a general-purpose, procedural, imperative
programming language that is especially suited to numeric computation
and scientific computing. Originally developed by IBM at their campus in
south San Jose, California in the 1950s for scientific and engineering
applications, Fortran came to dominate this area of programming early on
and has been in continual use for over half a century in computationally
intensive areas such as numerical weather prediction, finite element
analysis, computational fluid dynamics, computational physics and
computational chemistry.

CSE/IT

89/338

Compilation

Compilation is a process that translates a program in one language (the


source language) into an equivalent program in another language (the
object or target language).
A compiler is a computer program that translates a program in a source
language into an equivalent program in a target language.
A source program/code is a program/code written in the source language,
which is usually a high-level language.
A target program/code is a program/code written in the target language,
which often is a machine language or an intermediate code

CSE/IT

90/338

Compilation

CSE/IT

91/338

Cont..

CSE/IT

92/338

Symbol Table

Identifiers are names of variables, constants, functions, data types, etc.


Store information associated with identifiers
Information associated with different types of identifiers can be
different
Information associated with variables are name, type, address,size
(for array), etc.
Information associated with functions are name,type of return
value, parameters, address, etc.
The scanner, parser, and semantic analyzer put names of identifiers
in symbol table.
The semantic analyzer stores more information (e.g. data types) in
the table.
The intermediate code generator, code optimizer and code
generator use information in symbol table to generate appropriate c
ode.
CSE/IT

93/338

Literal table

Store constants and strings used in program


reduce the memory size by reusing constants and strings
Can be combined with symbol table

CSE/IT

94/338

Parse tree

Dynamically-allocated, pointer-based structure


Information for different data types related to parse trees need to be stored
somewhere.
Nodes are variant records, storing information for different types of
data
Nodes store pointers to information stored in other data structure, e.g.
symbol table

CSE/IT

95/338

Interpreter

An interpreter translates some form of source code into a target


representation that it can immediately execute and evaluate.
The structure of the interpreter is similar to that of a compiler, but the
amount of time it takes to produce the executable representation will vary
as will the amount of optimization. The following diagram shows one
representation of the differences.

CSE/IT

96/338

Cont C

CSE/IT

97/338

Compiler characteristics

spends a lot of time analyzing and processing the program


the resulting executable is some form of machine- specific binary code
the computer hardware interprets (executes) the resulting code
program execution is fast

CSE/IT

98/338

Interpreter characteristics:

relatively little time is spent analyzing and processing the program


the resulting code is some sort of intermediate code
the resulting code is interpreted by another program
program execution is relatively slow

CSE/IT

99/338

Assemblers

There are two main classes of programming languages: high level (e.g., C,
Pascal) and low level. Assembly Language is a low level programming
language. Programmers code symbolic instructions, each of which
generates machine instructions.

An assembler is a program that accepts as input an assembly language


program (source) and produces its machine language equivalent (object
code) along with the information for the loader.

CSE/IT

100/338

Advantages of coding in
assembly language

Provides more control over handling particular hardware components


May generate smaller, more compact executable modules
Often results in faster execution

CSE/IT

101/338

Disadvantages of coding in
assembly language

Not portable
More complex
Requires understanding of hardware details (interfaces)

CSE/IT

102/338

Assembler
1. Generate machine instructions
evaluate the mnemonics to produce their machine code
evaluate the symbols, literals, addresses to produce their equivalent
machine addresses
convert the data constants into their machine representations
2. Process pseudo operations

CSE/IT

103/338

Two Pass Assembler


A two-pass assembler performs two sequential scans over the source code:
Pass 1: symbols and literals are defined
Pass 2: object program is generated

CSE/IT

104/338

Data Structures

Location counter (LC): points to the next location where the code will be
placed
Op-code translation table: contains symbolic instructions, their lengths and
their op-codes (or subroutine to use for translation)
Symbol table (ST): contains labels and their values
String storage buffer (SSB): contains ASCII characters for the strings
Configuration table: contains pointer to the string in SSB and offset where
its value will be inserted in the object code

CSE/IT

105/338

Cont

CSE/IT

106/338

Linker

In computer science, a linker or link editor is a program that takes one or


more objects generated by a compiler and combines them into a single
executable program.

On UNIX variants the term loader is often used as a synonym for linker.
Other terminology was in use, too. For example, on SINTRAN III the
process performed by a linker (assembling object files into a program) was
called loading (as in loading executable code onto a file). Because this
usage blurs the distinction between the compile-time process and the runtime process, this article will use linking for the former and loading for the
latter. However, in some operating systems the same program handles both
the jobs of linking and loading a program.

CSE/IT

107/338

Cont

CSE/IT

108/338

Cont

Linkers can take objects from a collection called a library. Some linkers do
not include the whole library in the output; they only include its symbols
that are referenced from other object files or libraries. Libraries exist for
diverse purposes, and one or more system libraries are usually linked in by
default.
The linker also takes care of arranging the objects in a program's address
space. This may involve relocating code that assumes a specific base
address to another base. Since a compiler seldom knows where an object
will reside, it often assumes a fixed base location (for example, zero).
Relocating machine code may involve re-targeting of absolute jumps, loads
and stores

CSE/IT

109/338

Dynamic linking

Many operating system environments allow dynamic linking, that is the


postponing of the resolving of some undefined symbols until a program is
run. That means that the executable code still contains undefined symbols,
plus a list of objects or libraries that will provide definitions for these.
Loading the program will load these objects/libraries as well, and perform
a final linking.

CSE/IT

110/338

Advantages

Often-used libraries (for example the standard system libraries) need to be


stored in only one location, not duplicated in every single binary.
If an error in a library function is corrected by replacing the library, all
programs using it dynamically will benefit from the correction after
restarting them. Programs that included this function by static linking
would have to be re-linked first

CSE/IT

111/338

Disadvantages

Known on the Windows platform as "DLL Hell", an incompatible updated


DLL will break executables that depended on the behavior of the previous
DLL.
A program, together with the libraries it uses, might be certified (e.g. as to
correctness, documentation requirements, or performance) as a package,
but not if components can be replaced. (This also argues against automatic
OS updates in critical systems; in both cases, the OS and libraries form part
of a qualified environment.)

CSE/IT

112/338

Loader

Part of the OS that brings an executable file residing on disk into memory
and starts it running
Steps -:
Read executable files header to determine the size of text and data
segments
Create a new address space for the program
Copies instructions and data into address space
Copies arguments passed to the program on the stack
Initializes the machine registers including the stack ptr
Jumps to a startup routine that copies the programs arguments from the
stack to registers and calls the programs main routine

CSE/IT

113/338

Basic Introduction to Computer


Networks

Data Communication
Modulation
Network devices
LAN, LAN topologies
WAN,
OSI Reference model
TCP/IP Reference model,
Backbone network
Network connecting devices,
HTTP
DNS
Network Security
CSE/IT

114/338

What is data communication

Not to be confused with telecommunication


Any process that permits the passage from a sender to one or more
receivers of information of any nature, delivered in any easy to use
form by any electromagnetic system.
Data communication Defined as a subset of telecommunication involving the transmission
of data to and from computers and components of computer systems.
More specifically data communication is transmitted via mediums
such as wires, coaxial cables, fiber optics, or radiated
electromagnetic waves such as broadcast radio, infrared light,
microwaves, and satellites.

CSE/IT

115/338

History of Data
Communication

Transistor developed by Bell Labs (which is now ???) 1947


Hush-a-Phone Case
Carterphone case
MCI and Long Distance
Creation of networks (LANs and WANs)
Data Link Protocols
Microcomputers

CSE/IT

116/338

Features of Communication

Four things required


Sender, receiver, medium, and message
Types of messages
File
Request
Response
Status
Control
Correspondence
Understandability
Error Detection

CSE/IT

117/338

Cont.

CSE/IT

118/338

Network Applications

The network applications environment consists of several important


components:
Application programs
Operating systems
Data communication systems
Database management systems
The application environment is illustrated in Figure 1-10

CSE/IT

119/338

Other Data Communication


Applications

Batch applications
Data entry applications
Distributed applications
Inquiry/response applications

CSE/IT

Interactive applications
Sensor-based applications
Combined applications

120/338

Introduction to Modulation

Modulation is the process of varying some characteristic of a periodic


wave with an external signals. Modulation is utilized to send an
information bearing signal over long distances.
The characteristics (amplitude, frequency, or phase) of the carrier signal
are varied in accordance with the information bearing signal.
The information bearing signal is also known as the modulating signal. The
modulating signal is a slowly varying signal as opposed to the rapidly
varying carrier frequency.

CSE/IT

121/338

Contd.

CSE/IT

122/338

Encoding
and
Contd.
Modulation Techniques

CSE/IT

123/338

2/45

Cont
Types of Modulation
Amplitude Modulation
Frequency Modulation
Phase Modulation

CSE/IT

124/338

Frequency Modulation
(FM)

In FM, the amplitude of the carrier remains fixed


In FM, frequency changes according to the signal:
when the signal is stronger, the carrier frequency increases slightly,
and when the signal is weaker, the carrier frequency decreases slightly
Figure 10.3 illustrates an example of FM for an info signal
FM is more difficult to visualize
because slight changes in frequency are not as clearly visible
However, one can notice that the modulated wave has higher frequencies
when the signal used for modulation is stronger

CSE/IT

125/338

Frequency Modulation

CSE/IT

126/338

Phase Modulation (PM)

One of the property of a sine wave is its phase, the offset from a reference time
at which the sine wave begins
It is possible to use changes in phase to represent a signal
We use the term phase shift to characterize such changes
If phase changes after cycle k, the next sine wave will start slightly later than
the time at which cycle k completes
A slight delay resembles a change in frequency
PM can be thought of as a special form of frequency modulation
However, phase shifts are important when a digital signal is used to
modulate a carrier

CSE/IT

127/338

Amplitude Modulation And


Shannon's Theorem

shows the amplitude varying from a maximum to almost zero


The figure is slightly misleading:
in practice, modulation only changes the amplitude of a carrier slightly,
depending on a constant known as the modulation index
Practical systems do not allow for a modulated signal to approach zero
Consider Shannon's Theorem
assuming the amount of noise is constant
the signal-to-noise ratio will approach zero as the signal approaches
zero
Keeping the carrier wave near maximum insures that the signal-to-noise ratio
remains as large as possible. This permits the transfer of more bits per second

CSE/IT

128/338

Networking Devices

Networking hardware or networking equipment typically refers to devices


facilitating the use of a computer network. Typically, this includes
gateways, routers, network bridges, switches, hubs, and repeaters.
Devices are Repeater
Hub
Bridge
Router
Gateway

CSE/IT

129/338

Cont

CSE/IT

130/338

Cont

CSE/IT

131/338

Router
ROUTER: a specialized network device that determines the next network point to
which it can forward a data packet towards the destination of the packet. Unlike a
gateway, it cannot interface different protocols. Works on OSI layer 3.

CSE/IT

132/338

Bridge
BRIDGE : a device that connects multiple network segments along the data link layer
Works on OSI layer 2.

CSE/IT

133/338

Hub
HUB : connects multiple Ethernet segments together making them act as a single
segment. When using a hub, every attached device shares the same broadcast domain
and the same collision domain . Therefore, only one computer connected to the hub is
able to transmit at a time. Depending on the network topology, the hub provides a basic
level 1 OSI model connection among the network objects (workstations, servers, etc.).
It provides bandwidth which is shared among all the objects, compared to switches,
which provide a connection between individual nodes. Works on OSI layer 1.

CSE/IT

134/338

Repeater
REPEATER: device to amplify or regenerate digital signals received while sending
them from one part of a network into another. Works on OSI layer 1.

CSE/IT

135/338

LAN (Local Area


Networks)

A LAN is a computer network that covers a small area (home, office,


building, campus)
a few kilometers
LANs have higher data rates (10Mbps to 10Gbps) as compared to WANs
LANs (usually) do not involve leased lines; cabling and equipments belong
to the LAN owner.
A LAN consists of
Shared transmission medium
now so valid today due to switched LANs
regulations for orderly access to the medium
set of hardware and software for the interfacing devices

CSE/IT

136/338

LAN Protocol Architecture

Corresponds to lower two layers of OSI model


But mostly LANs do not follow OSI model
Current LANs are most likely to be based on Ethernet protocols developed
by IEEE 802 committee
IEEE 802 reference model
Logical link control (LLC)
Media access control (MAC)
Physical

CSE/IT

137/338

LAN Topologies

Bus
Ring
Star

CSE/IT

138/338

Bus Topology - 1
Stations attach to linear medium (bus)
Via a tap - allows for transmission
and reception
Transmission propagates in medium in
both directions
Received by all other stations
Not addressed stations ignore
Need to identify target station
Each station has unique address
Destination address included in frame
header
Terminator absorbs frames at the end of
medium
CSE/IT

139/338

Bus Topology - 2

Need to regulate transmission


To avoid collisions
If two stations attempt to transmit at same time, signals will overlap
and become garbage
To avoid continuous transmission from a single station. If one station
transmits continuously, access is blocked for others
Solution: Transmit Data in small blocks frames

CSE/IT

140/338

Ring Topology
Repeaters
joined
by
pointto-point links in closed loop
Links unidirectional
Receive data on one link and
retransmit on another
Stations attach to repeaters
Data transmitted in frames
Frame passes all stations in a
circular manner
Destination recognizes address
and copies frame
Frame circulates back to source
where it is removed
Medium access control is needed to
determine when station can insert
frame
CSE/IT

141/338

Frame Transmission Ring


LAN

CSE/IT

142/338

Star Topology

Each
station
connected
directly to central node
using
a
full-duplex
(bi-directional) link
Central node can broadcast (hub)
Physical star, but logically like
bus since broadcast
Only one station can transmit at
a time
Central node can act as frame
switch
retransmits only to destination
todays technology

CSE/IT

Hub or Switch

143/338

Wide Area Network


(WAN)

A Wide Area Network (WAN) is a telecommunication network that covers


a broad area (i.e., any network that links across metropolitan, regional, or
national boundaries). Business and government entities utilize WANs to
relay data among employees, clients, buyers, and suppliers from various
geographical locations. In essence this mode of telecommunication allows
a business to effectively carry out its daily function regardless of location.

CSE/IT

144/338

Normally WANs are just physical extensions of LANs. They are built
using private leased lines. Their huge coverage area makes the cost go
higher and transmission speeds to drop down.

CSE/IT

145/338

There are two main components when the Wide Area Networks are considered.
1.Switching elements
2.Transmission lines
Let us start with what transmission lines are. Simply put transmission lines is a a
medium to transfers bits of information between the machines in the network.
To connect these transmission lines, we use specialized computers called
switching elements. It performs intelligent switching function. When it receives
an input packet, it decides which output line to forward it to. You should note that
that subnet mentioned here is a little ambiguous. Subnet here and subnetting for
network address is not the same. Here, the term subnet is used as a generic term
for computer components in the WAN.

CSE/IT

146/338

WAN Connection
Types
Leased line a pre-established WAN communications path from the
CPE, through the DCE switch, to the CPE of the remote site, allowing
DTE networks to communicate at any time with no setup procedures
before transmitting data.
Circuit switching uses dial-up modems or ISDN and is used for lowbandwidth data transfers. Think phone call.
Packet switching allows you to share bandwidth with other companies
to save money. Can be thought of as a network thats designed to look like
a leased line, yet costs more like circuit switching.

CSE/IT

147/338

WAN protocols used today:


Frame Relay
ISDN Integrated Services Digital Network
LAPB Link Access Procedure, Balanced
HDLC High-Level Data-Link Control
PPP Point-to-Point Protocol
ATM Asynchronous Transfer Mode

CSE/IT

148/338

The OSI Reference Model

The OSI models is shown on Fig. 1. (minus the physical medium).


This model is based on a proposal developed by the International
Standards Organization (ISO) as a first step toward international
standardization of the protocols used in the various layers.
The model is called the ISO OSI (Open Systems Interconnection)
Reference Model because it deals with connecting open systems that is,
systems that are open for communication with other systems. We will
usually just call it the OSI model for short.

CSE/IT

149/338

The OSI reference model


CSE/IT

150/338

The OSI Reference Model


- Principles
The OSI model has seven layers.
The principles that were applied to arrive at the seven layers are as
follows:
A layer should be created where a different level of abstraction is
needed.
Each layer should perform a well defined function.
The function of each layer should be chosen with an eye toward
defining internationally standardized protocols.
The layer boundaries should be chosen to minimize the information
flow across the interfaces.
The number of layers should be large enough that distinct functions
need not be thrown together in the same layer out of necessity, and
small enough that the architecture dose not become unwieldy.

CSE/IT

151/338

The OSI Reference Model

Note that the OSI model itself is not a network architecture, because it
does not specify the exact services and protocols to be used in each layer.
It just tells what each layer should do.
However, ISO has also produced standards for all the layers, although
these are not part of the reference model itself. Each one has been
published as a separate international standard.
Next, we will discuss each layer of the model in turn, starting at the
bottom layer.

CSE/IT

152/338

OSI The Physical Layer

The physical layer is concerned with transmitting raw bits over a


communication channel. The design issues have to with making sure that
when one side send a 1 bit, it is received by the other side as a 1 bit, not as a
0 bit.
Typical questions here are:
how many volts should be used to represent a 1 and how may for a 0
how many microseconds a bit lasts
whether transmission may proceed simultaneously in both directions
how the initial connection is established and how it is torn down when
both sides are finished
And how many pins the network connector has and what each pin is used
for.
The design issues here largely deal with mechanical, electrical, and
procedural interfaces, and the physical transmission medium, which lies
below the physical layer.
CSE/IT

153/338

OSI The Data Link


Layer

The main task of the data link layer is to take a raw transmission facility
and transform it into a line that appears free of undetected transmission
errors to the network layer.
It accomplishes this task by having the sender break the input data up into
data frames (typically a few hundred or a few thousand bytes), transmit the
frames sequentially, and process the acknowledgment frames sent back by
the receiver.
Since the physical layer merely accepts and transmits a stream of bits
without any regard to meaning or structure, it is up to the data link layer to
create and recognize frame boundaries.
This can be accomplished by attaching special bit patterns to the beginning
and end of the frame. (if these bit patterns accidentally occur in the data,
special care must be taken to make sure these patterns are not incorrectly
interpreted as frame delimiters.)

CSE/IT

154/338

OSI The Data Link


Layer

A noise burst on the line can destroy a frame completely. In this case, the
data link layer software on the source machine can retransmit the frame.
However, multiple transmissions of the same frame introduce the
possibility of duplicate frames. (if the acknowledgment frame from the
receiver back to the sender was lost)
It is up to this layer to solve the problems caused by damaged, lost and
duplicate frames.
Another issue that arises in the data link layer (and most higher layers as
well) is how to keep a fast transmitter from drowning a slow receiver in
data. Some traffic regulation mechanism must be employed to let the
transmitter know how much buffer space the receiver has at the moment.
Frequently, this flow regulation and error handling are integrated.

CSE/IT

155/338

OSI The Network Layer

A key design issue with the network layer is determining how packets are
routed from source to destination.
Routes can be based on static tables that are wired into the network
and rarely changed.
They can also be determined at the start of each conversation, for
example a terminal session.
Finally, the can be highly dynamic, being determined anew for each
packet, to reflect the current network load.
If too many packets are present in the communication line at the same
time, they will get in each others way, forming bottlenecks. The control of
such congestion also belongs to the network layer.
There is often some accounting function built into the network layer. At
the very least, the software must count how many packets or characters or
bits are sent by each customer, to produce billing information. When a
packet crosses a national border, with different rates on each side, the
accounting can become complicated.
CSE/IT

156/338

Cont

When a packet has to travel from one network to another to get to its
destination, many problems can arise:
The addressing used by the second network may be different from the
first one
The second one may not accept the packet at all because it is too large
The protocols may differ, and so on

It is up to the network layer to overcome all these problems to allow


heterogeneous networks to be interconnected.

In broadcast networks, the routing problem is simple, so the network layer


is often thin or even nonexistent.

CSE/IT

157/338

OSI The Transport Layer

The basic function of the transport layer is to accept data from the session
layer, split it up into smaller units if need be, pass these to the network
layer, and ensure that the pieces all arrive correctly at the other end.
Furthermore, all this must be done efficiently, and in a way that isolates
the upper layers from the inevitable changes in the hardware technology.

Under normal conditions, the transport layer creates a distinct network


connection for each transport connection required by the session layer. If
the transport connection requires a high throughput, however the transport
layer might create multiple network connections, dividing the data among
the network connections to improve throughput.

CSE/IT

158/338

Cont

The transport layer also determines what type of service to provide the
session layer, and ultimately, the users of the network:
The most popular type of transport connection is an error-free pointto-point channel that delivers messages or bytes in the order in which
they were sent.
However, other possible kinds of transport service are transport of
isolated messages with no guarantee about the order of delivery, and
broadcasting of messages to multiple destinations.

The type of service is determined when the connection is established.

CSE/IT

159/338

OSI The Transport Layer

The transport layer is a true end-to-end layer, from source to destination. In


other words, a program on the source machine carries on a conversation
with a similar program on the destination machine, using the message
headers and control messages. In the lower layers, the protocols are
between each machine and its immediate neighbors, and not by the
ultimate source and destination machines (which may be separated by
many routers). The difference between layers 1 through 3, which are
chained, and 4 through 7, which are end-to-end, is illustrated in Fig. 4.
In addition to multiplexing several message streams onto one channel, the
transport layer must take care of establishing and deleting connections
across the network. This requires some kind of naming mechanism, so that
a process on one machine has a way of describing with whom it wishes to
converse.
There must also be a mechanism to regulate the flow of information, so
that a fast host cannot overrun a slow one flow control.

CSE/IT

160/338

OSI The Session Layer

The session layer allows users on different machines to establish sessions


between them.
A session allows ordinary data transport, as does the transport layer, but it
also provides enhanced services useful in some applications. A session
might be used to allow a user to log into a remote timesharing system or to
transfer a file between two machines.
One of the services of the session layer is to manage dialogue control.
Session can allow traffic to go in both directions at the same time, or in
only one direction at a time. If traffic goes one way only, the session layer
can help keep track of whose turn it is.
A related session service is token management. For some protocols, it is
essential that both sides do not attempt the same operation at the same
time. To manage these activities tokens are exchanged. Only one side,
holding the token, can perform the critical operation.

CSE/IT

161/338

OSI The Session Layer

Another session service is synchronization.


Consider the problems that might occur when trying to do a 2-hour file
transfer between two machines with 1-hour mean time between
crashes.
After each transfer was aborted, the whole transfer would have to start
over again and would probably fail again the next time as well.

To eliminate this problem, the session layer provides a way to insert


checkpoints into the data stream so that after a crash, only the data
transferred after the last checkpoint have to be repeated.

CSE/IT

162/338

OSI The Presentation


Layer

The presentation layer performs certain functions that are requested


sufficiently often to warrant finding a general solution for them, rather
than letting each user solve the problems.
In particular, unlike all the lower layers, which are just interested in
moving bits reliably from here to there, the presentation layer is concerned
with the syntax and semantics of the information transmitted.
A typical example of a presentation service is encoding data in a standard
agreed upon way. Most user programs do not exchange random binary bit
srings. They exchange thins such as peoples names, dates, amounts of
money, and invoices. These items are represented as character strings,
integers, floating-point numbers, and data structures composed of several
simpler items.

CSE/IT

163/338

OSI The Presentation Layer

In order to make it possible for computers with different representations to


communicate, the data structures to be exchanged can be defined in an
abstract way, along with a standard encoding to be used on the wire.

The presentation layer manages these abstract data structures and converts
from the representation used inside the computer to the network standard
representation and back.

CSE/IT

164/338

OSI The Application


Layer

The application layer contains a variety of protocols that are commonly


needed.
For example, there are hundreds of incompatible terminal types in the
world. Consider a full screen editor that is supposed to work over a
network with many different terminal types (each may have different
screen layouts, keys for inserting ad deleting text, moving the cursor, etc.)
To handle each terminal type, a network virtual terminal can be written.
Next, a piece of software must be written to map the functions of the
virtual network terminal onto the functions of the real terminal.
Another application layer function is file transfer. If two machines have
different files systems for example, the files may have incompatible
naming conventions, ways to represent text lines, etc. Handling these
incompatibilities belongs to the application layer.

CSE/IT

165/338

OSI The Application


Layer

In summary: the application layer makes network services available to


applications (i.e. programs)

It also hides all other layers from programmers, and makes using a
network application transparent to the user

CSE/IT

166/338

Data Transmission in the


OSI Model

CSE/IT

167/338

Data Transmission in the


OSI Model

The sending process has some data it wants to send to the receiving
process.
It gives the data to the application layers, which then attaches the
application header AH to the front of it and gives the resulting item to the
presentation layer.
The presentation layer may transform this item in various ways, and
possibly add a header to the front, giving the result to the session layer. It
is important to note that the presentation layer is not aware which portion
of the item is AH and which is user data.
This process is repeated until the data reach the physical layer, where they
are actually transmitted to the receiving machine.

CSE/IT

168/338

Data Transmission in the


OSI Model

The key idea throughout is that although actual data transmission is


vertical in Fig. 2., each layer is programmed as though it were horizontal.
(each layer thinks it is communicating directly (horizontally) with its peer
on the other machine)

For example, when the sending transport layer gets a message from the
session layer, it attaches a transport header (with information to be used by
the receiving transport layer) and sends it to the receiving transport layer.
From its point of view, the fact that it must actually hand the message to
the network layer on its own machine is an unimportant technicality.

CSE/IT

169/338

The TCP/IP Reference


Model

Let us now turn from the OSI reference model to the reference model used
in the grandparent of all computer networks, the ARPANET, and its
successor, the worldwide Internet.
Although TCP/IP was originally intended for the ARPANET, and currently
used in the Internet, it has become so popular that many local networks
(LANs) are using it as their protocols as well. Thus, we would like to
review this model as well.
The ARPANET was a research network sponsored by the DoD (U.S.
Department of Defense). It eventually connected hundreds of universities
and government installations using leased telephone lines. When satellite
and radio networks were added later, the existing protocols had trouble
internetworking with them, so a new reference architecture was needed.

CSE/IT

170/338

The TCP/IP Reference Model

This architecture later became known as the TCP/IP Reference model,


after its two primary protocols. It was first defined in 1974, and updated
in 1985 and 1988.
Given the DoDs worry that some of its precious hosts, routers, and
internetworking gateways might get blown to pieces at a moments notice,
another major goal was that the network be able to survive loss of subnet
hardware, with existing conversations not being broken off.
In other words, DoD wanted connections to remain intact as long as the
source and destination machines were functioning even if some of the
machines or transmission lines in between were suddenly put out of
operation. Furthermore, a flexible architecture was needed, since
applications with divergent requirements were envisioned, ranging from
transferring files to real-time speech transmission.

CSE/IT

171/338

TCP/IP The Internet Layer

All these requirements lead to the choice of a packet-switching network


based on a connectionless internetwork layer. This layer, called the internet
layer, is the glue that holds the whole architecture together.
Its job is to permit hosts to inject packets into any network and have them
travel independently to the destination (potentially on a different network).
They may even arrive in a different order than they were sent, in which
case it is the job of higher layers to rearrange them, if in-order delivery is
desired.
Note that internet is used here in a generic sense, even though this layer
is present in the Internet.

CSE/IT

172/338

TCP/IP The Internet


Layer

The analogy here is with the mail system. A person can drop a sequence of
international letters into a mail box in one country, and most of them will
be delivered to the correct address in the destination country. Probably the
letters will travel through one or more international mail gateways along
the way, but this is transparent to the users. Furthermore, the letters may
arrive out of order, and each country (i.e. network) has its own stamps,
preferred envelope sizes, and delivery rules, which is also hidden from the
users.
The internet layer defines an official packet format and protocol called IP
(Internet Protocol). The job of the internet layer is to deliver IP packets
where they are supposed to go. Packet routing is clearly the major issue
here, as is avoiding congestion. For these reasons, we can say that the
TCP/IP internet layer is very similar to the OSI network layer. Fig. 3.
shows the correspondence

CSE/IT

173/338

TCP/IP The Internet


Layer
OSI

TCP/IP
Application

Application

Presentation

Session

Transport

Transport

Network

Internet

Data Link

Host-to-network

Physical

CSE/ITmodel
The TCP/IP reference

174/338

TCP/IP The Transport


Layer

The layer above the internet layer in the TCP/IP model is now usually
called the transport layer.
It is designed to allow peer entities on the source and destination hosts
to carry on a conversation, the same as the OSI transport layer.
Two end-to-end protocols have been defined here:
1.
TCP (Transmission Control Protocol) is a reliable connectionoriented protocol that allows a byte stream originating on one
machine to be delivered without errors on any other machine in the
internet. It fragments the incoming byte stream into discrete
messages and passes each one onto the internet layer. At the
destination, the receiving TCP process reassembles the received
messages into the output stream. TCP also handles flow control to
make sure a fast sender cannot swamp a slow receiver with more
messages than it can handle.
CSE/IT

175/338

TCP/IP The Transport


Layer
2.

UDP (User Datagram Protocol) is an unreliable, connectionless


protocol for applications that do not want TCPs sequencing or flow
control and wish to provide their own. It is also widely used for oneshot, client-server type request-reply queries and applications in
which fast delivery is more important than accurate delivery, such as
transmitting speech or video.
The relation of IP, TCP and UDP is shown on Fig. 4. Since this model
was developed, IP has been implemented on many other networks.

CSE/IT

Protocols and networks in the TCP/IP model initially.

176/338

TCP/IP The Application


Layer

The TCP/IP model does not have session or presentation layers. No


need for them was perceived, so they were not included. Experience
with the OSI model has proven this view correct: they are of little use to
most applications.
On top of the transport layer is the application layer. It contains all the
higher-level protocols. The early ones , included:

virtual terminal (TELNET) allows a user on one machine to log


into a distant machine and work there

file transfer (FTP) and provides a way to move data efficiently


from one machine to another

electronic mail (SMTP)

CSE/IT

177/338

TCP/IP The Application


Layer

Many other protocols have been added to these over the years, such as:

the DNS (Domain Name Service) for mapping host names onto
their network addresses

NNTP (Network News Transfer Protocol) for moving news


articles around

HTTP (Hypertext Transfer Protocol) used for fetching pages on


the World Wide Web, and many others

CSE/IT

178/338

A comparison of OSI and


TCP/IP

The OSI and TCP/IP reference models have much in common. Both are
based on the concept of a stack of independent protocols. Also, the
functionality of the layers is roughly similar.
Despite the fundamental similarities, the two models also have many
differences.
Probably the biggest contribution of the OSI model is to make the
distinction between the Services, Interfaces, and Protocols explicit.
These ideas fit very nicely with modern ideas about object-oriented
programming. An object, like a layer, has a set of methods (operations)
that can be invoked outside the object. The semantics of these methods
define the set of services that the object offers.

CSE/IT

179/338

A comparison of OSI and


TCP/IP

The OSI reference model was devised before the protocols were
invented.

With the TCP/IP the reverse is true: the protocols came first, and the
model was really just a description of the existing protocols. There was
no problem with the protocols fitting the model: they fit perfectly. The
only trouble was that the model did not fit any other protocol stacks.

CSE/IT

180/338

A comparison of OSI and


TCP/IP
In summary:

despite its problems, the OSI model (minus the session and presentation
layers) has proven to be exceptionally useful for discussing computer
networks. In contrast, the OSI protocols have not become popular.

The opposite is true for TCP/IP: the model is practically nonexistent,


but the protocols are widely used.

Therefore, we would like to think of a modified OSI model and


concentrate on the TCP/IP and related protocols and use a hybrid
model, shown on Fig, as a framework.

CSE/IT

181/338

HTTP vs HTML

HTML: hypertext markup language


Definitions of tags that are added to Web documents to control their
appearance
HTTP: hypertext transfer protocol
The rules governing the conversation between a Web client and a Web
server

CSE/IT

182/338

What is a protocol?

In diplomatic circles, a protocol is the set of rules governing a conversation


between people

We have seen that the client and server carry on a machine-to-machine


conversation

A network protocol is the set of rules governing a conversation between a


client and a server

There are many protocols, HTTP is just one

CSE/IT

183/338

An HTTP
conversation
Client

Server

I would like to open


a connection

OK

GET <file location>


Send page or error message

Display response
Close connection

OK

CSE/IT

184/338

An HTTP Example
The message requesting a Web page must begin with the work GET and be
followed by a space and the location of a file on the server, like this:

GET /fac/lpress/shortbio.htm

The protocol spells out the exact message format, so any Web client can
retrieve pages from any Web server.

CSE/IT

185/338

Network protocols

The details are only important to developers.


The rules are defined by the inventor of the protocol may be a group or a
single person.
The rules must be precise and complete so programmers can write
programs that work with other programs.
The rules are often published as an RFC along with running client and
server programs.
The HTTP protocol used for Web applications was invented by Tim
Berners Lee.

CSE/IT

186/338

Concept: DNS Names 1

The namespace needs to be made hierarchical to be able to scale.


The idea is to name objects based on
location (within country, set of organizations, set of companies, etc)
unit within that location (company within set of company, etc)
object within unit (name of person in company)

CSE/IT

187/338

How names appear in the


DNS
Fully Qualified Domain Name (FQDN)
WWW.RIPE.NET.
labels separated by dots

DNS provides a mapping from FQDNs to resources of several types

Names are used as a key when fetching data in the DNS

CSE/IT

188/338

Concept: Resource
Records
The DNS maps names into data using Resource Records.

Resource Record
www.ripe.net.

A 10.10.10.2

More detail later

Address Resource

CSE/IT

189/338

Concept: DNS Names 3

ws1 ws2
ftp

www disi

Domain names can be mapped to a tree.

www

New branches at the dots

No restriction to the amount of


sun

branches.
ripe isi
tislabs
moon

google
net educom

CSE/IT

190/338

Concept: Domains

Domains are namespaces


Everything below .com is in the com domain.
Everything below ripe.net is in the ripe.net domain and in the net domain.

com doma

net edu com

ripe

disi
www
ftp

net domain

ws2

CSE/IT

ripe.net domain

google
isi sun tislabs
moon
www
ws1

191/338

What is Security

Dictionary.com says:
1. Freedom from risk or danger; safety.
2. Freedom from doubt, anxiety, or fear; confidence.
3. Something that gives or assures safety, as:
1. A group or department of private guards: Call building security
if a visitor acts suspicious.
2. Measures adopted by a government to prevent espionage,
sabotage, or attack.
3. Measures adopted, as by a business or homeowner, to prevent a
crime such as burglary or assault: Security was lax at the firm's
smaller plant.
etc.

CSE/IT

192/338

Why do we need security?

Protect vital information while still allowing access to those who need it
Trade secrets, medical records, etc.
Provide authentication and access control for resources
Ex: AFS
Guarantee availability of resources
Ex: 5 9s (99.999% reliability)

CSE/IT

193/338

Cont

Financial institutions and banks


Internet service providers
Pharmaceutical companies
Government and defense agencies
Contractors to various government agencies
Multinational corporations

CSE/IT

194/338

Common security attacks

Finding a way into the network


Firewalls
Exploiting software bugs, buffer overflows
Intrusion Detection Systems
Denial of Service
Ingress filtering, IDS
TCP hijacking
IPSec
Packet sniffing
Encryption (SSH, SSL, HTTPS)
Social problems
Education

CSE/IT

195/338

Section -C

CSE/IT

196/338

Overview of C
C is developed by Dennis Ritchie
C is a structured programming language
C supports functions that enables easy maintainability
of code, by breaking large file into smaller modules
Comments in C provides easy readability
C is a powerful language

CSE/IT

197/338

Program structure
A sample C Program
#include<stdio.h>
int main()
{
--other statements
}

CSE/IT

198/338

Header files
The files that are specified in the include section is
called as header file
These are precompiled files that has some functions
defined in them
We can call those functions in our program by
supplying parameters
Header file is given an extension .h
C Source file is given an extension .c
CSE/IT

199/338

Main function
This is the entry point of a program
When a file is executed, the start point is the main
function
From main function the flow goes as per the
programmers choice.
There may or may not be other functions written by
user in a program
Main function is compulsory for any c program

CSE/IT

200/338

Writing the first program


#include<stdio.h>
int main()
{
printf(Hello);
return 0;
}
This program prints Hello on the screen when we
execute it
CSE/IT

201/338

Running a C Program
Type a program
Save it
Compile the program This will generate an exe file
(executable)
Run the program (Actually the exe created out of
compilation will run and not the .c file)
In different compiler we have different option for
compiling and running. We give only the concepts.
CSE/IT

202/338

Comments in C
Single line comment
// (double slash)
Termination of comment is by pressing enter key
Multi line comment
/*.
.*/
This can span over to multiple lines

CSE/IT

203/338

Data types in C
Primitive data types
int, float, double, char

Aggregate data types


Arrays come under this category
Arrays can contain collection of int or float or char
or double data

User defined data types


Structures and enum fall under this category.
CSE/IT

204/338

Variables
Variables are data that will keep on changing
Declaration
<<Data type>> <<variable name>>;
int a;
Definition
<<varname>>=<<value>>;
a=10;
Usage
<<varname>>
a=a+1; //increments the value of a by 1
CSE/IT

205/338

Variable names- Rules

Should not be a reserved word like int etc..


Should start with a letter or an underscore(_)
Can contain letters, numbers or underscore.
No other special characters are allowed
including space
Variable names are case sensitive
A and a are different.

CSE/IT

206/338

Input and Output


Input
scanf(%d,&a);
Gets an integer value from the user and stores it
under the name a
Output
printf(%d,a)
Prints the value present in variable a on the screen

CSE/IT

207/338

For loops
The syntax of for loop is
for(initialisation;condition checking;increment)
{
set of statements
}
Eg: Program to print Hello 10 times
for(I=0;I<10;I++)
{
printf(Hello);
}
CSE/IT

208/338

While loop
The syntax for while loop
while(condn)
{
statements;
}
Eg:
a=10;
while(a != 0) Output: 10987654321
{
printf(%d,a);
a--;
}
CSE/IT

209/338

Do While loop
The syntax of do while loop
do
{
set of statements
}while(condn);
Eg:
i=10;
Output:
do 10987654321
{
printf(%d,i);
i--;
}while(i!=0)
CSE/IT

210/338

Conditional statements
if (condition)
{
stmt 1;
}
else
{
stmt 2;
}

//Executes if Condition is true

//Executes if condition is false

CSE/IT

211/338

Conditional statement
switch(var)
{
case 1: //if var=1 this case executes
stmt;
break;
case 2: //if var=2 this case executes
stmt;
break;
default:
//if var is something else this will execute
stmt;
}
CSE/IT

212/338

Operators

Arithmetic (+,-,*,/,%)
Relational (<,>,<=,>=,==,!=)
Logical (&&,||,!)
Bitwise (&,|)
Assignment (=)
Compound assignment(+=,*=,-=,/=,%=,&=,|=)
Shift (right shift >>, left shift <<)

CSE/IT

213/338

String functions

strlen(str) To find length of string str


strrev(str) Reverses the string str as rts
strcat(str1,str2) Appends str2 to str1 and returns str1
strcpy(st1,st2) copies the content of st2 to st1
strcmp(s1,s2) Compares the two string s1 and s2
strcmpi(s1,s2) Case insensitive comparison of
strings

CSE/IT

214/338

Numeric functions

pow(n,x) evaluates n^x


ceil(1.3) Returns 2
floor(1.3) Returns 1
abs(num) Returns absolute value
log(x) - Logarithmic value
sin(x)
cos(x)
tan(x)

CSE/IT

215/338

Procedures
Procedure is a function whose return type is void
Functions will have return types int, char, double,
float or even structs and arrays
Return type is the data type of the value that is
returned to the calling point after the called function
execution completes

CSE/IT

216/338

Functions and
Parameters
Syntax of function
Declaration section
<<Returntype>> funname(parameter list);
Definition section
<<Returntype>> funname(parameter list)
{
body of the function
}
Function Call
Funname(parameter);
CSE/IT

217/338

Example function
#include<stdio.h>
void fun(int a);
int main()
{
fun(10);
}
void fun(int x)
{
printf(%d,x);
}

//declaration

//Call
//definition

CSE/IT

218/338

Actual and Formal


parameters
Actual parameters are those that are used during a
function call
Formal parameters are those that are used in function
definition and function declaration

CSE/IT

219/338

Arrays
Arrays fall under aggregate data type
Aggregate More than 1
Arrays are collection of data that belong to same data
type
Arrays are collection of homogeneous data
Array elements can be accessed by its position in the
array called as index

CSE/IT

220/338

Arrays
Array index starts with zero
The last index in an array is num 1 where num is
the no of elements in a array
int a[5] is an array that stores 5 integers
a[0] is the first element where as a[4] is the fifth
element

CSE/IT

221/338

Multidimensional Arrays
We can also have arrays with more than one
dimension
float a[5][5] is a two dimensional array. It can store
5x5 = 25 floating point numbers
The bounds are a[0][0] to a[4][4]

CSE/IT

222/338

Structures
Structures are user defined data types
It is a collection of heterogeneous data
It can have integer, float, double or character data in it
We can also have array of structures
struct <<structname>>
{
members;
}element;
We can access element.members;
CSE/IT

223/338

Structures
Collections of related variables (aggregates) under
one name
Can contain variables of different data types
Commonly used to define records to be stored in
files
Combined with pointers, can create linked lists,
stacks, queues, and trees

CSE/IT

224/338

Structure Definitions
Example
struct card {
char *face;
char *suit;
};

struct introduces the definition for structure card


card is the structure name and is used to declare
variables of the structure type
card contains two members of type char *
These members are face and suit
CSE/IT

225/338

Structure Definitions
struct information
A struct cannot contain an instance of itself
Can contain a member that is a pointer to the same
structure type
A structure definition does not reserve space in
memory
Instead creates a new data type used to declare
structure variables

CSE/IT

226/338

Continued..
Declarations
Declared like other variables:
card oneCard, deck[ 52 ], *cPtr;
Can use a comma separated list:
struct card {
char *face;
char *suit;
} oneCard, deck[ 52 ], *cPtr;
CSE/IT

227/338

Structure Definitions
Valid Operations
Assigning a structure to a structure of the same
type
Taking the address (&) of a structure
Accessing the members of a structure
Using the sizeof operator to determine the size
of a structure

CSE/IT

228/338

Initializing Structures
Initializer lists
Example:card oneCard = { "Three", "Hearts" };
Assignment statements
Example: card threeHearts = oneCard;
Could also declare and initialize threeHearts as
follows:
card threeHearts;
threeHearts.face = Three;
threeHearts.suit = Hearts;
CSE/IT

229/338

Accessing Members of
Structures
Accessing structure members
Dot operator (.) used with structure variables
card myCard;
printf( "%s", myCard.suit );
Arrow operator (->) used with pointers to structure
variables
card *myCardPtr = &myCard;
printf( "%s", myCardPtr->suit );
myCardPtr->suit is equivalent to
( *myCardPtr ).suit
CSE/IT

230/338

Using Structures With


Functions
Passing structures to functions
Pass entire structure
Or, pass individual members
Both pass call by value
To pass structures call-by-reference
Pass its address
Pass reference to it
To pass arrays call-by-value
Create a structure with the array as a member
Pass the structure
CSE/IT

231/338

Arrays of Structure
Since structures are data types that are especially useful for
creating collection items, make a collection of them using an
array. Let us now take an example to use an array of structures
rather than individual ones.\
object2.c:
#include <stdio.h>
#include <stdlib.h>
struct object {
char id[20];
int xpos;
int ypos;
};
CSE/IT

232/338

Continue
struct object createobj(char id[], int xpos, int ypos);
void printobj(struct object obj);
void main() {
int i;
struct object gameobjs[2];
gameobjs[0] = createobj("player1", 0, 0);
gameobjs[1] = createobj("enemy1", 2, 3)
for (i = 0; i < 2; i++)
printobj(gameobjs[i]);
//update enemy1 position
gameobjs[1].xpos = 1;
gameobjs[1].ypos = 2;
CSE/IT

233/338

Continue
for (i = 0; i < 2; i++)
printobj(gameobjs[i]);
}
struct object createobj(char id[], int xpos, int ypos) {
struct object newobj;
strcpy(newobj.id, id);
newobj.xpos = xpos;
newobj.ypos = ypos;
return newobj;
}

CSE/IT

234/338

Continue
void printobj(struct object obj) {
printf("name: %s, ", obj.id);
printf("x position: %d, ", obj.xpos);
printf("y position: %d", obj.ypos);
printf("\n");
}

We create an array of structures called gamobjs and use


the createobj function to initilize it's elements. An
update for the enemy1's position to show how to access
a structure's members when it is an element within an
array.
CSE/IT

235/338

Structure within a
Structure
Structures may even have structures as members.
Imagine (x, y) coordinate pair is a structure called
coordinates. Redeclare the object structure as follows:
struct object {
char id[20];
struct coordinates loc;
};
Initialize these by using nested braces :
struct object player1 = {player1, {0, 0}};
CSE/IT

236/338

Continue
To access or set members of the above internal structure do like
this:
struct object player1;
player1.id = player1;
player1.loc.xpos = 0;
player1.loc.ypos = 0;

CSE/IT

237/338

Type def
typedef
Creates synonyms (aliases) for previously defined
data types
Use typedef to create shorter type names
Example:
typedef struct Card *CardPtr;

Defines a new type name CardPtr as a synonym


for type struct Card *
typedef does not create a new data type
CSE/IT

238/338

Type def
The typedef operator is used for creating alias of a
data type
For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
CSE/IT

239/338

Unions
Unions and Structures are identical in all ways,
except for one very important aspect. Only one
element in the union may have a value set at any
given time.
Unions are mainly used to conserve memory. While
each member within a structure is assigned its own
unique storage area, the members that compose a
union share the common storage area within the
memory.
Unions are useful for application involving multiple
members where values are not assigned to all the
members at any one time.
CSE/IT

240/338

Continue..
Let us modify structure object from above so that it has
a union for indicating dead or alive in it:
struct object {
char id[20];
struct coordinates loc;
union deadoralive {
int alive;
int dead;
}
};
CSE/IT

241/338

Section -D

CSE/IT

242/338

Pointers
Pointer is a special variable that stores address of
another variable
Addresses are integers. Hence pointer stores integer
data
Size of pointer = size of int
Pointer that stores address of integer variable is called
as integer pointer and is declared as int *ip;

CSE/IT

243/338

Pointers
Pointers that store address of a double, char and float
are called as double pointer, character pointer and
float pointer respectively.
char *cp
float *fp
double *dp;
Assigning value to a pointer
int *ip = &a; //a is an int already declared

CSE/IT

244/338

Examples
int a;
a=10;
int *ip;
ip = &a;

//a stores 10
//ip stores address of a (say 1000)

ip :
fetches 1000
*ip :
fetches 10
* Is called as dereferencing operator
CSE/IT

245/338

Call by Value
Calling a function with parameters passed as values
int a=10;
fun(a);

void fun(int a)
{
defn;
}
Here fun(a) is a call by value.
Any modification done with in the function is local to it
and will not be effected outside the function
CSE/IT

246/338

Call by reference
Calling a function by passing pointers as parameters
(address of variables is passed instead of variables)
int a=1;
fun(&a);

void fun(int *x)


{
defn;
}
Any modification done to variable a will effect outside
the function also
CSE/IT

247/338

Example program Call


by value
#include<stdio.h>
void main()
{
int a=10;
printf(%d,a);
fun(a);
printf(%d,a);
}
void fun(int x)
{
printf(%d,x)
x++;
printf(%d,x);
}

a=10
a=10

x=10
x=11

CSE/IT

248/338

Explanation

CSE/IT

249/338

Example Program Call by


reference
#include<stdio.h>
void main()
{
int a=10;
printf(%d,a);
fun(a);
printf(%d,a);
}
void fun(int x)
{
printf(%d,x)
x++;
printf(%d,x);
}

a=10
a=11

x=10
x=11

CSE/IT

250/338

Explanation

a and x are referring to same location. So value will be over written.


CSE/IT

251/338

Conclusion
Call by value => copying value of variable in another
variable. So any change made in the copy will not
affect the original location.
Call by reference => Creating link for the parameter
to the original location. Since the address is same,
changes to the parameter will refer to original
location and the value will be over written.

CSE/IT

252/338

Storage Management and File allocation


in C

CSE/IT

253/338

Outline
Memory management
Dynamic memory allocation
Functions: malloc, calloc, realloc

De-allocating memory
Functions: free

CSE/IT

254/338

Dynamic memory
allocation in C
Stack-allocated memory
When a function is called, memory is allocated for
all of its parameters and local variables.
Each active function call has memory on the stack
(with the current function call on top)
When a function call terminates,

the memory is deallocated (freed up)


Ex:
main() calls f(),
f() calls g()
g() recursively calls g()
CSE/IT

255/338

Dynamic memory
allocation in C
Heap-allocated memory
This is used for persistent data, that must survive
beyond the lifetime of a function call
global variables
dynamically allocated memory C statements can
create new heap data (similar to new in Java/C++)
Heap memory is allocated in a more complex way than
stack memory
Like stack-allocated memory, the underlying system
determines where to get more memory the
programmer doesnt have to search for free memory
space!
CSE/IT

256/338

Dynamic Memory
Two different ways to look at memory
allocation:
Transparent to user
Done by the compiler as well as the OS.

User-defined
Memory allocated by the user.

CSE/IT

257/338

Dynamic Memory
(contd.)
Why allocate memory ??
Required by program for permanent variables.
Compiler arranges for memory at compiler
time.
OS + program allocate memory at run time.
Memory exists for life of program.

CSE/IT

258/338

Dynamic Memory
(contd.)
Why allocate memory ??
Reserve working space for program.
Working space is space required for execution
of program instructions (e.g: arithmetic, logical
operations).
Normally maintained using a stack or a heap.

CSE/IT

259/338

Dynamic Memory
(contd.)
Stacks and heaps:
Data structures with specific purposes.
A stack is an organized data structure, which
follows the LIFO (Last In First Out)
principle.
A data item which enters the stack last is the first
to be taken out.

A heap is just a collection in memory that is


manipulated as the user/system chooses.
CSE/IT

260/338

HEAP Manipulation
1

After removal

CSE/IT

261/338

STACK Manipulation
5
4

After removal

1
CSE/IT

262/338

Dynamic Memory
(contd.)
Why do we need dynamic allocation ?????
There are times when we dont know how much
memory is required.
Employee data base that sorts employee records
and adds new employees.
Program accepting command line input defining
size of matrices.
Directory trees where files/folders can be
added/deleted.
CSE/IT

263/338

Dynamic Memory
(contd.)
Programmer arranges to allocate appropriate amount
of memory.
Reads command line arguments.
Processes input flag to add new record to database.

CSE/IT

264/338

Dynamic Memory
(contd.)
E.g:
char response;
printf (Add a new record y/n ?);
scanf (%c, &response);
if (response == y || response == Y)
{allocate required memory}

CSE/IT

265/338

Dynamic Memory
(contd.)
Also used by the OS !!!
Heap is managed dynamically through the use of
dynamic memory.
Used mostly to calculate the values of expressions,
assign memory blocks etc.
Stacks are also managed dynamically.
Used mostly for function calls, scope of variables
etc.
CSE/IT

266/338

Dynamic Memory
(contd.)
Functions available to allocate memory:
void *malloc (size_t size)
Returns a void pointer to a contiguous block in
memory of size equal to size bytes.
** Size is always taken to be in bytes.

CSE/IT

267/338

Dynamic Memory
(contd.)
E.g: x = malloc (10);
If successful, returns address of the block of 10
bytes in memory.
x points to the beginning of this block of mem.

Size of memory block is 10 bytes.


CSE/IT

268/338

Allocating a block of
memory :malloc
On success returns pointer (address of beginning of
block of memory just created).
On error, returns NULL (keyword in C).
Errors:
Insufficient block size.
size = 0.

CSE/IT

269/338

malloc (contd.)
Memory is allocated from the heap.
Allocated space is not initialized, so contains
garbage.
No connection exists with type of data to be stored in
the memory space just created.
Contained in the header file: stdlib.h or alloc.h

CSE/IT

270/338

malloc (contd.)
Why is a void pointer returned ???
malloc just allocates memory which consists of
some number of bytes.
Memory as such has no data type, unless the user
or the running program chooses to associate a data
type with the block of memory just created.

CSE/IT

271/338

malloc (contd.)
How to assign a data type to the memory just
created ???
Use type casting.
Once type cast to a data type, memory takes on the
meaning of that data type.
Amount of data types that can be represented
depends on the size of the data type.

CSE/IT

272/338

malloc (contd.)
E.g:
double *x; // x is a pointer to double as malloc
returns an address.
x = (double *) malloc (100); // type casting the
memory to be of type pointer to double.
No. of doubles = 100/8 = 12 !!!
We can clearly see a pit fall of malloc out here.

CSE/IT

273/338

malloc (contd.)
More E.gs:
double *x;
x = (double *) malloc (100 * sizeof (double));
This is the correct declaration, gives us 800 bytes
in memory, where we have 100 doubles.
Always better to use sizeof instead of the
following:
x = (double *)malloc (100 * 8); // assume that double is
8 bytes

CSE/IT

274/338

Dynamic Memory
Other memory allocation functions:
void *calloc (size_t count, size_t size)
Same as malloc, but is contained in stdlib.h
Allocated space is automatically initialized to
zero.
Still have to cast void pointer to correct type.

CSE/IT

275/338

Allocating multiple
blocks of memory :calloc
Advantages over malloc:
Allocated memory is automatically initialized.
The semantics of size and count are separated,
making it easier for the user during declaration.
Less prone to making errors while declaration
for the correct amount of size and/or count
required.

CSE/IT

276/338

calloc (contd.)
E.g:
int *x;
x = (int *) calloc (10, sizeof (int));
Gives us a block of 10 integers in memory.
char *x;
x = (char *) calloc (10, sizeof (char));
Gives us a block of 10 characters in memory.
CSE/IT

277/338

malloc and calloc


We can also assign space for structures.
E.g:
struct test {
int x;
int y;
};
struct test *x;
x = (struct test *) calloc (10, sizeof (struct test));
CSE/IT

278/338

Dynamic Memory
More functions:
void *realloc (void *blk, size_t newsize)
blk is pointer to previously allocated block of
memory using either malloc or calloc.
Attempts to reallocate the block of memory.
Resizes the memory to newsize (can be greater or
smaller than previously designated size).

CSE/IT

279/338

Altering the size of


block: Realloc
There are times, when after assigning memory, we
find that we have assigned more/less than what we
require.
realloc to the rescue.
On success returns pointer to new location.
On success, copies data from old location to new
location.
On error returns NULL.

CSE/IT

280/338

realloc (contd.)
Pit falls:
size = 0 frees memory block and returns NULL.
Once memory is re-allocated, the old location in
memory is invalid.
Both memory locations (new and old), are the
same now (= new).
Example follows.

CSE/IT

281/338

realloc (contd.)
E.g:
# include <stdio.h>
int main ()
{
int *x, *y;
x = (int *) malloc (1 * sizeof (int));
*x = 1; // value of *x is 1 here.
y = (int *) realloc (x, 1);
*y = 10; // value of *x and *y are same = 10 !!!
printf ("%d\n", *y);
printf ("%d\n", *x);
}
CSE/IT

282/338

realloc (contd.)

malloc
realloc

realloc
y

malloc
CSE/IT

283/338

Dynamic Memory
Memory that is allocated can also be freed to the
heap.
Only dynamically allocated memory can be freed.
E.g:
int x; // memory for x is statically assigned here,
hence it cannot be freed.

CSE/IT

284/338

Dynamic Memory
(contd.)
When finished using dynamically allocated memory,
free it.
Good practice to avoid memory leaks.
Growing loss of memory due to unreleased
locations.
Could prevent program from running properly,
due to lack of memory.
Can run out of memory.
CSE/IT

285/338

Dynamic Memory
(contd.)
Function to free memory:
void free (void *blk)
De-allocates memory block previously allocated
with malloc, calloc or realloc.
blk is pointer to existing memory block already
allocated.

CSE/IT

286/338

Releasing the used space:


Free()
E.g:
char *x;
x = (char *) malloc (10 * sizeof (char));
free (x); // frees the memory just assigned.

CSE/IT

287/338

free
No return value.
Available in the header file stdlib.h
Never free a memory block that is not dynamically
allocated.
E.g:
int *x;
free (x); // error

CSE/IT

288/338

free (contd.)
Once block has been freed, do not attempt to access
it.
E.g:
char *x;
x = (char *) malloc (10 * sizeof (char));
free (x);
strcpy (x, welcome); // error as memory has
already been freed.
CSE/IT

289/338

free (contd.)
Free memory only when you are sure of not using it
again elsewhere in the program.
Cannot free memory already freed.
E.g:
char *x = (char *) malloc (10 * sizeof (char));
free (x);
free (x); // ERROR

CSE/IT

290/338

Pit falls
Memory is being manipulated directly, so any error
will stop your program.
Free memory at the end of the program.
Use realloc as little as possible.
As once realloc is executed, new location and
old location map to the same address in memory
char *x = (char *) malloc (10 * sizeof (char));
char *y = realloc (x, 15);
free (x); // y is also freed as x y.

CSE/IT

291/338

Pit falls
Dangling pointer:
E.g:
char *x, *y;
x = (char *) malloc (10 * sizeof (int));
y = (char *) malloc (10 * sizeof (int));
x = y; // cannot access what was in x anymore, so that block
is always lying around in memory with no way to free it
until program terminates.
CSE/IT

292/338

Files in C
A file must first be opened properly before it can be
accessed for reading or writing. When a file is
opened, a pointer is associated with the file.
Successfully opening a file returns a pointer to (i.e.,
the address of) a file structure, which contains a file
descriptor and a file control block.

CSE/IT

293/338

Why files?
Scanf and Printf are the built-in files used for
console-oriented operations i.e., giving I/P from
keyboard and getting O/P on the screen.
Files are used to store data in a manner that can later
be retrieved and displayed especially in large
volumes.
Files are used to store the information permanently
and to access information whenever necessary.
Files are stored in the Secondary Storage Devices like
Floppy Disks, Hard Disks.
CSE/IT

294/338

Data Organization
Memory
Our
Program

C Library
Functions

OS
Input and
DISK
Output
for File
Oriented
Operation
s For large

volumes of data

CSE/IT

295/338

Types of Files
Text File
Binary File

CSE/IT

296/338

Text File
Stores textual information like alphabets, numbers,
special symbols .etc.,
Ex: A-Z, a-z, 1,2,3etc., : , ; , , , ? etc.
Represented as C source code files with .txt
extension.
Text File operations include the above mentioned
six operations which are performed with the help of
C built-in functions.

CSE/IT

297/338

Binary File
Any files which store the data in the form of bytes
is a binary file.
Every executable file generated by the C compiler is
a binary file.
Ex: .exe files, video stream files, image files
etc.
Reading from a file, Writing to a file, Appending
files etc are also a part of binary file operations
done with the help of built-in functions.
CSE/IT

298/338

File Operations
1.
2.
3.
4.
5.
6.

Creation of a new file


Opening an existing file
Reading from a file
Writing to a file
Moving to a specific location in a file (seeking)
Closing a file

CSE/IT

299/338

Defining and Opening a


File
For data to be stored in secondary memory, the OS
should be specified with:
File Name : A string of characters that make up a valid
name for the OS
Eg: input.dat,store,PROG.c,Text.out etc.
Data structure: A Data Structure of a file is defined as
FILE in the library of standard I/O definitions. All files
should be declared as type FILE before they are used.
FILE is a defined data type.
CSE/IT

300/338

Creation of a new file


The statement
FILE *fp;
fp=fopen(filename,mode)
;
declares that fp is a pointer variable of type FILE. They
will be assigned the address of a file descriptor, that is,
an area of memory that will be associated with an input
or output stream.
CSE/IT

301/338

Examples:
FILE *fp1,*fp2;
fp1=fopen(data,r);
fp2=fopen(results,w);
File data is opened for reading only.
File results are opened for writing only.
r+, w+, a+ are also included in the latest compilers.
CSE/IT

302/338

List of Functions
Functions

Operation

fopen()

Creates a new file for use,


opens an existing file for use.

fclose()

Closes a file which has been


opened for use

fgetc()

Reads a character from file

fputc()

Writes a character to a file

fprintf()

Writes a record to the file.


CSE/IT

303/338

List of Functions
(Continued..)
Functions

Operation

fscanf()

Reads a record from a file

fgetw()

Reads an integer from a file

fputw()

Writes an integer to a file

fseek()

Sets the position to a desired


point in the file

CSE/IT

304/338

Testing for Successful


Open
If the file was not opened, then the value returned by the
fopen function will be always NULL.
For example, let's assume that the file mydata does not
exist.
FILE *fp ;
fp = fopen ( "mydata", "r") ;
if (fp == NULL)
printf ("File 'mydata' does not exist.\n") ;
CSE/IT

305/338

Closing a file
Prevents accidental misuse of the file.
fclose (file_pointer);
Ex:
FILE *fp1;

.
fclose (fp1);
CSE/IT

306/338

Input/output operations
on files
getc and putc functions
getw and putw functions
printf and fscanf functions

CSE/IT

307/338

getc and putc functions


Same as getchar & putchar functions
c = getc(fp1);

Used to read a character from


a file that has been opened in
read mode.

Reading terminates when end of file has been


reached.
putc(c, fp2);

Used to write character contained


in char variable c to the file with
pointer fp2.
CSE/IT

308/338

Program
Read data from keyboard, write it to a file called
INPUT, again read the same data from the INPUT
file and display it on the screen.
CODE:
main ()
{
FILE *fp1;
char c;
printf("Data Input\n\n");
fp1 = fopen("INPUT","w");
CSE/IT

309/338

Continue..
while((c=getchar())!=EOF)
putc(c,fp1);
fclose(fp1);
printf("\nData Output\n\n");
fp1=fopen("INPUT","r");
while((c=getc(fp1)) !=EOF)
printf("%c",c);
fclose(fp1);
system("PAUSE");
}
CSE/IT

310/338

getw and putw functions


Integer-oriented functions.
Used to read and write integer values.
Useful when we deal with only integer data.
putw (integer, fp);
getw (fp);

CSE/IT

311/338

Program
Read integers from keyboard and write the same
into file data and display the same on keyboard.
Code:
main ()
{
FILE *fp1;
int i,num;
printf("Contents of data file\n\n");
fp1 = fopen("data","w");
CSE/IT

312/338

Continue..
for(i=0;i<=20;i++)
{
scanf("%d",&num);
putw(num,fp1);
}
fclose(fp1);
fp1 = fopen("data","r");
while((num=getw(fp1))!=EOF)
printf("\n%d",num);
fclose(fp1);
system("PAUSE");
}
CSE/IT

313/338

fprintf and fscanf


functions
Previous functions can handle only one character or integer
at a time.
Can handle group of mixed data simultaneously.
Similar to printf and scanf functions.
fprintf(fp, control string, list);
Ex:
fprintf(fp1, %s %d %f, name, age, 7.5);

CSE/IT

314/338

Input/output operations
on files
fscanf :
Reads items in the list from the file with pointer fp.
Returns the number of items that are successfully read.
When the end of file is reached, it returns the value EOF.
fscanf(fp, control string, list);
Ex: fscanf(fp2, %s %d, item, &quantity);

CSE/IT

315/338

Reading From Files


In the following segment of C language code:
int a, b ;
FILE *fptr1, *fptr2 ;
fptr1 = fopen ( "mydata", "r" ) ;
fscanf ( fptr1, "%d%d", &a, &b) ;
the fscanf function would read values from the file
"pointed" to by fptr1 and assign those values to a
and b.
CSE/IT

316/338

Error handling during I/O


operations
Typical error situations:
1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, when the file
is opened for another type of operation.
5. Opening a file with an invalid file name.
6. Attempting to write to a write-protected file.
CSE/IT

317/338

Error handling during I/O


operations
Unchecked errors => premature termination of the
program or incorrect output.
Two status-inquiry library functions that help us to
detect I/O errors in the files
1. feof
2. ferror

CSE/IT

318/338

feof function
Can be used to test for an end of file condition.
Takes file pointer as its only argument
Returns a nonzero integer value if all of the data from
the specified file has been read.
Returns zero otherwise.

CSE/IT

319/338

feof function
if(feof(fp))
printf(End of data.\n);
Would display the message on reaching the end of file
condition (File opened for reading).

CSE/IT

320/338

ferror function
Reports the status of the file indicated.
Takes file pointer as its argument.
Returns non zero integer if an error has been
detected up to that point, during processing.
Otherwise returns zero.

CSE/IT

321/338

ferror function

if(ferror(fp) !=0)
printf(An error has occured.\n);
Would display the error message if reading is not
successful.

CSE/IT

322/338

Program
Program to illustrate error handling functions:
Code:
main()
{
char *filename;
FILE *fp1,*fp2;
int i,num;
fp1 = fopen("TEST","w");
for(i=0;i<=100;i+=10)
putw(i,fp1);
fclose(fp1);
CSE/IT

323/338

Continue..
fp1 = fopen("TEST","r");
for(i=1;i<=10;i++){
num=getw(fp1);
if(feof(fp1)) {
printf("\nRan out of data.\n");
break; }
else
printf("%d\n",num);
}
fclose(fp1);
system(PAUSE);
}
CSE/IT

324/338

Random access to files


Functions that help in accessing only a particular part
of the file:
(not reading & writing sequentially).
ftell
fseek
rewind

CSE/IT

325/338

Random access to files


ftell :
Takes a file pointer.
Returns a number of type long, that corresponds to
the current position.
Useful in saving the current position of a file,
which can be used later in the program.

CSE/IT

326/338

Random access to files


n = ftell (fp);
n would give the relative offset (in bytes) of the
current position
i.e., n bytes have already been read (or written).

CSE/IT

327/338

Random access to files


rewind:
Takes a file pointer and resets the position to the
start of the file.
Ex:
rewind (fp);
n = ftell (fp);
Would assign 0 to n because the file position has been
set to the start of the file by rewind.
Whenever a file is opened for reading or writing, a
rewind is done implicitly.
CSE/IT

328/338

Random access to files

fseek (file_pointer, offset,


position);

offset -> number of positions to be moved from


location specified by position.(number or variable
of type long)
position -> integer number.
CSE/IT

329/338

Random access to files


position:
Value

Meaning

Beginning of file

Current position

End of file

Offset:
positive -> meaning move forwards
negative -> meaning move backwards
CSE/IT

330/338

Statements and
Meanings
Statement

Meaning

fseek(fp,0L,0)

Go to beginning (similar to rewind).

fseek(fp,0L,1)

Stay at the current position (rarely


used).

fseek(fp,0L,2)

Go to the end of the file, past the last


character of the file.

fseek(fp,m,0)

Move to (m+1)th byte in the file.

fseek(fp,m,1)

Go to forward by m bytes.

fseek(fp,-m,1)

Go backward by m bytes from the


current position.
CSE/IT

331/338

Random access to files


fseek:
Returns zero, when operation is successful.
Returns -1 when attempted to move file pointer
beyond the file boundaries (error occurs).

CSE/IT

332/338

Program
Program that uses functions ftell and fseek:
Code:
main()
{
FILE *fp;
long int n;
char c;
fp=fopen("Random","w");
while((c=getchar())!=EOF)
putc(c,fp);
CSE/IT

333/338

Continue..
printf("No. of characters entered = %ld\n",ftell(fp));
fclose(fp);
fopen("Random","r");
n=0L;
while(feof(fp)==0){
fseek(fp,n,0); //position to (n+1)th character
printf("Position of %c is %ld\n", getc(fp),ftell(fp));
n++;}
fclose(fp);
system("PAUSE");
}
CSE/IT

334/338

Command line
arguments
It is a parameter supplied to a program when the
program is invoked.
Parameter may represent a file name the program should
process.
Command line to copy contents of a file named X_FILE
to another one named Y_FILE:

C > PROGRAM
PROGRAM is the file name where the executable code
X_FILE Y_FILE
of the program is stored.

CSE/IT

335/338

Command line
arguments
main function:
can also take arguments like other functions.
Can take two arguments called argc and argv.
The information contained in the command line is
passed on to the program through these arguments,
when main is called up by the system.

CSE/IT

336/338

Command line
arguments
agrc:
Is an argument counter
counts the no. of arguments on the command line.

argv:
Is an argument vector
Represents an array of character pointers that
points to the command line arguments.
Size of this array = value of argc.
CSE/IT

337/338

Command line
arguments
Ex:
C > PROGRAM X_FILE Y_FILE

Here,
argc = 3
argv = array of three pointers to strings,
argv[0] = PROGRAM
argv[1] = X_FILE
argv[2] = Y_FILE
CSE/IT

338/338

Command line
arguments
To access these command line arguments, we must declare
the main function and its parameters as:
main (int argc, char *argv[])
{
.
.

First parameter in command} line -> always program name


i.e., argv[0].
CSE/IT

339/338

You might also like