Cspc final

192
CSPC-COMPUTER SYSTEMS PROGRAMMING IN ‘C’ ANKUR SRIVASTAVA DEPARTMENT OF COMPUTER SCIENCE 31-Dec-16 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI 1

Transcript of Cspc final

Page 1: Cspc final

CSPC-COMPUTER SYSTEMS

PROGRAMMING IN ‘C’

ANKUR SRIVASTAVA

DEPARTMENT OF COMPUTER SCIENCE

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

1

Page 2: Cspc final

BASICS OF COMPUTER: INTRODUCTION TO DIGITAL COMPUTER, BASIC OPERATIONS OF COMPUTER, FUNCTIONAL COMPONENTS OF COMPUTER, CLASSIFICATION OF

COMPUTERS.

INTRODUCTION TO OPERATING SYSTEM: [DOS, WINDOWS, LINUX AND ANDROID] PURPOSE, FUNCTION, SERVICES AND TYPES.

NUMBER SYSTEM: BINARY, OCTAL AND HEXADECIMAL NUMBER SYSTEMS, THEIR MUTUAL CONVERSIONS.

BINARY ARITHMETIC. BASICS OF PROGRAMMING: APPROACHES TO PROBLEM SOLVING, CONCEPT OF ALGORITHM AND FLOWCHARTS.

TYPES OF COMPUTER LANGUAGES:- MACHINE LANGUAGE, ASSEMBLY LANGUAGE AND HIGH LEVEL LANGUAGE, CONCEPT OF ASSEMBLER, COMPILER, LOADER AND

LINKER.

UNIT-1 TOPICS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

2

Page 3: Cspc final

STANDARD I/O IN “C”, FUNDAMENTAL DATA TYPES- CHARACTER TYPE, INTEGER, SHORT, LONG, UNSIGNED, SINGLE AND DOUBLE FLOATING POINT.

STORAGE CLASSES- AUTOMATIC, REGISTER, STATIC AND EXTERNAL.

OPERATORS AND EXPRESSION USING NUMERIC AND RELATIONAL OPERATORS, MIXED OPERANDS.

TYPE CONVERSION, LOGICAL OPERATORS, BIT OPERATIONS, ASSIGNMENT OPERATOR, OPERATOR PRECEDENCE AND ASSOCIATIVELY.

FUNDAMENTALS OF C PROGRAMMING: STRUCTURE OF C PROGRAM, WRITING AND EXECUTING THE FIRST C PROGRAM, COMPONENTS OF C LANGUAGE. STANDARD I/O

IN C.

UNIT-2 TOPICS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

3

Page 4: Cspc final

CONDITIONAL PROGRAM EXECUTION: APPLYING IF AND SWITCH

STATEMENTS, NESTING IF AND ELSE, USE OF BREAK AND DEFAULT WITH

SWITCH.

PROGRAM LOOPS AND ITERATIONS: USE OF WHILE, DO WHILE AND FOR

LOOPS, MULTIPLE LOOP VARIABLES, USE OF BREAK AND CONTINUE

STATEMENTS.

FUNCTIONS: INTRODUCTION, TYPES OF FUNCTIONS, FUNCTIONS WITH ARRAY,

PASSING VALUES TO FUNCTIONS, RECURSIVE FUNCTIONS.

UNIT-3 TOPICS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

4

Page 5: Cspc final

ARRAYS: ARRAY NOTATION AND REPRESENTATION, MANIPULATING ARRAY

ELEMENTS, USING MULTI-DIMENSIONAL ARRAYS.

STRUCTURE, UNION, ENUMERATED DATA TYPES.

UNIT-4 TOPICS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

5

Page 6: Cspc final

POINTERS: INTRODUCTION, DECLARATION, APPLICATIONS FILE HANDLING.

STANDARD C PREPROCESSORS, DEFINING AND CALLING MACROS.

CONDITIONAL COMPILATION, PASSING VALUES TO THE COMPILER.

UNIT-5 TOPICS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

6

Page 7: Cspc final

Some Basic Computer Understanding

1: What is a computer?

2: Different Types

3: Different Operating Systems

4: Different Brands

5: Basic Components

6: Hardware & Software

7: How a computer boots up

8: Different applications of a computer

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

7

Page 8: Cspc final

Basics of Computer:

Introduction to Digital Computer:- A Computer is an Electronic

device which takes Input and gives Output.

Computers are machines that perform tasks or calculations according to a set of instructions, or programs.

It works through an interaction of Hardware & Software.

Hardware items such as our monitor, keyboard, mouse, printer.

Software such as System software and Application software.

COMPUTER is a MACHINE that manipulates DATA according to a

list of INSTRUCTION. To accomplish a task using a computer,

need a combination of hardware, software .

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

8

Page 9: Cspc final

Printer Speakers UPS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

9

Monitor

LCD CRT LED

CPU KEYBOARD MOUSE

Page 10: Cspc final

Basic Operations of Computer:-

Program & Data

Results

Central Processing

Unit

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

10

Input

Unit

Output

UnitStorage

Unit

Control

Unit

Arithmetic

Logic Unit

Page 11: Cspc final

Basic Operations:

Input Unit:- Information and Programs are entered into the COMPUTER

through Input Devices such as the KEYBOARD, DISKS, or through other Computers

via network connections or modems connected to the INTERNET. The Input

Device also retrieves information off Disks.

Output Unit:- This unit takes care of receiving processed information from

processing unit & present it to the user in suitable form. A computer produces

results in binary form & output unit does Decoding to make it usable to the users.

The devices that can output information from computer are known as output unit

devices. Monitors, Speakers, Projectors are soft output devices whereas printers,

plotters produces hard copy output.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

11

Page 12: Cspc final

Processing Unit:-

The assignment of performing calculations and contrasts are known as processing. The unit in Computer System that is accountable for processing is ALU (Arithmetic and Logical Unit).

ALU is the place where real execution of the instructions takes place during the processing operations. All calculations & comparisons are made in the ALU. The data and instructions deposited in the primary storage are moved to it as when required. ALU may produce Intermediate results and store it in the memory which are also transferred back to the ALU for the final processing. After conclusion of processing the final results are send to storage units from ALU.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

12

Page 13: Cspc final

Storage Unit:-

Before actual processing start, data & directions entered to the computer

must be stored somewhere inside the computer. Similarly, results produced by

the computer are required to be stored before it is passed to the output unit.

The middle result created by the computer must also be kept for further

processing. Thus the status of storage Unit in a computer system is vital.

Based on whether storage device is inside the main machine or not, it can be

internal internal or external storage. Similarly, looking at whether the storage

device works close with CPU or works as holdup media, they can be primary

storage or unimportant storage. Primary storage are also called primary

memory. Unimportant storage are known with other names such as backup

storage or secondary memory.

For the storage purpose, a computer system may have different devices such

as registers, cache, RAM/ROM, flash, magnetic disks, optical disks and so on.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

13

Page 14: Cspc final

Control Unit:-

It manages co-ordinates the entire system.

CU doesn’t perform any actual processing on data yet it is known as a central

nervous system for the comforts of the computer.

It controls all the processing & calculations of the ALU.

It directs operation of the processor.

It tells how to respond to a program's instructions.

It directs the operation of the other units by providing timing and control signals.

Most computer resources are managed by the CU.

It directs the flow of data between the CPU and the other devices.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

14

Page 15: Cspc final

Functional Components of COMPUTER

The five classic components of a Computer are as follows:-

Processor(CPU)

Main Memory

Secondary Memory

Input Devices

Output Devices

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

15

Page 16: Cspc final

FIG. THE OPERATION OF A PROCESSOR

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

16

CPU

Output

Devices

Storage

Devices

Input

DevicesMemory

CPU

Output Devices

Storage

Devices

Input Devices Memory

Page 17: Cspc final

MEMORY:

Memory

Primary or Main memory

RAM

SRAM

DRAM

ROM

PROM

EPROM

EEPROM

Secondary or Auxiliary memory

Hard Disk, Floppy Disks, Magnetic Tapes, Offline

storage, optical disks, flash memory, USB

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

17

Page 18: Cspc final

TYPES OF DRAM:

DRAM

Synchronous DRAM

Enhanced SDRAM

DDR SDRAM DDR2RambusDRAM

Synchronous link DRAM

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

18

Page 19: Cspc final

FUNCTIONAL COMPONENTS OF COMPUTER

1. Processor:- The processor is an electronic device about a one

inch square, covered in plastic.

2. Memory:- The processor performs all the fundamental

computations of the computer system.

3. Input & Output Devices:- Input & Output devices allow the

computer system to interact with the outside world by moving data into & out of the system.

4. Storage Devices:- There are two types of storage devices used

with computers: a primary storage device, such as RAM, and a

secondary storage device, like a hard drive. Secondary storage can be removable, internal, or external storage.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

19

Page 20: Cspc final

CLASSIFICATION OF COMPUTERS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

20

CLASSIFICATION OF COMPUTERS

Computers

Analog Digital Hybrid (Analog +Digital)

Purpose Performance& Size

Special Purpose

General Purpose

Embedded Micro Mini Mainframe Super

Page 21: Cspc final

Classification of Computers

1. Analog Computer:-

Analog computers are used to process continuous data.

Analog computers represent variables by physical quantities.

such as flow, temperature, pressure.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

21

Page 22: Cspc final

2. Digital Computer:-

Digital computer represents physical quantities with the help of digits or

numbers.

These numbers are used to perform Arithmetic calculations and also

make logical decision to reach a conclusion, depending on, the data

they receive from the user.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

22

Page 23: Cspc final

3. Hybrid Computers

Various specifically designed computers are with both digital and

analog characteristics combining the advantages of analog and digital

computers when working as a system.

Hybrid computers are being used extensively in process control system.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

23

Page 24: Cspc final

SUPER COMPUTER

It is used for large purpose works.

Used for scientific research.

Used in research laboratories.

These computers are extremely expensive and the speed is

measured in billions of instructions per seconds.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

24

Page 25: Cspc final

MINI COMPUTERS

Mini Computers are smaller in size as well as speed.

They are versatile that they can be fitted where ever they are needed.

Their speeds are rated between one and fifty million instructions per

second (MIPS).

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

25

Page 26: Cspc final

MICRO COMPUTERS

These are the smallest range of computers.

less storing space and processing speed.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

26

Page 27: Cspc final

Applications of Computers:- Today computers are widely used in fields such as engineering, health care, banking, education, etc.

Word Processing

Internet

Digital Video or Audio composition

Desktop Publishing

e- business

Bioinformatics

Health Care

Meteorology

Multimedia & Animation

Travel & Tourism

Simulation

Robotics

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

27

Page 28: Cspc final

Introduction to Operating System

The Interaction between the user and the system is known as Operating

System.

It provides a user-friendly environment in which a user may easily

develop and execute programs.

The OS manages these following resources and allocates them to

specific programs and users.

Processor Management

Memory Management

File Management

Device Management

Concurrency Control

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

28

Page 29: Cspc final

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

29

Application Programs

System Programs

Operating System

Machine Language

Hardware

Position of Operating System

Page 30: Cspc final

Types of OS: DOS, WINDOWS, LINUX and ANDRIOID

DOS:- Disk Operating System(1981)

It is a non-graphical command line operating system.

It was very powerful OS of that time

Easy to load and install.

The following are the commands used frequently-

CD- to change the current directory

COPY- to copy a file

DEL- to delete a file

DIR- to list directory contents

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

30

Page 31: Cspc final

EDIT- to start an editor to create or edit text files

FORMAT- to format a disk

HELP- to display information about a command

MKDIR- to create a new directory

RD- to remove a directory

REN- to rename a file

TYPE- to display contents of a file on the screen

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

31

Page 32: Cspc final

WINDOWS

Developed by Microsoft.

Initially two editions were taken- Home Users & IT Professionals.

IT Professionals.

--Well suited for server environment.

--Limited multimedia features.

--Enhanced networking capability & security.

Home Users support-

--More functionalities & multimedia features

--Limited support for security & networking

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

32

Page 33: Cspc final

S.No Version Year Reason/Limitations

1. Version 1.0 1985 Lack of functionality

2. Version 2.0 1987 Slightly more popularity

3. Version 2.03 1988 Different look

4. Version 3.0 1990 Commercial success, user interface

5. Version 3.1 1992 Offered OS a new facelift

6. Windows NT 1993 Designed for professional platform

7. Windows 95 1995 Support for pre-emptive multitasking

8. Windows 98 1998 Slower & less reliable than its previous one

9. Windows 00 2000 Consumer version

10. Windows XP 2001 Very popular.

11. Windows 7 2009 New features, compatibility with H/W

12. Windows 8 2012 Start screen-launch programs, search files,

browse the web.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

33

Page 34: Cspc final

LINUX

It is very powerful, free, open-source operating system based on UNIX.

It is free to download and one can make change to it.

Some advantage includes-

--Low cost

--Stability

--Performance

--Networking, Security

--Flexibility, Multitasking

--Compatibility

--Fast & easy to install

--Better use of hard disk

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

34

Page 35: Cspc final

ANDROID

It is Google’s OS, used on mobile devices.

Leading smartphones manufacturers such as Samsung, HTC, Motorola.

Currently it is one of the top operating systems.

Open source OS powered by the Linux Kernel.

Users can use this OS to develop apps.

It is a multitasking OS.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

35

Page 36: Cspc final

PURPOSE

To provide interaction b/w user and system.

To manage the computer hardware.

Provides a user interface.

To manage process management.

To organize memory management.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

36

Page 37: Cspc final

FUNCTION, SERVICES and TYPES

Function & Services

Functions are little bit same as the services.

The OS protects stored information from malicious users.

The OS allows users to create, copy, delete, and rename files.

Memory management is one of the important function of OS.

Multiple processes can be executed at the same time.

With the help of icons it is easy to interact for users.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

37

Page 38: Cspc final

TYPES OF OPERATING SYSTEMS

Based on usage and requirements, OS can be classified into different categories.

Batch operating system(BOS)

Single –user single-tasking operating system(SUSTOS)

Single-user multitasking operating system(SUMOS)

Multi-user multitasking operating system(MUMOS)

Multiprocessing(MP)

Real-time operating system(RTOS)

Network operating system(NOS)

Time-sharing operating system(TSOS)

Distributed operating system(DOS)

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

38

Page 39: Cspc final

BOS:

IT allows very limited interaction between user & processor.

Programs are bundled as a “batch” and executed together.

On large data, it performs very well.

Its processing is performed automatically.

The problems with Batch Systems are as follows −

--Lack of interaction between the user and the job.

--CPU is often idle, because the speed of the mechanical I/O devices is slower than the

CPU.

--Difficult to provide the desired priority.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

39

Page 40: Cspc final

SUSTOS:

It allows only one program to execute at a time.

Example- the Palm OS for Palm handled computers.

SUMOS:

Allows single user to perform several tasks simultaneously.

We usually use this in desktop and laptop computers.

Example- typing in Ms-Word while listening a song & downloading a file from the

Internet.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

40

Page 41: Cspc final

MUMOS:

It enables multiple users on different computers to access a single system.

By one CPU and one OS, many terminals can connect to the main computer.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

41

Page 42: Cspc final

MP:

It means two or more processors(CPUs) within a single computer system.

Complex programs can be divided into smaller programs.

Multiplicity of the processors and how they do act together are transparent to the others.

Following are some advantages of this type of system:-

--Enhanced performance

-- Execution of several tasks by different processors concurrently, increases the

system's throughput without speeding up the execution of a single task.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

42

Page 43: Cspc final

RTOS

It guarantees the maximum time for critical operations and complete them on time.

Real-time systems are used when there are rigid time requirements.

It is referred to as Hard Real-Time Operating Systems.

Hard real-time systems guarantee that critical tasks complete on time.

RTOS are used to control machinery, scientific instruments and industrial systems.

Soft real-time systems are less restrictive.

For example, multimedia, virtual reality, Advanced Scientific Projects like undersea

exploration and planetary rovers, etc.

Some more examples, Scientific experiments, medical imaging systems, industrial

control systems, weapon systems, robots, air traffic control systems, etc

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

43

Page 44: Cspc final

NOS

It runs on a server.

It provides the server the capability to manage data, users, groups,

security, applications, and other networking functions.

It allows shared file and printer access among multiple computers in

a network.

Examples of network operating systems include Microsoft Windows

Server 2003, Microsoft Windows Server 2008, UNIX, Linux, Mac OS X,

Novell NetWare, and BSD.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

44

Page 45: Cspc final

Advantages of network operating systems:

--Centralized servers are highly stable.

--Security is server managed.

Disadvantages

High cost of buying and running a server.

Dependency on a central location for most operations.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

45

Page 46: Cspc final

TSOS

time sharing systems are an extension of multiprogramming systems.

the prime focus is on minimizing the response time.

Multiple jobs are executed by the CPU by switching between them.

i.e the user can receive an immediate response.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

46

Advantages Disadvantages

Provides the advantage of quick

response.

Question of security and integrity of

user programs and data.

Avoids duplication of software. Problem of reliability.

Reduces CPU idle time. Problem of data communication.

Page 47: Cspc final

DOS

It use multiple central processors to serve multiple real-time applications

and multiple users.

Processors communicate with one another through various

communication lines (such as high-speed buses or telephone lines).

These are referred as loosely coupled systems or distributed systems.

These processors are referred as sites, nodes, computers, and so on.

Advantages

Better service to the customers.

Reduction of the load on the host computer.

Reduction of delays in data processing.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

47

Page 48: Cspc final

NUMBER SYSTEM: BINARY, OCTAL, DECIMAL AND

HEXADECIMAL

Data is stored in a computer in the form of 0s & 1s.

A number is represented by a string of digits, where each digit position has an associated

weight.

Each number system is associated with a base or radix.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

48

System Base Symbols

Used by

humans?

Used in

computers?

Decimal 10 0, 1, … 9 Yes No

Binary 2 0, 1 No Yes

Octal 8 0, 1, … 7 No No

Hexadecimal 16 0, 1, … 9,A, B,..F No No

Page 49: Cspc final

BINARY:

1. Convert 1101 into a decimal number.

Decimal number = 1*23 + 1*22 + 0*21 +1*20

= 1 * 8 + 1* 4 + 0 +1*1

= 8 + 4+ 0+ 1

= 13.

2. Convert (13)10 into a binary number.

13/2 = 6 rem 1

6/2 = 3 rem 0

3/2 = 1 rem 1

1/2 = 1 rem 1

(13)10 =(1101)2

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

49

Page 50: Cspc final

OCTAL:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

50

The octal number system: Base-8

Eight digits: 0,1,2,3,4,5,6,7

The hexadecimal number system: Base-16

Sixteen digits: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

For our purposes, base-8 and base-16 are most useful as a

“shorthand” notation for binary numbers

10

1012

8 )5.87(84878281)4.127(

10

0123

16 )46687(16151651661611)65( FB

Page 51: Cspc final

NUMBERS WITH DIFFERENT BASE:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

51

Decimal Binary Octal Hex

0 0000 0 0

1 0001 1 1

2 0010 2 2

3 0011 3 3

4 0100 4 4

5 0101 5 5

6 0110 6 6

7 0111 7 7

8 1000 10 8

9 1001 11 9

10 1010 12 A

11 1011 13 B

12 1100 14 C

13 1101 15 D

14 1110 16 E

15 1111 17 F

Page 52: Cspc final

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

52

Converting from octal to binary: Replace each octal digit with its

equivalent 3-bit binary sequence

Converting from binary to octal: Make groups of 3 bits, starting from

the binary point. Add 0s to the ends of the number if needed. Convert

each bit group to its corresponding octal digit.

= 6 7 3 . 1 2

= 110 111 011 . 001 010

=

8)12.673(

2)001010.110111011(

10110100.0010112 = 010 110 100 . 001 0112

= 2 6 4 . 1 38

Page 53: Cspc final

BINARY AND HEX CONVERSIONS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

53

Converting from hex to binary: Replace each hex digit with its

equivalent 4-bit binary sequence

Converting from binary to hex: Make groups of 4 bits, starting from the binary point. Add 0s to the ends of the number if

needed. Convert each bit group to its corresponding hex digit.

261.3516 = 2 6 1 . 3 516

= 0010 0110 0001 . 0011 01012

10110100.0010112 = 1011 0100 . 0010 11002

= B 4 . 2 C16

Page 54: Cspc final

BINARY ARITHMETIC:

Rules of Binary Addition

0 + 0 = 0, 0+1 = 1, 1+0 = 1

1+1 = 0, and carry 1 to the next more significant bit.

Rules of Binary Subtraction

0 - 0 = 0, 1-0 = 1, 1-1 = 0

0-1= 0, and borrow 1 from the next more significant bit.

Rules of Multiplication

0 * 0 = 0, 1*0 = 0, 1*1 = 1, 0*1= 0

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

54

Page 55: Cspc final

BASICS OF PROGRAMMING:

Program is a set of instruction to solve the problem.

‘C’ has now become a widely used professional language for

various reasons.

Easy to learn

Structured language

It produces efficient programs.

It can handle low-level activities.

It can be compiled on a variety of computers.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

55

Page 56: Cspc final

SOME FACTS ABOUT “C”

C was invented to write an operating system called UNIX.

C is a successor of B language which was introduced around

1970

The language was formalized in 1988 by the American National

Standard Institute (ANSI).

By 1973 UNIX OS almost totally written in C.

Today C is the most widely used System Programming Language.

Most of the state of the art software have been implemented

using C.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

56

Page 57: Cspc final

WHY TO USE “C”

C was adopted as a system development language.

It produces code that runs nearly as fast as code written in assembly

language.

Some examples of the use of C might be:

Operating Systems Language Compilers

Assemblers Text Editors

Print Spoolers Network Drivers

Modern Programs Data Bases

Language Interpreters Utilities

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

57

Page 58: Cspc final

APPROACHES TO PROBLEM SOLVING

People who are really good at solving problems go

about it systematically.

They have a way of placing the problem in context.

They don't jump to conclusions.

They evaluate alternatives.

A good way to become a systematic problem solver is

to adopt the following five-step problem-solving

process.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

58

Page 59: Cspc final

IDENTIFY THE PROBLEM.

This is critical: you must try to solve the right

problem.

Identify the right problem by asking the right

questions and observing.

You cannot identify the customer's problems

by presenting your products.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

59

Page 60: Cspc final

ANALYZE THE PROBLEM.

How often does the problem occur?

How severe is it?

Are there any special circumstances that are

present when it occurs?

What might be the causes of the problem?

Can you rule out any causes?

How long has it been going on?

Has it gotten worse?

How is the problem affecting other processes or people?

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

60

Page 61: Cspc final

ANALYZE PROBLEM

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

61

Page 62: Cspc final

IDENTIFY DECISION CRITERIA.

How will you and the customer make decisions when it is time to

decide?

How will you weigh the criteria?

Can you identify independent standards that can be used?

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

62

Page 63: Cspc final

DEVELOP MULTIPLE SOLUTIONS.

Don't stop at the first solution that you or others identify.

It may be good, but much better ones may exist.

Evaluate alternative scenarios.

As objectively as possible, assess the pros and cons of each.

Choose the optimal solution.

Use the criteria you developed in the third step of this problem-

solving process to choose the best solution.

Develop a base of support that will ensure you can implement

the solution.

Prepare for contingencies.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

63

Page 64: Cspc final

CONCEPT OF ALGORITHM AND FLOWCHARTS

The sequence of steps to be performed in order to solve a

problem by the computer is known as an algorithm.

Three reasons for using algorithms are efficiency, abstraction and reusability.

Flowchart is a diagram that shows the step-by-step execution of a control

structure.

Flowchart is a graphical or symbolic representation of an algorithm.

It is the diagrammatic representation of the step-by-step solution to a given

problem.

A diamond-shaped box represents a decision.

A rectangular box represents an assignment statement or a process.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

64

Page 65: Cspc final

EXAMPLE OF ALGORITHM

Write an algorithm to add two numbers.

STEP1 Read the Value of A and B.

STEP2 SUM = A+B.

STEP3 Display SUM.

STEP4 Stop.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

65

Page 66: Cspc final

EXAMPLE OF A FLOWCHART

Write (Display) the Sum, Average and Product

Flowchart for the above problem will look like

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

66

Start

Read X,Y,Z

S= X+Y+Z

A=S/3

P=X*Y*Z

Write S,A,P

Stop

Page 67: Cspc final

ADVANTAGES OF USING FLOWCHARTS:

Communication: Flowcharts are better way of communicating

the logic of a system to all concerned.

Effective analysis: With the help of flowchart, problem can be

analyzed in more effective way.

Proper documentation:Program flowcharts serve as a good

program documentation, which is needed for various purposes.

Efficient Coding: The flowcharts act as a guide or blueprint

during the systems analysis and program development phase.

Proper Debugging: The flowchart helps in debugging process.

Efficient Program Maintenance:The maintenance of operating

program becomes easy with the help of flowchart. It helps the programmer to

put efforts more efficiently on that part.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

67

Page 68: Cspc final

Example Of A If-else Flowchart

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

68

Page 69: Cspc final

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

69

Start

Read A, B

Is A > B

Print A Print B

End

Yes No

Flow Chart to find largest of two numbers:

Page 70: Cspc final

LIMITATIONS OF USING FLOWCHARTS:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

70

Complex logic: Sometimes, the program logic is quite complicated. In

that case, flowchart becomes complex and clumsy.

Alterations and Modifications: If alterations are required the flowchart

may require re-drawing completely.

Reproduction: As the flowchart symbols cannot be typed,

reproduction of flowchart becomes a problem.

Page 71: Cspc final

TYPES OF COMPUTER LANGUAGES: MACHINE,

ASSEMBLY, & HIGH LEVEL LANGUAGES

A programming language is an artificial language that can be

used to control the behavior of a machine, particularly a

computer .

Programming languages, like human languages, are defined

through the use of syntactic and semantic rules, to determine

structure and meaning respectively.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

71

Page 72: Cspc final

MACHINE LANGUAGE:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

72

• It is the lowest-level programming language.

Machine languages are the only languages understood by

computers.

Page 73: Cspc final

ASSEMBLY LANGUAGE:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

73

An assembly language is a low-level language for programming computers.

The word "low" does not imply that the language is inferior to high-level programming languages but rather refers to the small or nonexistent amount of abstraction between the language and machine language, because of this, low-level languages are sometimes described as being "close to the hardware."

It implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture.

Page 74: Cspc final

HIGH LEVEL LANGUAGE:

High-level languages are relatively easy to learn because the instructions bear a close resemblance to everyday language, and because the programmer does not require a detailed knowledge of the internal workings of the computer.

Each instruction in a high-level language is equivalent to several machine-code instructions, therefore it is more compact than equivalent low-level programs.

High-level languages are used to solve problems and are often

described as problem-oriented languages

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

74

Page 75: Cspc final

Concept of Assembler

It translates the assembly language into machine level language.

Translate mnemonic operation codes to machine code.

Assign addresses to symbolic labels used by the programmer

Fig1. The flow of assembler

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

75

AssemblerAssembly language code

Object code

Page 76: Cspc final

COMPILER:

It is a program translator that translates the instruction of a higher level

language to machine language.

It is called compiler because it compiles machine language instructions for

every program instructions of higher level language.

The programs written by the programmer in higher level language is called

source program.

After this program is converted to machine languages by the compiler it is called

object program.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

76

Page 77: Cspc final

INTERPRETER:

An interpreter is another type of program translator used for translating

higher level language into machine language.

It takes one statement of higher level languages, translate it into machine

language and immediately execute it.

Translation and execution are carried out for each statement.

It differs from compiler, which translate the entire source program into

machine code.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

77

High level

language interpreterLow level

language

Page 78: Cspc final

LOADER:

Software that copies programs

from a storage device to the

main memory, where they can be

executed.

A loader is a special type of

program that is part of an OS.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

78

Object code

source code

Assembly code

Executable code

compiler

Preprocessor

assembler

Link editor

libraries

Page 79: Cspc final

LINKER:

Software that transforms source code written in a programming language into

machine language comprising of just two digits, 1 & 0.

It is also called link editor and binder.

It combines object modules to form an executable program.

TRANSLATOR:

A computer program, which translates a code written in one programming

language to a code in another language that the computer understands.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

79

Page 80: Cspc final

UNIT-2 STANDARD I/O IN “C”

When we say Input, it means to feed some data into a program.

When we say Output, it means to display some data on screen, printer, or in

any file.

The Standard Files

C programming treats all the devices as files.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

80

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

Page 81: Cspc final

STANDARD I/O IN “C”

Two commonly used functions for I/O (Input/Output) are printf() and

scanf().

The scan() function reads formatted input from standard input (keyboard).

The printf() function sends formatted output to the standard output

(screen).

#include <stdio.h> //This is needed to run printf() function.

int main() {

printf(“ C programming”); // displays the content inside quotation.

return 0;

}

OUTPUT

C programming31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

81

Page 82: Cspc final

TYPES AND THEIR VALUES

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

82

Predefined Types Values

Read Character from File getc, fgetc and getchar

Write Character to File putc, fputc and putchar

Read String from File fgets and gets

Read Binary Data from File fread

Write String to File fputs and puts

Write Binary Data to File fwrite

Read Formatted Input scanf, fscanf, sscanf

Write Formatted Output printf, fprintf, sprintf

File Position fgetpos, fsetpos, rewind, fseek, and ftell

Page 83: Cspc final

FUNDAMENTAL DATA TYPES:

A data type is--

A set of values AND.

A set of operations on those values.

A data type is used to--

Identify the type of a variable when the variable is declared.

Identify the type of the return value of a function.

Identify the type of a parameter expected by a function.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

83

Page 84: Cspc final

FUNDAMENTAL DATA TYPES:

void – used to denote the type with no values

int – used to denote an integer type

char – used to denote a character type

float, double – used to denote a floating point

type

int *, float *, char * – used to denote a pointer

type, which is a memory address type.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

84

Page 85: Cspc final

TWO CLASSIFICATIONS OF DATA TYPES

Built-in data types

Fundamental data types (int, char, double, float,

void, pointer)

Derived data types (array, string, structure)

Programmer-defined data types

Structure

Union

Enumeration

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

85

Page 86: Cspc final

DERIVED DATA TYPES:

Array – a finite sequence (or table) of variables of the same data

type

String – an array of character variables

Structure – a collection of related variables of the same and/or

different data types. The structure is called a record and the

variables in the record are called members or fields

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

86

Page 87: Cspc final

PRIMARY DATA TYPES

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

87

PDT(Integer)

Signed

int

Short int

Long int

Unsigned

Unsigned int

Unsigned short int

Unsigned long int

Page 88: Cspc final

SINGLE AND DOUBLE FLOATING POINT

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

88

Floating point type

float

double

Long

double

Page 89: Cspc final

CHARACTER:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

89

Character

char

Signed char

Unsigned

char

Page 90: Cspc final

SIZE & RANGE OF DATA TYPES:

Type Size(bits/bytes) Range

Char or signed char 8/1 -128 to 127

Unsigned char 8/1 0 to 255

int or signed int 16/2 - 32768 to 32767

Unsigned int 16/2 0 to 65535

Short int or

Signed short int 8/1 -128 to 127

Unsigned short int 8/1 0 to 255

Long int or

Signed long int 32/4 -2147483648 to 2147483647

Unsigned long int 32/4 0 to 4294967295

float 32/4 3.4 E- 38 to 3.4 E + 38

double 64/8 1.7 E – 308 to 1.7 E + 308

Long double 64/8 3.4 E- 4932 to 3.4 E + 4932

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

90

Page 91: Cspc final

STORAGE CLASSES: AUTOMATIC, REGISTER, STATIC

AND EXTERNAL

A storage class defines the scope (visibility) and life time of

variables and/or functions within a C Program.

There are following storage classes which can be used in a C

Program

• Auto (automatic variables)

• Register variables

• Static variables

• Extern(external variables)

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

91

Page 92: Cspc final

AUTO - STORAGE CLASS

auto is the default storage class for all local variables.

{

int Count;

auto int Month;

}

The example above defines two variables with the same storage

class. auto can only be used within functions, i.e. local variables.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

92

Page 93: Cspc final

AUTO - STORAGE CLASS

Formal parameters and local variables of functions are variables

that are automatically allocated on the stack when a function is

called and automatically deallocated when the function returns.

They are of storage class auto.

By default they are assigned garbage value by the compiler.

Example

void main()

{

int detail; or

auto int detail; //Both are same

}

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

93

Page 94: Cspc final

REGISTER - STORAGE CLASS

register is used to define local variables that should be stored in aregister instead of RAM. This means that the variable has a

maximum size equal to the register size (usually one word) and

cant have the unary '&' operator applied to it (as it does not

have a memory location).

{

register int Miles;

}

Register should only be used for variables that require quickaccess - such as counters.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

94

Page 95: Cspc final

REGISTER VARIABLES

If you declare a variable of type register, it simply alerts the

compiler to the fact that this memory cell will be referenced

more often than most.

Register is a special high-speed memory location inside the

central processor.

Syntax :

register int number;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

95

Page 96: Cspc final

STATIC VARIABLES:

Static variable is allocated and initialized one time, prior to

program execution.

It remains allocated until the entire program terminates.

A static variable tells the compiler to persist the variable until the

end of program.

static is initialized only once and remains into existence till the

end of program.

Scope of internal static variable remains inside the function in

which it is defined.

External static variables remain restricted to scope of file in each

they are declared.

They are assigned 0 (zero) as default value by the compiler.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

96

Page 97: Cspc final

EXAMPLE: STATIC VARIABLE

void test(); //Function declaration

main() {

test(); test(); test();

} void test() {

static int a = 0; //Static variable

a = a+1;

printf("%d\t", a); }

output :

1 2 3

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

97

Page 98: Cspc final

EXTERNAL VARIABLES

The extern keyword is used before a variable to inform the

compiler that this variable is declared somewhere else.

The extern declaration does not allocate storage for variables.

A variable that is declared outside any function is a Global

variable.

Problem when extern is not used

main()

{

a = 10; // Error: cannot find variable a

printf("%d", a);

}

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

98

Page 99: Cspc final

EXTERN:

Storage class of names known to the linker.

Example: extern int square (int x);

Means the function will be available to the linker.

It notifies the compiler that such a function exists and that the

linker will know where to find it.

int number;

void main() {

number=10; }

fun1() {

number=20; }

fun2() {

number=30; } Here the global variable number is available to all

three functions. 31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

99

Page 100: Cspc final

OPERATORS AND EXPRESSIONS:

Operators form expressions by joining individual constants, variables, array elements.

Operators are symbols which take one or more operands or expressions and perform

arithmetic or logical computations.

C includes a large number of operators which fall into different categories.

These operators are used to form expressions. Some operators are as follows-

--arithmetic operators,

--unary operators,

--relational and logical operators,

--assignment operators and the

--conditional operators

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

100

Page 101: Cspc final

OPERATOR PRECEDENCE:

Consider the following arithmetic operation:

- left to right

6 / 2 * 1 + 2 = 5

- right to left

6/2 * 1 + 2 = 1

- using parentheses

= 6 / (2 * 1) + 2

= (6 / 2) + 2

= 3 + 2

= 5

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

101

Page 102: Cspc final

USING NUMERIC AND RELATIONAL OPERATORS:

--Arithmetic operators:

There are five main arithmetic operators in ‘C’.

They are ‘+’ for additions,

‘-' for subtraction,

‘*’ for multiplication,

‘/’ for division and

‘%’for remainder after integer division.

This ‘%’ operator is also known as modulus operator.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

102

Page 103: Cspc final

ARITHMETIC OPERATORS:

Operator example Meaning

+ a + b Addition –unary

- a – b Subtraction-

unary

* a * b Multiplication

/ a / b Division

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

103

Page 104: Cspc final

EXAMPLE OF ARITHMETIC OPERATOR

Operands can be integer quantities, floating-point quantities or

characters.

Example m=30 & n=20 respectively , now performing addition,

subtraction, multiplication, division, and modulus on m& n, we

get…….

m+n=50

m-n=10

m*n=600

m/n=1

m%n=10

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

104

Page 105: Cspc final

UNARY OPERATORS:

‘C’ includes a class of operators that act upon a single operand

to produce a new value.

Such operators are known as unary operators.

Unary operators usually precedes their single operands,

though some unary operators are written after their operands.

The most common unary operator is unary minus, where a minus

sign precedes a numerical constant, a variable or an expression.

e.g. -5,-10, -20(numbers)

x=-y(variable)

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

105

Page 106: Cspc final

MIXED OPERANDS:

When one of the operands is real and the other is integer.

If either operand is of the real type, then only the real operation is

performed .

Then the result is always a real number.

Example ---

15 / 10.0 = 1.5

Whereas

15 / 10 = 1.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

106

Page 107: Cspc final

TYPE CONVERSION:

Type conversion is done when the expression has variables of

different data types.

The data type is promoted from lower to higher level.

Type conversion is automatically done when the value is assign.

The hierarchy of data types (from higher to lower) is shown as:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

107

Page 108: Cspc final

CONVERSION HIERARCHY OF DATA TYPES

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

108

Long

double

double

int

short

float

Unsigned long

int

Long int

unsigned int

char

Page 109: Cspc final

EXAMPLE1

Consider the code given below

float x;

int y= 3;

x=y;

Now here integer value is promoted to float.

This is known as promotion.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

109

Page 110: Cspc final

EXAMPLE2

Now, x= 3.0, as automatically integer value is converted into its

equivalent floating point representation.

Consider the following group of statements:

float f= 3.5;

int i;

i= f;

Statement i= f results in f to be demoted to type int,

the fractional part of f will be lost and I will contain 3 (not 3.5).

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

110

Page 111: Cspc final

RELATIONAL OPERATORS:

Operator Meaning

< Is less than

<= Is less than or equal to

> Is greater than

>= Is greater than or equal

to

== Equal to

!= Not equal to

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

111

Page 112: Cspc final

LOGICAL OPERATORS:

For relational expression, 0 is FALSE, 1 is TRUE.

Any numeric value is interpreted as either TRUE or FALSE when it is used in a C /

C++ expression or statement that is expecting a logical (true or false) value. The rules

are:

1. A value of 0 represents FALSE.

2. Any non-zero (including negative numbers) value represents TRUE.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

112

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Page 113: Cspc final

LOGICAL OPERATORS:

Expressions Evaluates as

(3 == 3) && (4 != 3)True (1) because both operands are

true

(4 > 2) || (7 < 11)True (1) because (either) one

operand/expression is true

(3 == 2) && (7 == 7) False (0) because one operand is false

! (4 == 3)True (1) because the expression is

false

(3 == 3) && (4 != 3)True (1) because both operands are

true

NOT(FALSE) = TRUE

NOT(TRUE) = FALSE

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

113

Page 114: Cspc final

BIT OPERATORS:

A bit is the smallest digit capable of being stored in a modern day digital

computer.

A byte, consisting of 8 bits is the smallest unit of storage that a computer can work

with.

A word ( usually somewhere between 32 and 64 bits) is the smallest addressable

item in a computer.

---The word size of a computer is usually dictated by either the bus size of the

system or the word size of the CPU.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

114

Page 115: Cspc final

BITWISE OPERATORS:

Operator Name Description

& bitwise AND 1 only if both operands are 1.

| bitwise OR 1 if ether or both operands are

1

^ bitwise exclusive or 1 if either but not both

operands are 1

<< Left Shift Shifts bits of the first operand

by the number of bits specified

by the second operand.

>> Right Shift Shifts bits of the first operand

by the number of bits specified

by the second operand.

~ Complement Flips the bits in the operand.

All 1’s become 0’s and all 0’s

become 1’s.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

115

Page 116: Cspc final

BITWISE OPERATORS:

Bitwise operators are used to directly manipulate the

bits of integral operands such as char, short, int, long

(both signed and unsined).

Normally unsigned integers are used when dealing

with bitwise operations.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

116

Page 117: Cspc final

ASSIGNMENT OPERATORS:

The compound assignment operators consist of a binary operator and

the simple assignment operator.

They perform the operation of the binary operator on both operands

and store the result of that operation into the left operand.

The following table lists the simple and compound assignment

operators and expression examples:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

117

Page 118: Cspc final

Simple Assignment Operator

=

The simple assignment operator has the following form:

lvalue = expr

The operator stores the value of the right operand expr in the

object designated by the left operand lvalue.

The left operand must be a modifiable lvalue.

The type of an assignment operation is the type of the left

operand.

i = 5 + x;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

118

Page 119: Cspc final

CONDITIONAL OPERATORS:

Syntax:

exp1 ? exp2 : exp3

Where exp1,exp2 and exp3 are expressions

Working of the ? Operator:

Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated

and this becomes the value of the expression,

If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the

expression

Ex: m=2;

n=3

r=(m>n) ? m : n;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

119

Page 120: Cspc final

OPERATOR PRECEDENCE AND ASSOCIATIVELY :

The operator within C are grouped hierarchically according to their order of evaluation

known as precedence.

operations with a higher precedence are carried out before operations having a lower

precedence.

Arithmetic operators *,/ and % are under one precedence group and

+,- are under another precedence group.

The operators *, / and % have higher precedence than + and -.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

120

Page 121: Cspc final

Consecutive operations within the same precedence group are

carried out. This is known as associativity.

Example, say there are 3 variables a, b, and c having values 5,10

and 15 respectively.

The different operations on these three variables and their result is

as follows:

a+b/c=5,

b*c-a=145

a*b/c= 3,

(a+c)*b/a=40

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

121

Page 122: Cspc final

OPERATOR PRECEDENCE:

Precedence and Associativity of C Operators

Symbol Type of Operation Associativity

[ ] ( ) . –> postfix ++ and

postfix ––Expression Left to right

prefix ++ and prefix –– sizeof

& * + – ~ !Unary Right to left

typecasts Unary Right to left

* / % Multiplicative Left to right

+ – Additive Left to right

<< >> Bitwise shift Left to right

< > <= >= Relational Left to right

== != Equality Left to right

& Bitwise-AND Left to right

^ Bitwise-exclusive-OR Left to right

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

122

Page 123: Cspc final

OPERATOR PRECEDENCE EXAMPLE

Evaluating expressions using the precedence chart

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

123

1. x= 3 * 4 + 5 * 6

=12 + 5 * 6

=12 + 30

=42

2. x = 3 * ( 4 + 5) * 6

= 3 * 9 * 6

= 27 * 6

= 162

3. x= 3 * 4 % 5 / 2

= 12 % 5 / 2

= 2 / 2

= 1

4. x= 3 * (( 4 % 5) / 2 )

= 3 * (4 / 2)

= 3 * 2

= 6

Page 124: Cspc final

FUNDAMENTALS OF C PROGRAMMING:

C was developed in 1972 by “Dennis Ritchie” at AT & T Bell Lab.

It was developed for the ease of programming.

Some features for which it is so popular:

---It is very calm to learn

---It is a planned language

---It produces well-organized programs.

---It can handle low-level activities.

---It can be compiled on a multiplicity of computers.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

124

Page 125: Cspc final

STRUCTURE OF C PROGRAM

An example of simple program in C

#include <stdio.h>

void main(void)

{

printf(“I love programming\n”);

printf(“You will love it too once ”);

printf(“you know the trick\n”);

}

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

125

Preprocessor directive

Null Data Type

Closing parenthesis

Angle bracket

Standard input output

function

Line termination

Page 126: Cspc final

WRITING AND EXECUTING THE FIRST C PROGRAM

#include<stdio.h>

#include<conio.h>

Void main()

{

clrscr();

Int a, b, c;

Printf(“enter the value of a &

b”);

Scanf(“%d %d”, &a, &b);

c= a+b;

Printf(“value of c is =%d”, c);

getch();

}

OUTPUT

Enter the value of a & b

5 5

10

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

126

Page 127: Cspc final

COMPONENTS OF C LANGUAGE

Some basic component of a C program.

#include - The #include is known as a preprocessor directive

It is used to tell the C preprocessor to find the stdio file with

extension .h.

main() – Execution of a program starts from a main() function.

printf() - This is the standard way of producing output.

The functionality of printf() is referenced in stdio.h by the C

compiler.

scanf() - This is the standard way of taking input from user.

comments: Comments are information given by the program to make

a program readable and easy to understand.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

127

Page 128: Cspc final

STANDARD I/O IN C

So far our C programs are as follows:

/* description of program */

#include <stdio.h>

/* any other includes go here */

int main(){

/* program body */

return 0;

}

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

128

Page 129: Cspc final

UNIT-3 CONDITIONAL PROGRAM EXECUTION

C supports two types of decision control statements.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

129

Selection/Branching statement

Conditional type

if If-else If-else-if switch

Unconditional type

Page 130: Cspc final

CONDITIONAL BRANCHING STATEMENTS:

These statements helps to jump from one part to another part.

Whether a particular condition is satisfied or not.

It includes:-

---- if statement

---- if- else statement

---- if- else- if statement

---- Switch statement

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

130

Page 131: Cspc final

IF STATEMENTS

The if statement allows the program to test the state of the

program variables using a Boolean expression.

Syntax

If (test expression)

{

Statement 1;

……………

Statement n;

}

Statement x;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

131

Test

exp

Statement

block 1

Statement x

FALSE

TRUE

Page 132: Cspc final

IF-ELSE STATEMENT

The if-else statement expresses simplest decision making.

The syntax is

if (expression)

statement1

elseopt

Statement2

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

132

Page 133: Cspc final

IF –ELSE STATEMENT

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

133

Page 134: Cspc final

NESTED IF-ELSE

When the if-else condition exists in another if-else condition, it is nested if-else.

Syntax

If (test condition-1)

{

if (test condition-2)

{

Statement-1; }

else {

Statement-2; }

}

else

{

Statement-3;

}

Statement- x;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

134

Page 135: Cspc final

IF-ELSE-IF STATEMENT For testing additional conditions if-else-if statements is

constructed.

If (condition-1)

Statement -1;

Else if (condition-2)

Statement-2;

Else if (condition-3)

Statement-3;

Else if (condition-n)

Statement –n;

Else

Default-statement;

Statement-x;31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

135

Page 136: Cspc final

SWITCH STATEMENTS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

136

Page 137: Cspc final

SWITCH STATEMENT

The switch statement is used to select one of several alternatives when the selection is based on the value of a single variable or an expression.

switch (controlling expression) {

case label1:

statement1

break;

case label2:

statement2

break; ……..

case labeln:

statementn

break;

default:

statementd; }

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

137

If the result of this controlling expression

matches label1, execute staement1 and then break

this switch block.

If the result matches none of all labels, execute the

default statementd.

Page 138: Cspc final

USE OF BREAK AND DEFAULT WITH SWITCH

Switch (exp)

{

case value-1:

block-1

break;

case value-2:

block-2

break;

…………….

…………….

default:

default-block

break; } statement-x;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

138

Page 139: Cspc final

PROGRAM LOOPS AND ITERATIONS:

In looping, a sequence of statements are executed until some

conditions for termination of the loop are satisfied.

Two segments are:

------- body of the loop

------- control statement

Depending on the position of the control statement in the loop,

A control structure may be either—

-------- entry controlled loop or

-------- exit controlled loop.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

139

Page 140: Cspc final

LOOP CONTROL STRUCTURES

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

140

True

Test

condition

?

Test

condition

?

Body of the

loop

Body of the

loop

False

False

True

EntryEntry

(b) Exit controlled loop(a) Entry controlled loop

Page 141: Cspc final

USE OF WHILE:

THE WHILE STATEMENT IS USED TO REPEAT A COURSE OF ACTION.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

141

Page 142: Cspc final

THE WHILE STATEMENT

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

142

Format

While (test condition)

{

Body of the loop

Syntax

Statement x;

While (condition)

{

statement block;

}

Statement y;

WAP to calculate the sum

of first 10 nos.

int i= 1, sum= 0;

while(i<=10)

{

sum = sum +1;

i= i+1;

}

printf(“\n sum =% d”, sum);

return 0;

}

OUTPUT

Sum= 55

Page 143: Cspc final

DO WHILE

DO STATEMENT

The do statement is a variant of the while statement that tests its condition at the bottom of the loop.

General Form of the do Statement-

do

statement

while (expr);

next statement

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

143

do

{

body of the loop

}

while (test-condition);

Page 144: Cspc final

EXAMPLE OF DO-WHILE STATEMENT

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

144

int i =1;

do

{

printf(“\n % d”, i);

i=i+1;

}

while(i<=10);

return 0;

}

The code will print nos

from 1 to 10.

Page 145: Cspc final

COMPARISON B/W WHILE, DO, FOR

WHILE DO FOR

while (...) {

...

continue;

...

cont: ;

}

do {

...

continue;

...

cont: ;

}

for (...) {

...

continue;

...

cont: ;

}

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

145

Page 146: Cspc final

FOR LOOPS

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

146

Page 147: Cspc final

SYNTAX OF FOR LOOP

for (initialization ; test-condition ; increment)

{

body of the loop

}

Example

for (i = 1; i<=n ; i++)

{

printf(“\n %d”, i);

}

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

147

Page 148: Cspc final

MULTIPLE LOOP VARIABLES

MLV are the loops which can be placed inside other loops.

Example:

………..

………..while(……..)

{

for(………)

{ …….

……..if (……..) goto end_of_program;

………

}

………

………

} end_of_program

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

148

Jumping out

of loops

Page 149: Cspc final

USE OF BREAK AND CONTINUE STATEMENTS.

The break statement causes an exit from the innermost enclosing

loop or switch statement.

The continue statement causes the current iteration of a loop to

stop and the next iteration to begin immediately.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

149

Page 150: Cspc final

DIFFERENCE B/W BREAK & CONTINUE

break continue

while (……)

{

if (condition)

break;

………..

}

……….

Transfers control out of the loop while.

Example

int i = 1;

while (i<= 10)

{

if (i==5)

break;

printf(“\n % d”, i);

i=i+1; }

return 0; }

while (……)

{

……….

if (condition)

continue;

………..

}

Transfers control to the condition

expression of the while loop.

Example

int i = 1;

for (i=1; i<=10; i++)

{

if (i==5)

continue;

printf(“\t % d”, i);

}

return 0; }31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

150

Page 151: Cspc final

THE GOTO STATEMENT

GOTO is used to branch unconditionally from one point to

another.

The general forms of goto & label statements are shown below:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

151

goto label;

………….

………….

………….

label;

Statement;

label;

statement;

………….

………….

………….

goto label;

Forward jump Backward jump

Page 152: Cspc final

FUNCTIONS:

A complex problem is often easier to solve by dividing it into

several smaller parts, each of which can be solved by itself.

This is called structured programming.

These parts are sometimes made into functions in C.

main() then uses these functions to solve the original problem.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

152

Page 153: Cspc final

Main() Function Calls Func1()

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

153

main()

{

…………

func1();

…………

return 0;

}

func1()

{

Statement block;

}

Main function

Function A Function B

Function B1 Function B2

Function c

Page 154: Cspc final

DEFINITION OF FUNCTIONS:

A function definition shall include the following

elements:

1. Function name;

2. Function type;

3. List of parameters;

4. Local variable declarations;

5. Function statements; and

6. A return statement.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

154

Function header

Function body

Page 155: Cspc final

FUNCTIONS WITH ARRAY

Example, the call

largest (a, n)

Will pass the whole array a to the called function.

The largest function header might look like:

float largest (float array [ ], int size)

The declaration of the formal argument array is made as follows:

float array [ ];

The pair of brackets informs the compiler that the argument array is

as array of numbers.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

155

Page 156: Cspc final

PASSING VALUES TO FUNCTIONS

Three rules to pass an array to a function:

A. The function must be called by passing only the name of the

array.

B. In the function definition, the formal parameter must be an array

type; the size of the array does not need to be specified.

C. The function prototype must show that the argument is an array.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

156

Page 157: Cspc final

RECURSIVE FUNCTIONS

Recursion: the ability of a subprogram to call itself.

Each recursive solution has at least two cases

base case: the one to which we have an answer

general case: expresses the solution in terms of a call to itself with a smaller

version of the problem.

For example, the factorial of a number is defined as the number times the product of all

the numbers between itself and 0:

N! = N * (N 1)!

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

157

Page 158: Cspc final

UNIT-4 ARRAYS

An array is a named collection of homogeneous items in which

individual items are accessed by their place within the collection.

An array is a collection of variables of the same type that are referred

to by a common name.

Eg.

product part numbers:

int part numbers[] = {123, 326, 178, 1209};

student scores:

int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};

characters:

char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

158

Page 159: Cspc final

INITIALIZATION OF ARRAY

Array – a set of elements all of the same type stored contiguously in memory – e.g.,

int A[25]; // 25 integers

struct Str B[15]; /* 15 objects oftype struct Str */

double C[]; /* indeterminate #

of doubles */

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

159

Page 160: Cspc final

ARRAY NOTATION

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

160

An array of size N is indexed from zero to N-1

79 87 94 82 67 98 87 81 74 91scores

The entire array

has a single name

Each value has a numeric index

This array holds 10 values that are indexed from 0 to 9

Page 161: Cspc final

MANIPULATING ARRAY ELEMENTS

Some other examples of array declarations:

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] codes = new char[1750];

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

161

Page 162: Cspc final

2D ARRAY

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

162

A one-dimensional array stores a list of elements

A two-dimensional array can be thought of as a table of

elements, with rows and columns

one

dimensiontwo

dimensions

Page 163: Cspc final

3D ARRAY

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

163

An array can be declared with multiple dimensions.

2 Dimensional 3 Dimensional

Multiple dimensions get difficult to visualize graphically.

int [][][] table3 = { { {1,2}, {3,4} },

{ {5,6,7} , {8}, {9,10}

}

};

Page 164: Cspc final

USING MULTI-DIMENSIONAL ARRAYS

An array can have many dimensions – if it has more than one

dimension, it is called a multidimensional array

Each dimension subdivides the previous one into the specified

number of elements

Each dimension has its own length constant

Because each dimension is an array of array references, the

arrays within one dimension can be of different lengths

these are sometimes called ragged arrays

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

164

Page 165: Cspc final

MULTIDIMENSIONAL ARRAY

Arrays with more than one index

number of dimensions = number of indexes

Arrays with more than two dimensions are a simple extension of

two-dimensional (2-D) arrays

A 2-D array corresponds to a table or grid

one dimension is the row

the other dimension is the column

cell: an intersection of a row and column

an array element corresponds to a cell in the table

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

165

Page 166: Cspc final

STRUCTURE:

A structure is a collection of one or more components (members).

Structures are called records in many other programming languages.

Members are known as fields.

Declaring a structure:-

struct {

char name[25];

int id, age;

char sex;

} s1, s2;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

166

Page 167: Cspc final

INITIALIZING A STRUCTURE:-

struct {

char name[25];

int id, age;

char sex;

}

s1 = { "Smith, John", 2813, 25, 'M'},

s 2 = { "Smith, Mary", 4692, 23, 'F'};

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

167

Page 168: Cspc final

ACCESSING THE MEMBERS OF A STRUCTURE:

The members of a structure are accessed by writing first the name of the

structure, then a period, then the name of the member:

struct student {

char name[25];

int id, age;

char sex;

} s;

strcpy(s.name, "Doe, John");

s.id = 18193;

s.age = 18;

s.sex = 'M';

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

168

Page 169: Cspc final

UNION:

A union is similar to a structure, except that its members are overlaid

(located at the same memory address).

A union is like a structure in which all members are stored at the

same address.

Example:

union {

int i;

double d;

} u;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

169

Page 170: Cspc final

ACCESSING THE MEMBER

The members of a union are accessed in the same way as members of a

structure:

u.i = 15;

or

u.d = 8.89;

Since u.i and u.d have the same memory address, changing the value of one

alters the value of the other.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

170

Page 171: Cspc final

ENUMERATED DATA TYPES

Enumeration Data Types

Declaration

Assignment

Operations

Looping with Enumeration

Types

A data type is

A set of values together with

A set of operations on those

values.

A name for the data type.

A set of values for the data

type.

A set of operations on the

values.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

171

Page 172: Cspc final

UNIT-5 POINTERS• In a generic sense, a “pointer” is anything that tells us where

something can be found.

– Addresses in the phone book

– URLs for webpages

-- Road signs

What actually ptr is?

ptr is a variable storing an address

ptr is NOT storing the actual value of i

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

172

Page 173: Cspc final

EXAMPLE OF POINTER

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

173

int i = 5; ptr

int *ptr;

ptr = &i;

printf(“i = %d\n”, i);

printf(“*ptr = %d\n”, *ptr);

printf(“ptr = %p\n”, ptr);

Output:

i = 5

*ptr = 5

ptr = effff5e0

address of i

5i

value of ptr

= address of

i

in memory

Page 174: Cspc final

POINTER APPLICATIONS IN C PROGRAMMING

Passing Parameter by Reference

Accessing Array element

Dynamic Memory Allocation :

Reducing size of parameter

Some other pointer applications :

--Passing Strings to function

--Provides effective way of implementing the different data

structures such as tree, graph, linked list

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

174

Page 175: Cspc final

FILE HANDLING: GOALS

By the end of this unit we should understand …

… how to open a file to write to it.

… how to open a file to read from it.

… how to open a file to append data to it.

… how to read strings from a file.

… how to write strings to a file.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

175

Page 176: Cspc final

DEFINITION

A file is a collection of related data that a computers treats as a single unit.

Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down.

When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

176

Page 177: Cspc final

OPERATIONS ON FILE

Opening a file

Reading data from a file

Writing data to a file

Closing a file

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

177

Page 178: Cspc final

OPENING A FILE

A file must be “opened” before it can be used.

FILE *fp;

:

fp = fopen (filename, mode);

fp is declared as a pointer to the data type FILE.

filename is a string - specifies the name of the file.

fopen returns a pointer to the file which is used in all

subsequent file operations.

mode is a string which specifies the purpose of opening the

file:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

178

Page 179: Cspc final

EXAMPLES

“r” :: open the file for reading only

“w” :: open the file for writing only

“a” :: open the file for appending data to it.

FILE *in, *out ;

in = fopen (“mydata.dat”, “r”) ;

out = fopen (“result.dat”, “w”);

FILE *empl ;

char filename[25];

scanf (“%s”, filename);

empl = fopen (filename, “r”) ;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

179

Page 180: Cspc final

CLOSING A FILE

After all operations on a file have been completed, it must be closed.

Ensures that all file data stored in memory buffers are properly written to

the file.

General format: fclose (file_pointer) ;

FILE *xyz ;

xyz = fopen (“test”, “w”) ;

…….

fclose (xyz) ;

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

180

Page 181: Cspc final

STANDARD C PREPROCESSORS

The C preprocessor executes before a program is compiled.

Some actions it performs are the inclusion of other files in the file being compiled,

definition of symbolic constants and macros, conditional compilation of program code

and conditional execution of preprocessor directives.

Preprocessor directives begin with # and only white-space characters and comments may

appear before a preprocessor directive on a line.

Macro definition

#define, #undef

File inclusion

#include

Conditional Compilation

#if, #ifdef, #ifndef, #elseif, #else

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

181

Page 182: Cspc final

#INCLUDE PREPROCESSOR DIRECTIVE

The #include preprocessor directive has been used throughout this text.

The #include directive causes a copy of a specified file to be included in place of the directive.

The two forms of the #include directive are:

#include <filename>#include "filename"

The difference between these is the location the preprocessor begins searches for the file to be included.

If the file name is enclosed in quotes, the preprocessor starts searches in the same directory as the file being compiled for the file to be included (and may search other locations, too).

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

182

Page 183: Cspc final

#DEFINE PREPROCESSOR DIRECTIVE: SYMBOLIC CONSTANTS

The #define directive creates symbolic constants—constants represented as symbols—

and macros—operations defined as symbols.

The #define directive format is

#define identifier replacement-text

When this line appears in a file, all subsequent occurrences of identifier that do not

appear in string literals will be replaced by replacement-text automatically before the

program is compiled.

Consider the following macro definition with one argument for the area of a circle:

#define CIRCLE_AREA( x ) ( ( PI ) * ( x ) * ( x ) )

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

183

Page 184: Cspc final

#ERROR AND #PRAGMA PREPROCESSOR DIRECTIVES:

The #error directive

#error tokens

prints an implementation-dependent message including the tokens specified in the directive.

The tokens are sequences of characters separated by spaces.

For example,

#error 1 - Out of range error

contains 6 tokens.

When a #error directive is processed on some systems, the tokens in the directive are displayed as an error message, preprocessing stops and the program does not compile.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

184

Page 185: Cspc final

PREPROCESSOR DIRECTIVES

Directive Function

#define Defines a macro substitution

#undef Undefines a macro

#include Specifies the files to be included

#ifdef Test for a macro definition

#endif Specifies the end of #if

#ifndef Tests whether a macro is not defined

#if Test a compile time condition

#else Specifies alternatives when #if test fails

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

185

Page 186: Cspc final

TYPES OF MACROS

Macro substitution is a process where an identifier in a program is

replaced by a predefined string composed of one or more tokens.

These directives can be divided into three categories:

Macro substitution directives

File inclusion directives

Compiler control directives

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

186

Simple MS

Argumented MS

Nested MS

Page 187: Cspc final

MACRO SUBSTITUTION

General form:

#define identifier string

1. SIMPLE MS:

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

187

MACRO IDENTIFIER STRING

#define COUNT 200

#define FALSE 0

#define SUBJECTS 5

#define PI 3.1415

#define CAPITAL “LUCKNOW”

Page 188: Cspc final

MACRO SUBSTITUTION

2. Argumented MS

The preprocessor permits us to define more complex & more useful

form of replacements.

It takes the form:

#define identifier (f1, f2,………….fn) string

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

188

MACRO IDENTIFIER STRING

#define MAX(a, b) (((a)>(b))?(a):(b))

#define MIN (a, b) (((a)<(b))?(a):(b))

#define ABS(x) (((x)>(0))?(x):(-x))

#define STREQ(s1, s2) (strcmp((s1,)(s2))==0)

#define STRGT(s1, s2) (strcmp((s1,)(s2))>0)

Page 189: Cspc final

MACRO SUBSTITUTION

Nested MS:

We can also use one macro in the definition of another macro.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

189

MACRO IDENTIFIER STRING

#define M 5

#define N M+1

#define SQUARE(x) ((x)* (x))

#define CUBE(x) (SQUARE (x) *(x))

#define SIXTH(x) (CUBE (x) * CUBE (x))

Page 190: Cspc final

CONDITIONAL COMPILATION:

Conditional compilation enables you to control the execution of preprocessor

directives and the compilation of program code.

Each of the conditional preprocessor directives evaluates a constant integer

expression.

Cast expressions, sizeof expressions and enumeration constants cannot be

evaluated in preprocessor directives.

The conditional preprocessor construct is much like the if selection statement.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

190

Page 191: Cspc final

CONDITIONAL COMPILATION

Structure similar to if

#if !defined( NULL )

#define NULL 0

#endif

Every #if must end with #endif

#ifdef short for #if defined( name )

#ifndef short for #if !defined( name )

Other statements

#elif – equivalent of else if in an if structure

#else – equivalent of else in an if structure

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

191

Page 192: Cspc final

PASSING VALUES TO THE COMPILER

CALL BY VALUE CALL BY REFERENCE

Formal parameters are local variables to callee.

Values of the actual parameters are copied to the formal parameters when function is called.

Conceptually simple.

Values of actual parameters are protected.Costly copying if parameters are large. Can only return 1 value.

Formal parameters are pointers to actual parameters.

Every use of the formal parameter is implicitly dereferenced.

Actual parameters must have l-values. (If not, either prohibit, or create temporary unnamed variable in caller).

Aliasing problem.

Can’t use in remote procedure call.

31-Dec-16ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI

192