0% found this document useful (0 votes)
372 views

CP Material

Computer programming covers 5 units: (1) an overview of computers and programming including hardware, software, algorithms and flowcharts; (2) selection statements, iteration statements, and other programming constructs; (3) pointers, functions, and dynamic memory allocation; (4) command line arguments, recursion, and variable length parameters; (5) structures, unions, enumerations, file I/O, and the preprocessor. The document provides details on computer hardware components, operating systems, application software, and the role of the CPU and memory. It also gives examples of input and output devices and discusses primary and secondary memory.

Uploaded by

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

CP Material

Computer programming covers 5 units: (1) an overview of computers and programming including hardware, software, algorithms and flowcharts; (2) selection statements, iteration statements, and other programming constructs; (3) pointers, functions, and dynamic memory allocation; (4) command line arguments, recursion, and variable length parameters; (5) structures, unions, enumerations, file I/O, and the preprocessor. The document provides details on computer hardware components, operating systems, application software, and the role of the CPU and memory. It also gives examples of input and output devices and discusses primary and secondary memory.

Uploaded by

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

COMPUTER PROGRAMMING

UNIT-I: Overview of computers and programming – Electronic computers then and now –
Computer hardware – Computer software – Algorithm – Flowchart – Software development method –
Applying the software development method.
Types, Operators and Expressions – Variable names – Data types and sizes – Constants –
Declarations – Arithmetic operators – Relational and Logical operators – Type conversions –
Increment and Decrement operators – Bitwise operators – Assignment operator and Expressions –
Conditional Expressions – Precedence and Order of evaluation.

UNIT-II : Selection statements – Iteration statements – Jump statements – Expression


statements – Block statements.
Single dimensional arrays – Generating a pointer to an array – Passing single dimension
arrays to functions – Strings – Two dimensional arrays – Indexing pointers – Array initialization –
Variable length arrays.

UNIT-III : Pointer variables – Pointer operators – Pointer expressions – Pointers and


arrays – Multiple indirection – Initializing pointers – Pointers to functions – C’s dynamic memory
allocation functions – Problems with pointers.
Understanding the scope of functions – Scope rules – Type qualifiers – Storage class
specifiers – Functions arguments – The Return statement.

UNIT-IV : Command line arguments – Recursion – Function prototypes – Declaring


variable length parameter lists.
Structures – Array of structures – Passing structures to functions – Structure pointers – Arrays
and structures within structures – Unions – Bit fields – Enumerations – typedef.

UNIT-V : Reading and Writing characters – Reading and writing strings – Formatted
console I/O – Printf – Scanf – Standard C Vs Unix File I/O – Streams and Files – File System basics –
Fread and Fwrite – Fseek and Random Access I/O – Fprintf() and Fscanf() – The standard streams –
The preprocessor directives #define and #include.

Text Books:

1. “The Complete Reference C” – Fourth Edition – Herbert Schildt – McGrawHill Education.


2. “The C Programming Language” Second Edition – Brain W.Kernighan – Dennis M.Ritchie –
Prentice Hall – India.
References:

1. Programming in c, Second Edition – Pradip Dey, Manas Ghosh, Oxford University Press.
2. “C From Theory to Practice” – George S. Tselikis – Nikolaos D. Tselikas – CRC Press.
3. “Programming with C” – R S Bichkar – University Press.
4. Programming in C and Data Structures” – J.R.Hanly, Ashok N. Kamthane and A.Ananda
Rao, Pearson Education.

*****

Page 1
UNIT – I

COMPUTER Computer is an electronic device that takes data as input from input
devices, process the instructions, and produces information as output on output devices.

(Data) (Information)
Input Devices Output Devices
Computer
(Input) (Output)

Raw content used for processing the instructions is known as data whereas processed
data is known as information.

Computer system is formed with the combination of two major components namely
hardware components and software components.

Computer Hardware:

Physical parts of the computer which are possible to touch and visible are known as
hardware components. The most important components are:

1. Input Devices
2. Output Devices
3. Central Processing Unit
4. Memory Unit

Central Processing Unit

Memory Unit

1. Input Devices:

Page 2
Input devices are used to submit data to the computer for processing the instructions.

Examples: Keyboard, Mouse, Trackball, Scanner, Microphone etc.,


Keyboard:
 Keyboard is an input device that allows users to enter textual data into
the computer system.
Mouse:
 Mouse is an input device that allows users to select elements on the
screen.
Scanner:
 Scanner is an input device that converts documents and images into
digitized data which is understandable by the computer system.
 The digitized data may produces black and white images, color images.

2. Output Devices:

Output devices are used to display information after processing the instructions by the
computer. The output information can be of visual or audio type depending on the type of
output device used.

Examples: Monitor, Speaker, Printer, Plotter etc.,

Monitor:

 Monitor is an output device used to display the information in visual


format.
Printer:

 Printer is an output device used to print data on the paper.


 Different types of printers are: Dot Matrix printers, Inkjet printers and
Laser printers.

3. Central Processing Unit:

Central processing unit (CPU) is main heart of the computer. CPU consists of three
major components namely
Arithmetic and Logical Unit (ALU)
Control Unit (CU)
Register Unit (RU)

Arithmetic and logical calculations are performed inside the arithmetic and logical
unit. Control unit is responsible for to follow up all the signals carried out by the computer.
CPU’s current instructions data values are stored temporarily inside a high-speed memory
location called register unit.

4. Memory Unit:

Page 3
Memory unit is used to store the data. Memory unit consists of an ordered sequence
of storage locations called memory cells and each memory cell has a unique address. The
data stored in a memory cell are called the contents of the cell.
A memory cell is grouping of smaller units called as bytes. Each byte is a
combination of 8 bits. Each bit is capable to the data as a binary digit 0/1.

ABBREVIATION NOTATION EQUIVALENT VALUE


Byte B 8 bits
Kilo Byte KB 1,024 Bytes
Mega Byte MB 1,024 Kilo Bytes
Giga Byte GB 1,024 Mega Bytes
Tera Byte TB 1,024 Giga Bytes
Peta Byte PB 1,024 Tera Bytes

Memory is divided into two parts as:

a) Primary Memory
b) Secondary Memory

a) Primary Memory: Primary memory is also known as main memory. It


stores programs, data and results.

Most common types of main memory (primary memory) are:

RAM (Random Access Memory) and


ROM (Read Only Memory).

ROM stores programs or data permanently. It allows only read operation. It’s is a
non-volatile memory. i.e., the data stored doesn’t disappear even though the system is
switched off.

RAM stores programs or data or results temporarily. It allows both read and write
operations. It’s a volatile memory. i.e., the data stored will be disappearing whenever the
power is switched off.

RAM is very expensive in cost and has limited storage capacity. So that large volume
of data is not possible to store in RAM. For storing huge amount of data, it is better to select
secondary storages devices.

b) Secondary Memory: Secondary storage devices are less expensive in


cost and have large storage capacity. Information stored in secondary storage devices are
organized in terms of files.
Examples: Hard disks, Floppy disks, Zip disks,
Compact disks (CD),
Digital video disks (DVD) etc.,
Primary storage devices and secondary storage devices are available in different
storage capacities like Bytes, Kilobytes, Megabytes, Gigabytes and Terabytes.

Page 4
First, the program must be transferred from secondary storage devices to main
memory before it can be executed. Programmer submits input data from input devices to
process the instructions. Those values are stored in the computer’s main memory.
Depending on the type of the instructions, CPU manipulates with the interaction of main
memory. Results values are again stored in main memory. Finally, the information in main
memory can be displayed on output devices and is possible to store in secondary storage
devices for future re-use.

Computer Software:

Software is a collection of programs. Each program consists of a set of instructions


that initiates the computer to perform some action.

Main components of computer software are:

1. Operating system
2. Application software
3. Package.

1. Operating System:

Operating system is a software that acts as interface between hardware components


and the user. Operating system is also known as System Software.

Examples: DOS, Windows, Unix etc.,

Main responsibilities of the operating system are:

 Communicating with the computer user


 Managing allocation of memory, processor time, and other resources
 Collecting input from input devices
 Conveying the output on output devices
 Accessing data from secondary storage devices
 Writing data to secondary storage devices etc.,

2. Application Software:

Collection of programs used to solve the given problem statement is called as


application software. Programs are designed based on the computer languages.

Examples: Pascal, FORTRAN, COBOL, C, C++, Java etc.,

Application software is further divided into two classes as:

 General purpose software

Page 5
 Application specific software

General purpose software can be used for more than one application.

Example: Word Processors, Database Management System, Computer-Aided


Design system etc.,

Application specific software can be used only for its intended purpose (Only for one
application).

Example: Accounts ledger system.

3. Packages:

Packages are used to store large volume of data for future use.

Example: Ms-office, SQL etc.,

***

ELECTRONIC COMPUTERS THEN AND NOW

 Computer was invented by CHARLES BABBAGE in 19th century.


 The first electronic computer was built in the later 1930s by Dr John Atanasoff
and Clifford Berry.
 The first general-purpose electronic digital computer named ENIAC
(Electronic Numerical Integrator And Computer) was designed in 1946.

In early days, vacuum tubes are the basic electronic components used for the
calculations. Later in next generations vacuum tubes are replaced with transistors then with
integrated circuits then with microprocessors.

Using today’s technology, the entire circuit can be packaged into a single component
known as micro-processor and known as CPU.

Based on the size and performance, computers are categorized into different ways as:

 Personal Computers : Used by a single person at a time.


Examples: Desktop Computers
Laptop Computers
Palmtop Computers etc.,
 Mainframes : Used in ATMs, Banking networks, Corporate
reservation systems, Air lines etc.,
 Super Computers : Used in Research laboratories, Weather
forecasting etc.,

Page 6
CHARACTERISTICS OF COMPUTERS

Important characteristics of computer is

 Speed and Accuracy


 Storage
 Versatile
 Diligence

Speed and Accuracy:

Computer performs complex calculation at a very high speed. Computer takes a few
micro/nano second to execute an operation.

1 millisecond = 1/1000 of second


1microsecond = 1/1000000 of a second
1 nanosecond = 1/000000000 of a second
1 Pico second = 1/1000000000000 of a second

Computer always gives 100% actual outputs (result), if the user provides
correct Input and Instructions. Since it is100% accurate, it is reliable.

Storage:

Computer can store a huge amount of data for the future use in auxiliary device like
floppy disk, hard disk or compact disk. The storing capacity of computer is expressed in
bytes.

Versatile:

Computers are being used in different fields such as offices, school, hospital, etc. to
perform various tasks.
Versatile means ability to perform various tasks & computer can capable to do so. A
computer can process any kind of data.

Diligence:

It is a capacity of performing repeated operation without any tiredness & any


mistakes.
A computer is capable of performing the required tasks continuously with the same
speed, accuracy & efficiency without any error.
APPLICATIONS OF COMPUTER

 Personal use
 School & College
 Graphic designing
 Audio/ Video mixing
 Entertainment
 Design & Modeling
Page 7
 Satellites & Networking System
 Research Center
 Hospitals
 Banks & other offices
 National & Multinational organizations
 Robotics etc.,

COMPUTER NETWORKS

Network is collection of systems that are communicated with each other. In network
main system is referred as server and other systems are referred as nodes. Networks are
classified into two types as:
 Local Area Network (LAN)
 Wide Area Network (WAN)

LAN is collection of computers that linked with each other. It is limited to a small
area like within the organization, building etc., In LAN technology systems can share
information and resources such as printers, scanners etc.,

A network that links many individual computers and local area networks over a large
geographic area is called a WAN.

Ex: Internet, Corporate companies etc.,

***

COMPUTER LANGUAGES

A program is a set of instructions that satisfy terminology of the specific languages.


Applications are solved by designing programs in any of the computer languages. In general,
computer languages are classified into three types as:

a) Machine language
b) Assembly language
c) High-level languages

a) Machine language:

Machine language is formed with the combination of machine codes which are
binary numbers either 0 or 1. Machine language is also known as binary language.

Example: 1001 0001 0010 1100


0010 1111 0101 0011

Page 8
At this stage, internal circuits of a computer are made of switches, transistors and
other electronic devices that can be in one of the two states as OFF state and ON state. In
case of computers OFF state is represented by 0 and ON state is represented by 1.

b) Assembly language:

Assembly language is formed with the combination of simple English words known as
mnemonic codes like ADD, SUB, MUL etc.,

Example: DATA SEGMENT


- - -
- - -
DATA ENDS
CODE SEGMENT
- - -
- - -
MOV AX, N1
MOV BX, N2
ADD AX,BX
- - -
- - -
CODE ENDS

C) High level languages:

High-level languages are formed with the combination of simple English sentences.
High level languages are easier to design compared to machine language and assembly
language.

Examples: Pascal, FORTRAN, COBOL, C, C++, Java etc.,

/* EXAMPLE PROGRAM IN C TO PERFORM ADDITION OF GIVEN TWO NUMBERS */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z;
clrscr();
printf(“\nEnter Two Values:”);
scanf(“%d%d”,&x,&y);
z=x+y;
printf(“\nResult = %d”,z);
}

Most of the users are interested to design programs in high-level languages. But a
computer can understood only machine language which consists of binary digits as either 0 or

Page 9
1. So, that a mediator is required to convert the given programming language into machine
codes and vice-versa. Such mediators are known as translators.

TRANSLATORS

A translator is a program that converts the given programming language from one
type to machine codes and vice-versa. The process of conversion is known as compilation.

(Source Program) (Object Program)


Different types of translators are:

 Assembler
 Compiler
 Interpreter

Assembler is a translator used to convert the assembly language program into


machine code and vice versa.

(Source Program) (Object Program)

Compiler is a translator used to convert the high level language programs into
machine code and vice-versa.

Data

Interpreter is also used as a translator for High level language programs. It takes one
statement of a high level language at a time and translates it into machine language which is
immediately executed.

Interpreter loaded
Source Program Result
computer

Page 10
Data

Compiler and Interpreter both are translators used to convert the high-level
language program into machine code and vice versa.

The main differences between both of them are:

 Compiler converts the entire source program into machine code and displays
errors if occurred. Whereas interpreter converts line by line of the source
program into machine code and displays errors immediately, if occurred.
 Designing of interpreters are easy compared to compilers.
 Compilers are more efficient than interpreters.

CREATING AND RUNNING PROGRAMS

The process of creating and running programs is falls into four stages as:

a) Writing and Editing programs


b) Compiling programs
c) Linking programs
d) Executing programs

a) Writing and Editing programs

The software used to write programs is known as a text editor. The text editor allows
to enter, change and store character data. It also allows some editing features to search and
locate replace statements, copy and paste commands, move statements from one place to
another place etc.,

After typing the program in the editor, save the file in the disk. This program is
known as a source file. Source file acts as an input to the compiler for the next stage.

b) Compiling Programs

The process of converting the source program from one language into machine code
is known as compilation. Compilation process is done with either compilers or interpreters.

In C language, C compiler includes two separate programs: Preprocessor and


Translator.

Preprocessor program scans the special instructions from the source program and
make substitutions in the code which is proper format for translator. After the preprocessor

Page 11
has prepared the code for compilation, translator converts the entire source program into
machine language.

While translating, compiler activates another program called debugger. Debugger


software is used to detect errors and bugs exist in the program. The process of detecting and
correcting errors is called debugging.

The output machine language code is known as object program. The object program
code is in machine codes 0’s and 1’s.

c) Linking Programs

Most of the high-level language programs consist of multiple modules. Linker is a


program used to arrange all the object codes of the modules into a single executable program.

Module 1 Object1
Translator
Code
Source Code
Linker

Module 2 Object2
Translator
Code
Source Code
Executable
Code

Linker assembles the various objects generated by the compiler in such a manner that
all the objects are accepted as a single program during executions.

d) Executing Programs

To execute the program, it is necessary to place it in the primary memory. For this,
operating system activates loader to load the executable program into the primary memory.
When everything is loaded, the program control begins execution. The program reads
data for processing either from the user or from a file. After processing the instructions,
output can be displayed on monitor or to a file.

Source File

Editor Format: Text

Compiler Page 12
Translates into
machine code
Errors Debugger

Success

Object File
Format: Binary

Linker Executable File

Format: Binary

Other Object File Loader


Format: Binary Copies executable file into
memory

Input Results

System

Here,

 First user creates a source file using programming language editors.

 Source files are compiled with compilers. Compiler translates the source program
from high level language into machine language program. While compilation, if any
errors are occurred, and then debugger activates and shows the bugs in the program.
Whenever, the program is successfully compile without out errors then an object file
with machine code is generated by the compiler.

 Linker is a program that linkers object file with other object codes and converts in
terms of executable code which is in binary format.

Page 13
 Loader is a program that loads this executable code into primary memory for
execution.

 Computer accepts the data from input devices and performs operations and produces
results.

***

ALGORITHM

An algorithm is a step-by-step procedure of solving the given problem statement.


Algorithms are designed by using pseudo code. Pseudo code is a language independent code.
All algorithms must satisfy the following characteristics.

 Input : Values submitted for the processing the instructions are


known as input values. Here, zero or more quantities are
externally supplied.

 Output : Values generated after processing the instructions are


known as output values. Here, at least one quantity must be
produced.

 Definiteness : Each instruction is in clear format.


Example: Add 10 to X (Valid)
Add 10 or 20 X (Invalid)

 Finiteness : If we trace out the instructions, the algorithm must


terminate after a finite sequence of steps.

 Effectiveness : Every instruction must be in basic format.

Basic rules followed while designing algorithms are:

 START / BEGIN statement is used to indicate beginning of the algorithm.


 STOP / END statement is used to indicate ending of the algorithm.
 READ / INPUT statement is used for input statements.
 WRITE / OUTPUT statement is used for output statements.
 ← Symbol is used to assign values to the variables.
 RETURN statement is used to return back from either procedure or function.

Examples: Design algorithm for the following problem statements.


Page 14
1. Addition of given two numbers.
2. Addition, Subtraction, Multiplication and Division of given two numbers.
3. Average of given three numbers.
4. Swapping of given two numbers.
5. Calculate simple interest (SI=(PTR)/100).
6. Gross Salary of an Employee Where HRA = 1500 and DA = 75% of Basic Pay
(GS=BPARY+HRA+DA).
7. Conversion of Fahrenheit Temperature into Celsius Temperature (C=(F-32)/1.8).
8. Calculate Area and Circumference of a Circle (Area= and Circumference=2∏r).

1. Addition of given two numbers 2. Addition, Subtraction, Multiplication and


Division of given two numbers

Step 1: START
Step 1: START Step 2: READ x, y
Step 2: READ x, y Step 3: Sum ← x + y
Step 3: sum ← x + y Sub ← x – y
Step 4: WRITE sum Mul ← x * y
Step 5: STOP Div ← x / y
Step 4: WRITE Sum, Sub, Mul, Div
Step 5: STOP

Algorithm Types:

In general, the steps in an algorithm can be divided into three basic categories as:

a) Sequence algorithm
b) Selection algorithm
c) Iteration algorithm

a) Sequence algorithm:

A sequence algorithm is a series of steps in sequential order without any break. Here,
instructions are executed from top to bottom without any disturbances.

Example: Algorithm for addition of given two numbers


Step 1: START
Step 2: READ x, y
Step 3: sum ← x + y
Step 4: WRITE sum
Step 5: STOP

b) Selection algorithm:

Page 15
Steps of an algorithm are designed by selecting appropriate condition checking is
called as selection algorithms. Selection algorithms are designed using selection control
statements such as IF, IF-ELSE, Nested IF-ELSE, ELSE-IF Ladder and SWITCH statements.

Example: Algorithm for maximum of given three numbers

Step 1: START
Step 2: READ x, y and z values
Step 3: IF x>y AND x>z THEN
Max ← x
ELSEIF y>z THEN
Max ← y
ELSE
Max ← z
ENDIF
Step 4: WRITE Max
Step 5: STOP

c) Iteration algorithm:

Steps of an algorithm are designed based on certain conditions and repeatedly


processed the same statements until the specified condition becomes false is called as
iteration algorithms. Iteration algorithms are designed using iterative control statements such
as WHILE, D0-WHILE and FOR statements.

Example: Algorithm for reverse of a given number

Step 1: START
Step 2: READ n value
Step 3: rev ← 0
Step 4: Repeat WHILE n > 0
k ← n MOD 0
rev ← rev * 10 + k
n ← n / 10
EndRepeat
Step 5: WRITE rev
Step 6: STOP

FLOWCHART

Pictorial/Graphical/Diagrammatic representation of an algorithm is called as a


flowchart. Flowcharts are designed by using some specific symbols. The most import
symbols used for designing flowcharts are:

START / STOP STATEMENTS: The symbol used to represent START / STOP


statements is “Oval”.
Page 16
Symbol :

Example : START STOP

INPUT / OUTPUT STATEMENTS: The symbol used to represent input statements and
output statements is “Parallelogram”.

Symbol :

Example : READ X,Y WRITE X,Y

FLOW LINES: The symbol used to represent data flow from one place to
another place is “Arrow”. Arrow symbols are also used to connect every two symbols in the
flowchart.

Symbol :

Example :
START

READ X

WRITE X

STOP

Page 17
PROCESS STATEMENTS: The symbol used to represent processing instructions is
“Rectangle”. Assignment statements and calculation statements are placed inside the
rectangle symbol.

Symbol :

Example : SUM ← X + Y

CONNECTOR SYMBOL: The symbol used to connect every two parts of the program
flow is “Circle”.

Symbol :

When we reach the end of a column or a page and still total chart is not finished. In
this case, at the bottom of flow use a connector to show that the flow continues at the top of
the next column or page.

Example : START A

:
: :
:
STOP
A

DECISION MAKING: The symbol used for representing decision parts of the program
is “Diamond”.

Symbol :

For this symbol, input is at one way and output is either of two ways.

Example :

F
Is
x>0

T
Page 18
Additional symbols that used for designing flowcharts are:

SYMBOL DESCRIPTION

DATA BASE

SUB ROUTINE

MULTIDOCUMENTS

IDEL OR WAITING STATE

EXTRACTS INDIVIDUAL SETS OF


DATA ITEMS

MERGE

MERGE AND EXTRACT ACTIONS

Examples: Design flowcharts for the following problem statements.

Page 19
1. Addition of given two numbers.
2. Addition, Subtraction, Multiplication and Division of given two numbers.
3. Average of given three numbers.
4. Swapping of given two numbers.
5. Calculate simple interest (SI=(PTR)/100).
6. Gross Salary of an Employee Where HRA = 1500 and DA = 75% of Basic Pay
(GS=BPARY+HRA+DA).
7. Conversion of Fahrenheit Temperature into Celsius Temperature (C=(F-32)/1.8).
8. Calculate Area and Circumference of a Circle (Area= and Circumference=2∏r).

SOFTWARE DEVELOPMENT METHOD

Modern projects are built using a series of interrelated phases commonly referred as
the software development life cycle (SDLC). The exact number and name of the phases of
SDLC are differing from one environment to other. One of the popular development life
cycles is Water fall model.

The main important phases in software development method are:

1. Analysis
2. Algorithm & Flowchart
3. Program Design
4. Compilation
5. Program Execution
6. Testing & Validation

1. Analysis: Analysis phase is also referred as specification requirement analysis.


In this phase, analyze the given problem to determine the input requirements and the
expected output.

Example: Problem Statement : Addition of given two values

Input requirements : Read two numbers as x and y


Expected output : Addition Value as x+y

2. Algorithm & Flowchart: Solution of the given problem statement is represented


interms of a step-by-step procedure is known as an algorithm. The steps of the algorithm is
represented in the form of a pictorial representation is called as a flowchart.

Example: Algorithm & Flowchart for addition of given two values


Step 1: START

Step 2: READ x, y START

Step 3: sum ← x + y
READ x, y
Step 4: WRITE sum

Step 5: STOP Page 20


sum ← x + y

WRITE sum

STOP

3. Program Design: The flowchart and algorithm steps developed in the previous
phase is converted into actual programs by selecting any programming languages like C, C++
etc.,

Example: Program for addition of given two values in C language

#inlcude<stdio.h>
#include<conio.h>
main()
{
int x,y,sum;
clrscr();
pritnf(“\nEnter Two Numbers:”);
scanf(“%d%d”,&x,&y);
sum = x+y;
printf(“\nTotal:%d”,sum);
}

4. Compilation: The process of converting the source program from one


language to machine language is called as compilation process. Typing and syntax errors are
found at the time of compilation process. These errors are occurred due to the usage of
wrong syntaxes for the statements.

Example:

In C language, the above program is compiled by pressing either F9 or Alt+F9 keys.

5. Program Execution: Successfully compiled program comes into execution phase. In


this phase, it may arise two types of problems such as run-time errors and logical errors.

Run-Time Errors: These errors may occur during the execution of the programs
even though the program is successfully compiled. The most common types of run time
errors are:
Example: Divide-By-Zero, Array-Out-Of-Bounds etc.,

Logical Errors: These errors may occur due to incorrect usage of the
instructions in the program. These errors are neither detected during compilation or
execution nor cause any stoppage to the program execution. They only produce unwanted
outputs.
Page 21
Logical errors are to be detected by analyzing the outputs for different possible inputs
that can be applied to the program.

Example:

In C language, the above program is executed by pressing Ctrl+F9 key.

6. Testing & Validation: In this phase, the program is tested by submitting proper
input values. And then program is validated with different valid inputs. With this, the
program is maintained for future re-use.

Example:

Input : Enter Two Numbers : 10 20


Output : Total : 30

Once testing and validation part is completed, software need to be maintained up-to-
date as company policies and government regulations etc., many organizations maintain
programs for number of years. This phase is referred as maintenance phase.

With completion of all the above phases, the program must be successfully produces
correct results.

Exercise: Apply software development method for the problem statement “ Reverse of a
given value”.

***
INTRODUCTION TO C LANGUAGE

C Language

ALGOL

BCPL

 ALGOL (Algorithmic Language) programming language is developed in the early


1960’s.
 In 1967, Martin Richards developed a language called Basic Combined Programming
Language (BCPL).
Page 22
 In 1970, Ken Thompson developed a simple language called B. B language was used
to develop the first version UNIX operating system.
 In 1972, Dennis Ritchie developed C language.

C is a structured programming language developed by Dennis Ritchie at AT&T’s


(American Telephone and Telegraph) Bell Laboratories of USA in 1972.

Note: In 1983, the American National Standards Institute (ANSI) began the definition of
standards for C. It was approved in December 1989.

Different ANSI versions are: C89, C95, C99, Embedded C (2008), C11 (C1X).

CHARACTERISTICS OF C LANGUAGE

1. C is a structured programming language.


2. C is a middle-level language.
Depending on the efficiency and performance, programming languages are
classified into two types as:
 Problem Oriented (or) High Level Languages: These languages
have been designed to improve the program efficiency while designing
programs.
Examples: FORTRAN, COBOL, PASCAL, C, C++ etc.

 Machine Oriented (or) Low Level Languages: These


languages have been designed to improve the machine efficiency while
designing programs.
Examples: Assembly language and Machine language.

C is a middle level language. Since, it was designed to improve both program


efficiency and machine efficiency.

3. C is a case-sensitive language.
In C language, both lower case and upper case characters are different.

4. C supports the concept of dynamic memory allocation.

5. C is a robust language. It contains rich set of built-in functions and operators that are
used to design complex programs.

C CHARACTER SET

Character set of C language contains Alphabets, Digits and Special Symbols.

Alphabets : Upper case characters A, B, - - - - -, Z


Lower case characters a, b, - - - - , z

Digits : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Page 23
Special Symbols : ~ ‘ ! @ # ^ & * ( ) [ ] { } + - / % “ , : ; < > etc.,

CONSTANTS AND VARIABLES

A constant is a quantity that doesn’t change during the program execution.


A variable is a quantity that can change during the program execution.

Example: 3X + Y = 20

Here, 3, 20 are constants and X, Y are variables.

KEYWORDS

The words which are predefined by the system compiler are called as keywords.
Keywords are also known as ”Reserved Words”. 32 keywords are available in C language.
Those are:

auto double if static break else


int struct case char const continue
default do enum extern float far
for goto long near register return
short signed switch typedef union
unsigned
void while

IDENTIFIER

An identifier is a name given to the variable, constant, array, structure etc. Identifiers
are defined by the users.

Example: sum
X etc.

Note: Words in C language are either keywords or identifiers.

DATA TYPES

The type of the value stored in a variable is called its data type. Data types of C
language can be classified into different types as:

Data Types

Primitive / Basic / Built-In Derived Data Types User-Defined


Data Types Data Types

Page 24
int Array Structure
char Function Union
float Pointer Enumeration
double

Primitive / Basic / Built-In Data Types:

C language supports char, int, float and double data types as primitive data types that
are used for storing characters, integers and real values.

char: char data type is used for storing character values.


int: int data type is used for storing integer values.
float: float data type is used for storing real values.
double: double data type is also used for storing real values.
When variables are declared with its appropriate data types, compiler allocates
sufficient amount of memory for the variables based on the type of the language.

The following table shows different primitive data types, memory size in bytes and
range of values possible to store.

DATA TYPE SIZE RANGE


(BYTES)
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
signed long int 4 -2147483648 to 2147483647
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

Note:

1. Derived and user-defined data types are collectively known as complex data types.
2. Complex data types are created with the combination of primitive data types.

Page 25
VARIABLES

Variable is a quantity that can change during the program execution.

Declaration of Variables: All variables must be declared before they are using in the
program. Declaration of a variable directs the compiler to allocate memory for the variables.
The declaration statement begins with data type followed by the name of the variables. The
general format of declaring variables is:

Syntax: DataType VariableName;


X P
Example: int X;
float P;
2 Bytes 4 Bytes
Multiple variables of the same data types can be declared in a single statement by separating
with comma operator as:

Syntax: DataType VariableName1, VariableName2, - - - , VariableNamen;


Example: int x,y,z;

Rules for Constructing Variable Names:

1. The first character in the variable name must be an alphabet.


2. A variable name is any combination of 1 to 8 alphabets, digits or underscores. Some
compilers allow variable names whose length could be up to 40 characters.
3. No comma or blank spaces are allowed within a variable name.
4. No special symbols other than underscore can be used in a variable name.
5. Keywords can’t use as variable names.

Initialization of Variables: Assigning a value to the variable at the time of its


declaration is called initialization. The general format for initializing a variable is:

Syntax: DataType VariableName = Value;


x
Example: int x = 40; 40
2 Bytes

Here, the right hand side value is assigned to the left hand side variable.

C-TOKENS

In a C program the smallest individual units are known as C tokens. C language has
six types of tokens as:

Page 26
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Special Symbols

1. Keywords: The words which are predefined by the system compiler are called as
keywords. Keywords are also known as ”Reserved Words”. 32 keywords are available in C
language.

2. Identifiers: The words which are defined by the user are known as identifiers.

3. Constants: A constant is a quantity that doesn’t change during the program


execution. C language supports several types of constants as:

Constants : Numerical Constants : Integer Constants


Real Constants
Character Constants : Character Constants
String Constants

Integer Constants: An integer constant refers to the sequence of digits. There are three
types of integers namely, Decimal Integers, Octal Integers and Hexa-Decimal Integers.

Decimal Integers consist of a set of digits 0 through 9.


Example: 23 -67 +678

Octal Integers consist of a set of digits 0 through 7 with a leading 0.


Example: 075 0123

Hexa-Decimal Integers consist of a set of digits 0 through 9, A to F (10 to 15) with a leading
0X.
Example: 0X79 0XA76E

Rules for Constructing Integer Constants:

 An integer constant must have at least one digit.


 It must not have a decimal point.
 It could be either positive or negative. Default sign is positive.
 No comma or blank spaces are allowed within an integer constant.

Real Constants: Real constant is a quantity containing fractional parts. Real constants
often called as Floating Point constants. Real constants could be written in two forms as:

Decimal Format: In decimal format the whole number is followed by a


decimal point and the fraction part.
Example: 21.7896 -1045.2341

Page 27
Exponential Format: The exponential format of real constant is as follows.
Example: 2179e-2

Character Constants: Character constant contains a single character enclosed within a pair of
single quotation marks.
Example: ‘A’ ‘9’ ‘#’

Rules for Constructing Character Constants:

 A character constant is a single alphabet, digit or a special symbol.


 The maximum length of a character constant can be only 1 character.

String Constants: A string constant is a sequence of characters enclosed in double


quotation marks. The characters may be letters, digits, special symbols and blank spaces.

Example: “PBR VITS” “23456” “786&$34”

4. Strings: A string is defined as a collection of characters.

Example: HELLO
5. Operators: Operator is a symbol that tells the compiler to perform some action.
Example: + - & || ~ etc.

6. Special Symbols: C language supports various special symbols that perform different
types of actions.

Example: # ; etc.

ESCAPE SEQUENCE CHARACTERS

C language supports some special back slash character constants which are known as
escape sequence characters that are used to format the output display. Some of them are:

CONSTANT MEANING

‘\a’ Bell Sound Character


‘\n’ New Line Character
‘\f’ Form Feed Character
‘\r’ Carriage Return Character
‘\t’ Horizontal Tab Character
‘\v’ Vertical Tab Character
‘\0’ Null Character

COMMENTS

Page 28
The lines beginning with /* and ending with */ are known as comments. These are
used in a program to enhance its readability and understanding. Comment lines are not
executable statements.

Example: /* SAMPLE C LANGUAGE PROGRAM */

LIBRARY FUNCTIONS

C language is accomplished by a collection of library functions that includes a


number of input and output functions.
Functions which are predefined by the system compiler are known as library
functions. Functions can be accessed anywhere within the program simply by writing the
function name followed by a list of arguments enclosed in parenthesis. Some functions do
not require any arguments, then place empty parenthesis.

Example: printf(“Hello”);
getch() ; etc.

HEADER FILES

C includes a collection of header files that provides necessary information in support


of the various library functions. These header files are entered in the program via #include
statement at the beginning of the program. The general format of including header files in
the current programs is:

Syntax: #include<HeaderFileName>
Or
#include “HeaderFileName”

Example: #include<stdio.h>
#include”stdio.h”

#include<conio.h>

Note: stdio.h (Standard Input Output Header File) is a header file that provides input and
output library functions.

clrscr(): It is a library function that is used to clear the screen contents.

conio.h (Console Input Output Header File) provides necessary information for
clrscr() function.

READING DATA FROM KEYBOARD

scanf() is an input statement. scanf() library function is used to provide values to the
variables as input data through the keyboard. The general format of scanf() function is:
Page 29
Syntax: scanf(“Control String”,&varname1, &varname2, . . , &varnamen);

Where,
The control string consists of the format of data being received. Control string is
formed with the combination of % symbol followed by the conversion characters of different
data types. Control strings for different data types are:

%d - int
%c - char
%lf - double
%f - float
%u - unsigned int
%ld - long int
%o - octal
%x - hexa decimal

The scanf() statement requires ‘&’ operator called address operator. The role of the
address operator is to indicate the memory location of the variables.
scanf() library function information is available in stdio.h header file.

Note: Commas, blank spaces or any other special symbol characters are not allowed in
between the control strings.

Example: scanf(“%d%d”,&x,&y);

DISPLAY DATA ON MONITOR

printf() is an output statement. printf() library function is used to display any data on
the monitor. The general format of printf() function is:

Syntax: 1. printf(“Control String”,varname1, varname2, . . , varnamen);


2. printf(“String”);

Where,
The control string consists of the format of data to be displayed. Control string is
formed with the combination of % symbol followed by the conversion characters of different
data types. Control strings for different data types are:

%d - int
%c - char
%lf - double
%f - float
%u - unsigned int
%ld - long int
%o - octal
%x - hexa decimal

printf() library function information is available in stdio.h header file.


Page 30
Note: In printf() library functions, it is possible to place any commas, blank spaces and
output format characters like escape sequence characters in the between the control strings to
display outputs in various formats.

Example: printf(“\n Result Value = %d”,sum);


printf(“HELLO”);

STRUCTURE OF A C PROGRAM

The general format of a c program is as follows:

Header Files
Function Prototypes
Global Variable Declarations
main()
{
Local Variable Declarations
-----
----- /* PROGRAMMING LOGIC */
-----
}

Here,

 Header files provide the necessary information that supports various library functions.
Header files are placed within the programs via #include statement.
 Function prototype is a declaration statement that describes the function name, list of
arguments, type, order of arguments and type of the value returned from the function.
 Variables declared inside the function are called local variables. These variables are
possible to use only within the functions.
 Variables declared outside the function are called global variables. These variables
are possible to use throughout the program.
 main() is a special function used by the C system to tell the compiler that where the
program execution starts. Every C program must have exactly one main function.
o Left curly brace ‘{‘ and Right curly brace ‘}’ indicates opening and ending of
the function implementation.
o All the statements between these two braces form as the function body.

Page 31
Example:

/* WRITE A C PROGRAM TO PRINT NAME OF YOUR COLLEGE */

#include<stdio.h>
#inlcude<conio.h>
main()
{
clrscr();
printf(“RSR COLLEGE”);
}

SAVE : F2
FILENAME : demo.c
COMPILE : F9 (OR) ALT F9
RUN : CTRL F9
RESULT VIEW : ALT F5
Examples: Design programs for the following problem statements.

1. Addition of given two numbers.


2. Addition, Subtraction, Multiplication and Division of given two numbers.
3. Average of given three numbers.
4. Swapping of given two numbers.
5. Calculate simple interest (SI=(PTR)/100).
6. Gross Salary of an Employee Where HRA = 1500 and DA = 75% of Basic Pay
(GS=BPARY+HRA+DA).
7. Conversion of Fahrenheit Temperature into Celsius Temperature (C=(F-32)/1.8).
8. Calculate Area and Circumference of a Circle (Area= and Circumference=2∏r).

***
OPERATORS AND EXPRESSIONS

An expression is formed with the combination of operators and operands. An


operator is a symbol that tells the compiler to perform certain mathematical and logical
manipulations. An operand is a data item on which the particular operation takes place.

Example: x + y = 10;

Here,
x, y and 10 are operands ; + and = are operators

In C language, operators can be classified into different categories such as:

1. Assignment operator
2. Arithmetic operators
3. Relational operators

Page 32
4. Logical operators
5. Increment & Decrement operators
6. Conditional operator
7. Bitwise operators
8. Special operators
9. Additional operators

1. Assignment Operator:

C language supports assignment operator as =. Assignment operator is used to assign


the result of an expression to any variables.

Syntax: VariableName = Expression;

Here, the right hand side value is assigned to the left hand side variable.
x y
Example: x = 10; 10 35
y = x+25;

/* Example program for assignment operator */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=40;
y=x+5;
printf(“\n X VALUE = %d”,x);
printf(“\n Y VALUE = %d”,y);
}
2. Arithmetic Operators:

C language supports arithmetic operators as +, -, *, /, and % operators used to perform


addition, subtraction, multiplication, division and remainder operations. Any expression that
forms with the combination of operands and arithmetic operators is termed as an arithmetic
expression.

OPERATOR MEANING

+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder

Page 33
 Arithmetic operators are binary operators. Since, they required two operands to
perform the operation.
 While performing division operation,
o If both operands are integers, result is also an integer value. Since, integer
division truncates fractional parts.
o If either operand is float, result is also a floating point value.
 Modulo operator (%) can’t be applied on floating point numbers.

/* EXAMPLE PROGRAM FOR ARITHMETIC OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y,sum,sub,mul,div,rem;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&x,&y);
sum=x+y;
sub=x-y;
mul=x*y;
div=x/y;
rem=x%y;
printf("\nAddition:%d",sum);
printf("\nSubtraction:%d",sub);
printf("\nMultiplication:%d",mul);
printf("\nDivision:%d",div);
printf("\nRemainder:%d",rem);
}
3. Relational Operators:

C language supports relational operators as <, >, <=, >=, == and != operators. These
operators are used to compare the given two operand values.
Any expression that forms with the combination of relational operators and operands
is termed as a relational expression.

OPERATOR MEANING
< Is Less Than
<= Is Less Than Or Equal To
> Is Greater Than
>= Is Greater Than Or Equal To
== Is Equal To
!= Is Not Equal To

The result of a relational expression is either 1 or 0. Where 1 stands for TRUE and 0
stands for FALSE.

Page 34
/* EXAMPLE PROGRAM FOR RELATIONAL OPERATORS */

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

main()
{
clrscr();
printf("\nResult 1:%d",14>78);
printf("\nResult 2:%d",14<78);
printf("\nResult 3:%d",25<=50);
printf("\nResult 4:%d",25>=50);
printf("\nResult 5:%d",100==100);
printf("\nResult 6:%d",100!=100);
}

4. Logical Operators:

C language supports logical operators as &&, || and ! Operators. Logical operators


are used to combine two or more relational expressions.
Any expression that forms with the combination of logical operators and operands is
termed as a logical expression. Logical expressions are also known as compound relational
expressions.

OPERATOR MEANING
&& Logical AND
|| Logical OR
! Logical NOT
Logical AND, Logical OR operators are binary operators and Logical NOT is a unary
operator.
Logical expressions are also produces the result values as either 1 or 0, depending on
truth tables supported by the operators.

Exp1 Exp2 Exp1 && Exp1 || Exp2 ! Exp1


Exp2
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0

Here,
 Logical AND produces result value as 1 (TRUE), if both operands are 1 (TRUE);
otherwise, result value is 0 (FALSE).
 Logical OR produces result value as 0 (FALSE), if both operands are 0 (FALSE);
otherwise, result value is 1 (TRUE).
 Logical NOT produces result value as 1 (TRUE), is the expression value is 0
(FALSE); otherwise, result value is 0 (FALSE).

Page 35
/* EXAMPLE PROGRAM FOR LOGICAL OPERATORS */

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

main()
{
clrscr();
printf("\nResult 1:%d",(14>78)&&(24<78));
printf("\nResult 2:%d",(14>78)||(24<78));
printf("\nResult 3:%d",!45);
}

5. Increment & Decrement Operators:

++ and – operators are called increment and decrement operators. These operators are
unary operands and required only one operand.

Increment Operator: Increment operator ++ is used to increment the operand value


by 1. Depending on the placement of operator with the operand, increment operator can be
utilized in two ways as : pre-increment and post-increment.

If ++ operator is placed before the operand, it is termed as pre-increment operation.


Here, first compiler increments the operand value by 1 and then result is assigned to the
variable.
x = x+1
Example: X = 7; y = ++x
Y = ++X; y=x
If ++ operator is placed after the operand, it is termed as post-increment operation.
Here, first compiler assigns the value to the variable and then operand is incremented by 1.

y=x
Example: X = 7; y = x++
Y = X++; x = x+1

/* EXAMPLE PROGRAM FOR INCREMENT OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=10;
y=++x;
printf("\nPre-Increment X Value:%d",x);
printf("\nPre-Increment Y Value:%d",y);
Page 36
x=45;
y=x++;
printf("\nPost-Increment X Value:%d",x);
printf("\nPost-Increment Y Value:%d",y);
}

Decrement Operator: Decrement operator -- is used to decrement the operand value


by 1. Depending on the placement of operator with the operand, decrement operator can be
utilized in two ways as : pre-decrement and post-decrement.

If -- operator is placed before the operand, it is termed as pre-decrement operation.


Here, first compiler decrements the operand value by 1 and then result is assigned to the
variable.

x = x-1
Example: X = 7; y = --x
Y = --X; y=x

If -- operator is placed after the operand, it is termed as post-decrement operation.


Here, first compiler assigns the value to the variable and then operand value is decremented
by 1.

y=x
Example: X = 7; y = x--
Y = X++; x = x-1

/* EXAMPLE PROGRAM FOR DECREMENT OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=10;
y=--x;
printf("\nPre-Decrement X Value:%d",x);
printf("\nPre-Decrement Y Value:%d",y);
x=45;
y=x--;
printf("\nPost-Decrement X Value:%d",x);
printf("\nPost-Decrement Y Value:%d",y);
}

Note: Increment and Decrement operators can’t be applied on constant values.

Page 37
6. Conditional Operator:

C language supports a ternary operator pair ? : as conditional operator. Any


expression that forms with the combination of conditional operator pair and operands is
termed as a conditional expression.

The general format of conditional operator pair is:

Syntax: Expression1 ? Expression2 : Expression3

Here,

 First Expression1 is evaluated. It produces either TRUE of FALSE.


 If Expression1 outcome is TRUE, then Expression2 is evaluated and becomes result
of the total expression.
 If Expression1 outcome is FALSE, then Expression3 is evaluated and becomes result
of the total expression.
i.e., either Expression2 or Expression3 is evaluated depending upon the
outcome of Expression1.

/* EXAMPLE PROGRAM FOR CONDITIONAL OPERATOR */

#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&A,&B);
Max=(A>B)?A:B;
printf("\nMaximum Number:%d",Max);
}

7. Bitwise Operators:

C language supports bitwise operators as &, |, ^, ~, << and >> operators.


These operators are used to manipulate data of the operands at bit level i.e., operations are
performed on corresponding bits of the given operands. Bitwise operators can operate only
on integer quantities such as int, char, short int, long int etc.,

Bitwise operators are classified into two types as:


i) Bitwise Logical Operators
ii) Shift Operators

i) Bitwise Logical Operators:

Bitwise AND (&), Bitwise OR (|), Bitwise Exclusive-OR (^) and One’s complement
(~) operators are known as bitwise logical operators. Bitwise AND, Bitwise OR and Bitwise
Exclusive-OR are binary operators and One’s complement is an unary operator.
Page 38
OPERATOR MEANING

& Bitwise AND


| Bitwise OR
^ Bitwise Exclusive OR
~ One’s Complement

Bit-Wise AND, Bit-Wise OR and Bit-Wise Exclusive OR follows the following bit
comparison tables.

Bit1 Bit2 Bit1 & Bit2 Bit1 | Bit2 Bit1 ^ Bit2

0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Here,
 Bit-Wise AND compares the corresponding bits of the operands and produces 1 when
both bits are 1; 0 otherwise.
 Bit-Wise OR compares the corresponding bits of the operands and produces 0 when
both bits are 0; 1 otherwise.
 Bit-Wise Exclusive OR compares the corresponding bits of the operands and
produces 0 when both bits are same; 1 otherwise.

For the above operations consider the following number conversion system for octal and
hexa-decimal numbers.

NUMBER OCTAL HEXADECIMAL

0 000 0000
1 001 0001
2 010 0010
3 011 0011
4 100 0100
5 101 0101
6 110 0110
7 111 0111
8 1000
9 1001
A - 10 1010
B – 11 1011
C – 12 1100
D – 13 1101

Page 39
E – 14 1110
F - 15 1111

Example:

1. X : 011 0000000000001001
Y : 027 0000000000010111 (Octal)

X&Y : 0000000000000001 :1
X|Y : 0000000000011111 : 37
X^Y : 0000000000011110 : 36

2. X : 0X7B 0000000001111011
Y : 0X129 0000000100101001 (Hexadecimal)

X&Y : 0000000000101001 : 29
X|Y : 0000000101111011 : 17B
X^Y : 0000000101010010 : 152

One’s Complement (or) Bit Negation operator is a unary operator that complements the bits
of the given operand. i.e., Bit 0 converted into Bit 1 and Bit 1 converted into Bit 0.

Example:

X : 0X7B 0000000001111011
~X : 1111111110000100 : FF84

ii) Shift Operators: Left shift operator (<<) and right shift operator (>>) are known
as shift operators.

Left shift operator (<<): Left shift operator (<<) is a binary operator that shifts bits of
the given operand towards left hand side. It requires two integer arguments. The first
argument is the value to be shifted and the second argument is the number of bits to be
shifted. The general format of left shift operator is:

Syntax: VariableName << NoOfBitPositions;

Example: Let X = 24
X << 1;

0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0

Page 40
MSB LSB
(Most Significant Bit) (Least Significant Bit)

Result value = 48.

 While performing left shift operations, there is a loss of data at MSB side.
 The vacated positions at LSB side are filled with zeros.
 For each shift value by the number of bits, the result value is equivalent to
multiplication by 2.

Right shift operator (>>): Right shift operator (>>) is a binary operator that shifts bits of
the given operand towards right hand side. It requires two integer arguments. The first
argument is the value to be shifted and the second argument is the number of bits to be
shifted. The general format of left shift operator is:

Syntax: VariableName << NoOfBitPositions;

Example: Let X = 24
X >> 1;

0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0

MSB LSB
(Most Significant Bit) (Least Significant Bit)

Result value = 12

 While performing right shift operations, there is a loss of data at LSB side.
 The vacated positions at MSB side are filled with zeros.
 For each shift value by the number of bits, the result value is equivalent to division
with 2.

/* EXAMPLE PROGRAM FOR SHIFT OPERATORS */

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

main()
{
int x;
clrscr();
x=24;
printf("\nLeft Shift Result:%d",x<<2);
x=24;
printf("\nRight Shift Result:%d",x>>2);
}

Page 41
8. Special Operators:

C language supports some special operators such as unary minus operator, comma
operator, sizeof operator, pointer operators (& and *) and member selection operators (. and
->).

a) Unary minus operator: Unary minus (-) operator changes sign of the given operand.
i.e., +ve sign is changed as –ve sign and –ve sign is changed as +ve sign.
Example: +10 → -10
-456 → +456

b) Comma Operator: Comma (,) operator is used to separate the operands from one
to another.
Example: int x,y;
c) sizeof Operator: sizeof operator is a compile time operator used to return the number of
bytes occupied by the given operand. The general format of sizeof operator is:

Syntax: sizeof(Operand);
Here,
The operand may be a variable, a constant or a data type.

/* EXAMPLE PROGRAM FOR SIZEOF OPERATOR */

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

main()
{
int k;
char p;
float z;
double t;
clrscr();
printf("\nSIZE OF K:%d Bytes",sizeof(k));
printf("\nSIZE OF P:%d Bytes",sizeof(p));
printf("\nSIZE OF Z:%d Bytes",sizeof(z));
printf("\nSIZE OF T:%d Bytes",sizeof(t));
printf("\nSIZE OF INT:%d Bytes",sizeof(int));
printf("\nSIZE OF CHAR:%d Bytes",sizeof(char));
printf("\nSIZE OF FLOAT:%d Bytes",sizeof(float));
printf("\nSIZE OF DOUBLE:%d Bytes",sizeof(double));
printf("\nSIZE OF INT VALUE:%d Bytes",sizeof(100));
printf("\nSIZE OF CHAR VALUE:%d Bytes",sizeof('A'));
printf("\nSIZE OF FLOAT VALUE:%d Bytes",sizeof(23.45f));
printf("\nSIZE OF DOUBLE VALUE:%d Bytes",sizeof(456.678));
Page 42
}

9. Additional Operators:

C language allows to combine assignment operator with other existing operators.

Arithmetic Assignment Operators:

Arithmetic assignment operators are formed with the combination of arithmetic


operators ( +, -, *, /, %) and the assignment operator (=).

C language supports arithmetic assignment operators as +=, -=, *=, /= and %=


operators.

Syntax:

Exp1 += Exp2 Equivalent To Exp1 = Exp1 + Exp2


Exp1 -= Exp2 Equivalent To Exp1 = Exp1 - Exp2
Exp1 *= Exp2 Equivalent To Exp1 = Exp1 * Exp2
Exp1 /= Exp2 Equivalent To Exp1 = Exp1 / Exp2
Exp1 %= Exp2 Equivalent To Exp1 = Exp1 % Exp2

Example:
a += 2 ↔ a = a+2
a -= 5 ↔ a = a-5
a *= 3 ↔ a = a*3
a /= 2 ↔ a = a/2
a %= 4 ↔ a = a%4

/* EXAMPLE PROGRAM FOR ARITHMETIC ASSIGNMENT OPERATOR */

#include<stdio.h>
#include<conio.h>
main()
{
int x;
clrscr();
printf("\nEnter X Value:");
scanf("%d",&x);
x+=6;
printf("\nX Value=%d",x);
x-=2;
printf("\nX Value=%d",x);
x*=4;
printf("\nX Value=%d",x);
x/=3;
printf("\nX Value=%d",x);
x%=5;
Page 43
printf("\nX Value=%d",x);
}

Classification

Depending upon the number of operands used with the operator, operators are
classified into three categories as:

a) Unary operators: Unary operator requies only one operand for implementing the
specified operation.
Example: Unary Minus operator, ++, --, ! etc.,

b) Binary operators: Binary operator requires two operands for implementing the
specified operation.
Example: +, - , *, /, %, &&, ||, < etc.,

c) Ternary operators:Ternary operator requires more than two operands for


implementing the specified operation.
Example: ?:

OPERATOR PRECEDENCE & ASSOCIATIVITY

In programming languages, expressions are evaluated based on precedence and


associativity of the operators.

Precedence: If more than one operator is available in a single statement, order of


evaluation depends on precedence of operators. Precedence refers to rank of operators that
follow order of evaluation.

Compiler follows order of evaluation as:

 Highest precedence operator is evaluated first before the lowest precedence operator.
 If two or more operators have same precedence, it follows associativity.

Example: X = 2;
Y = X + 10 * 2;
X Y
= + *
2 22
Y = X + 20

= +

Y = 22

Page 44
Associativity: Associativity refers to the direction of evaluations as from left to right
or from right to left.
Left-to-Right associativity evaluates the expression by starting on the left and moving
to the right.

Example: 3*8/4%4*5

*/%* L→R

24 / 4 % 4 * 5

/%* L→R

6%4*5

%* L→R

2*5

*
10

Right-to-Left associativity evaluates the expression by starting on the right and


moving to the left.

Example: Assume a = 8, b = 5 and c = 8

a += b *= c -= 5
+= *= -= R→L

a += b *= 3
*= -= R→L

a += 15
+=

a = 23

Operator precedence & Associatity Table:

RANK OPERATOR ASSOCIATIVITY

1 ( ) [ ] -> . ++ (POSTFIX) L to R
- - (POSTFIX)
2 ++ (PREFIX) - - (PREFIX) ! ~ R to L
sizeof unary minus &(Address)
*(Pointer)
3 */ % L to R
4 +- L to R

Page 45
5 << >> L to R
6 < <= > >= L to R
7 == != L to R
8 & L to R
9 ^ L to R
10 | L to R
11 && L to R
12 || L to R
13 ?: R to L
14 = += -= *= /= %= >>= <<= &= ^= | R to L
=
15 , (comma operator) L to R

Solve the following expressions

1. Z = ++X + Y-- - ++Y - X-- - X-- - ++Y - X—


Where X = 7 and Y = -3

Solution: X = 5, Y = -2 and Z = -15

2. Z = X++ + ++Y - X-- + --Y


Where X = 7 and Y = 9

Solution: X = 7, Y = 9 and Z = 18

3. Z = X++ * Y++ / ++X - --Y % X++


Where X = 5 and Y = 2

Solution: X = 8, Y = 2 and Z = 0

4. Y = X + Y++ + ++Y + ++X + Y++


Where X = 4 and Y = 3

Solution: X = 5 and Y = 24

/* EXAMPLE PROGRAM FOR OPERATOR PRECEDENCE & ASSOCIATIVITY */

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

main()
{
int y;
clrscr();
y=2+10*2;
printf("\nResult 1:%d",y);
y=3*8/4%4*5;
printf("\nResult 2:%d",y);
}
Page 46
TYPE CONVERSION (or) CASTING

The process of converting data item from one data type to another data type is called
type casting.
Conversion rank procedure is:

Real Values

float
double
Integer Values long double

int
short int
Character Values long int

char

Type casting can be classified into two types as:

1. Implicit Type Casting


2. Explicit Type Casting

1. Implicit Type Casting: If the operands are of different data types, the lower data type is
automatically converted into the higher data type by the compiler before the operation
proceeds. Such conversion is known as implicit type casting. Implicit type casting is also
known as automatic type conversion.
In implicit type casting, the result is in higher data type and there is no loss of data.

Example: double p = (2 * 3.5) + 4;


= 7.0 + 4;
= 11.0

2. Explicit Type Casting: Users can also be converting the data items from one
data type to another data type. Such conversion is known as explicit type casting.

For explicit type casting, the target data type placed within in parenthesis before the
data item.

The general format of explicit type casting is:

Syntax: (TargetDataType) Expression;


Here,
Expression may be a constant, variable, or any expression.
Page 47
In explicit type casting, there may be a loss of data which converting from higher data type
into lower data types.
Example:

int x=14, y=3;


float z;

z = x/y; z = (float) x/y;

z = 14/3; z = 14.000000/3;
z = 4.000000; z = 4.666667

/* EXAMPLE PROGRAM FOR TYPE CASTING */

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

main()
{
int x,y,z,total;
float avg;
clrscr();
printf("\nEnter Three Values:");
scanf("%d%d%d",&x,&y,&z);
total=x+y+z;
avg=(float)total/3;
printf("\nAverage Result:%f",avg);
}

***********

Page 48
UNIT – II
STATEMENTS

A statement is a syntactic construction that performs some action when the program is
executed. In C language, statements are classified into three types as:

1. Simple (or) Expression Statements


2. Compound (or) Block Statements
3. Control Statements

1. Simple (or) Expression Statements

A simple statement is a single statement that ended with a semicolon.

Example: int x,y;

2. Compound (or) Block Statements

Any sequence of simple statements can be grouped together and enclosed within a
pair of braces is termed as compound statements. Compound statements are also known as
block statements.

Example: {
int x=4, y=2, z;
z=x+y;
printf(“\nResult :%d”,z);
}

3. Control Statements

Generally, C program is a set of statements which are normally executed in sequential


order from top to bottom. But sometimes it is necessary to skip one or more statements,
execute the same statements repeatedly based on certain conditions and control is necessary
to change from location to another location. Such statements are called control statements.
In C language, control statements are classified into three categories as:

a) Selection (or) Decision Control Statements


b) Loop (or) Iterative Control Statements
c) Branch (or) Jump Control Statements

a) SELECTION (or) DECISION CONTROL STATEMENTS

Selection control statements are used to skip one or more statements depending on the
outcome of the logical test. Selection control statements are also known as decision control
statements. C language supports decision control statements as:

Two-way selection: i) if statement

Page 49
ii) if-else statement
iii) Nested if-else statement
Multi-way selection: iv) else-if ladder
v) switch statement

i) if statement: The general format of a simple if statement is:

Syntax: if(condition)
{
Block-I Statements
}
Statements-X;

Here,

 First condition is evaluated. It produces either TRUE or FALSE.


 If the condition outcome is TRUE, then Block-I Statements are executed by the
compiler. After executing the Block-I Statements, control reaches to Statements-X.
 If the condition outcome is FALSE, then Block-I Statements are skipped by the
compiler and control directly reaches to Statements-X.
 Block-I Statements are either simple or compound statements. If the statements are
simple statements, pair of braces is optional. If the statements are compound
statements, pair of braces is mandatory.

/* PROGRAM TO READ THE VALUE OF X AND PRINT Y AS Y=1 FOR X>0; Y=0
FOR X=0 AND Y=-1 FOR X<0 */

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

main()
{
int x,y;
clrscr();
printf("\nEnter x value:");
scanf("%d",&x);
if(x>0)
y=1;
if(x==0)
y=0;
if(x<0)
y=-1;
printf("\nY value is:%d",y);
}

ii) if-else statement: The general format of an if-else statement is:

Page 50
Syntax: if(condition)
{
Block-I Statements
}
else
{
Block-II Statements
}
Statements-X;

Here,
 First condition is evaluated. It produces either TRUE or FALSE.
 If the condition outcome is TRUE, then Block-I Statements are executed by the
compiler. After executing the Block-I Statements, control reaches to Statements-X.
 If the condition outcome is FALSE, then Block-II Statements are executed by the
compiler. After executing the Block-II Statements, control reaches to Statements-X.

/* PROGRAM TO CHECK WHETHER A GIVEN NUMBER IS EVEN OR ODD */

#include<stdio.h>
#include<conio.h>
main()
{
int x;
clrscr();
printf("\nEnter one value:");
scanf("%d",&x);
if(x%2= =0)
printf("\n%d is Even Number",x);
else
printf("\n%d is Odd Number",x);
}

iii) Nested if-else statement: An if-else statement is embedded within another if-else
statement such representation is called as nested if-else statement. The general format of
nested if-else statement is:

Syntax: if(condition1)
{
if(condition2)
{
Block-I Statements
}
else
{
Block-II Statements
}
}
else
Page 51
{
Block-III Statements
}
Statements-X;

Here,
 First condition1 is evaluated. It produces either TRUE or FALSE.
 If the condition1 outcome is TRUE, then control enters into condition2 section.
Condition2 is evaluated and produces either TRUE or FALSE.
o If Condition2 outcome is TRUE, then Block-I Statements are executed by the
compiler. After executing the Block-I Statements, control reaches to
Statements-X.
o If Condition2 outcome is FALSE, then Block-II Statements are executed by
the compiler. After executing the Block-II Statements, control reaches to
Statements-X.
 If the condition1 outcome is FALSE, then Block-III Statements are executed by the
compiler. After executing the Block-III Statements, control reaches to Statements-X.

/* PROGRAM TO PRINT LARGEST NUMBER FROM THE GIVEN THREE NUMBERS */

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

main()
{
int x,y,z;
clrscr();
printf("\nEnter Three Numbers:");
scanf("%d%d%d",&x,&y,&z);
if(x>=y)
{
if(x>=z)
printf("\nMaximum Number:%d",x);
else
printf("\nMaximum Number:%d",z);
}
else
{
if(y>=z)
printf("\nMaximum Number:%d",y);
else
printf("\nMaximum Number:%d",z);
}
}

Programs:

Page 52
1. Write a progam to read a value for X and print Y value as Y = 0 for X = 0, Y = -1 for
X < 0 and Y = 1 for X > 0.

iv) Else-If Ladder Statement: Else-If ladder statement is a multi-way statement. The
general format of else-if ladder statement is:

Syntax: if(condition1)
{
Block-I Statements
}
else if(condition2)
{
Block-II Statements
}
.
.
.
else if(conditionn)
{
Block-n Statements
}
else
{
ElseBlock Statements
}
Statements-X

Here,
 First condition1 is evaluated. It produces either TRUE or FALSE.
 If the condition1 outcome is TRUE, then Block-I Statements are executed by the
compiler. After executing Block-I Statements control reaches to Statements-X.
 If the condition1 outcome is FALSE, then control reaches to condition2 and is
evaluated. If condition2 outcome is TRUE, then Block-II Statements are executed by
the compiler. After executing Block-II Statements control reaches to Statements-X.
If condition2 outcome is FALSE, then control reaches to condition3 and so on.

/* PROGRAM TO PRINT LARGEST NUMBER FROM THE GIVEN THREE NUMBERS */

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

main()
{
int x,y,z;
clrscr();
printf("\nEnter Three Numbers:");
scanf("%d%d%d",&x,&y,&z);
if(x>=y&&x>=z)
Page 53
printf("\nMaximum Number:%d",x);
else if(y>=z)
printf("\nMaximum Number:%d",y);
else
printf("\nMaximum Number:%d",z);
}

Programs:

1. Write a progam to read a value for X and print Y value as Y = 0 for X = 0, Y = -1 for
X < 0 and Y = 1 for X > 0.
2. Write a program to print electric bill paid by the customer based on
Consumption Units Rate of Charge
0 – 100 Rs: 1.75
101 – 200 Rs: 2.25
201 – 300 Rs: 3.75
Above 300 Rs: 5.00
3. Write a program to print status of the student according to the following rules:
Average Marks Grade
0 to 39 FAIL
40 to 49 THIRD DIVISION
50 to 59 SECOND DIVISION
60 to 79 FIRST DIVISION
80 to 100 HONOUR

4. Write a program to calculate tax based on


a) If income is less than Rs:1,50,000/- then No tax.
b) If income is in the range Rs:1,50,001/- to 3,00,000/- then charge 10% tax.
c) If income is in the range Rs:3,00,001/- to 5,00,000/- then charge 20% tax.
d) If income is above Rs:5,00,000/- then charge 30% tax.

v) switch Statement: switch statement is also a multi-way decision that allows for
placing different block statements and execution depends on the result of the expression
value. The general format of switch statement is:

Syntax: switch(Expression)
{
case value1: Block-I Statements
break;
case value2: Block-II Statements
break;
.
.
.
case valuen: Block-n Statements
break;
default: DefaultBlock Statements
}
Statements-X
Page 54
Here,
 First Expression is evaluated and produces an integer value.
 Now, the expression value will be compared with case values value1, value2, ---,
valuen by the compiler. If any case value coincide with the expression value then that
particular block statements are executed until break statement is encountered.
 break is a branch control statement used to transfer the control out of the loop.
 If the expression value doesn’t match with any case value then default block
statements will be executed. Default block is optional block.
 Case values value1, value2, …. are either integer constants (or) character constants.
 Case labels must be unique. No two case labels should have the same name.
 Generally switch statements are used for creating menu programs.

/* CREATE A MENU PROGRAM TO SELECT A CHOICE AND PRINT MESSAGE AS 1 FOR


RED 2 FOR GREEN 3 FOR BLUE */

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

main()
{
int ch;
clrscr();
printf("\n1:RED\n2:GREEN\n3:BLUE");
printf("\nEnter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nRED SELECTED"); break;
case 2:printf("\nGREEN SELECTED"); break;
case 3:printf("\nBLUE SELECTED"); break;
default:printf("\nINVALID SELECTION");
}
}

Switch statement allows for executing same block statements for more than one case
with different syntax as:

Syntax: switch(Expression)
{
case value1:
case value2:
:
:
case valuen: Block Statements;
break;
:
default: defaultBlockStatements
}

Page 55
/* PROGRAM TO CHECK WHETHER A GIVEN CHARACTER IS VOWEL OR NOT */

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

main()
{
char ch;
clrscr();
printf("\nEnter A Character:");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':printf("\nVOWEL");
break;
default:printf("\nCONSONANT");
}
}

CONDITIONAL EXPRESSION

An expression formed with the combination of conditional operator pair ?: and


operands is termed as a conditional expression.

The general format of a conditional expression is:

Syntax: Expression1 ? Expression2 : Expression3

Here,

 First Expression1 is evaluated. It produces either TRUE of FALSE.


 If Expression1 outcome is TRUE, then Expression2 is evaluated and becomes result
of the total expression.
 If Expression1 outcome is FALSE, then Expression3 is evaluated and becomes result
of the total expression.
i.e., either Expression2 or Expression3 is evaluated depending upon the
outcome of Expression1.
 Conditional expression provides same functionality as if-else decision control
statement.

Page 56
/* EXAMPLE PROGRAM FOR CONDITIONAL EXPRESSION */

#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&A,&B);
Max=(A>B)?A:B;
printf("\nMaximum Number:%d",Max);
}

/* ALTERNATE PROGRAM WITH IF-ELSE STATEMENT */

#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&A,&B);
if(A>B)
Max=A;
else
Max=B;
printf("\nMaximum Number:%d",Max);
}
b) Loop (or) Iterative Control Statements

Loop: A loop is a sequence of instructions that is continuously repeated until a


certain condition is reached. Loop is also known as iteration.

Series of

Statements

Pre-test and Post-test loops: A loop can be either a pre-test loop or a post-test loop.

In a pre-test loop, the condition is checked before beginning of the each iteration. If
the condition outcome is TRUE, then associated statements are executed. The process is

Page 57
repeated until the test condition reaches to FALSE. Pre-test loop is also known as entry-
controlled loop.

FALSE
Con
diti
on
TRUE

Statements

In a post-test loop, first statements are executed. At the completion of statements


execution, the condition is evaluated. If the outcome of the test condition is TRUE, then
again same statements are executed; if the outcome of the test condition is FALSE, then the
loop terminates. Post-test loop is also known as exit-controlled loop.

Statements

FALSE
Cond
ition

TRUE

LOOP (or) ITERATIVE CONTROL STATEMENTS

Repetitive execution of one or more statements is called iteration, commonly known


as loop. Loop control statements are also known as iterative control statements.
Loop control statements are used for repetitive execution of statements based on the
outcome of a logical test. C language supports three loop control statements as:

i) while statement
Page 58
ii) do-while statement
iii) for statement

i) while statement: While statement is used for repetitive execution of statements more
than once.

The general format of a while statement is:

Syntax: while(condition)
{
- - -
- - - Block Statements
}

Here,
 First the condition is evaluated. It produces either TRUE or FALSE.
 If the condition is TRUE, then Block Statements will be executed by the compiler.
After executing the Block Statements, again control reaches to condition section and
is evaluated.
 The process is repeated until the condition becomes FALSE.
 When the condition reaches to FALSE, then the control is transferred out of the loop.

Flowchart:

Condition
F

T
Block Statements

/* PROGRAM TO PRINT FIRST N NATURAL NUMBERS */

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

main()
{
int i,n;
clrscr();
Page 59
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nNatural Numbers Are:");
i=1;
while(i<=n)
{
printf(" %d",i);
i=i+1;
}
}

ii) do-while statement: do-while is also a loop control statement used for
repetitive execution of statements. The general format of a do-while statement is:

Syntax: do
{
- - -
- - - Block Statements
- - -
}
while(condition);

Flowchart:

Block Statements

T F
is
Condition

Here,
 First the compiler executes Block statements and then enters into condition
section.
 Condition is evaluated and produces either TRUE or FALSE.
 If the condition outcome is TRUE, then again control enters into Block
Statement and is executed. This procedure is repeated until the condition
becomes FALSE.
 When the condition outcome reaches to FALSE, then the control is transferred
out of the loop.
Note: The main difference between while and do-while statements is do-while statement
executed the Block Statements at least once even though the condition becomes FALSE.
Since, compiler checks the condition after executing the Block Statements.

/* PROGRAM TO PRINT FIRST N NATURAL NUMBER USING DO-WHILE STATEMENT */


Page 60
main()
{
int i=1,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nNATURAL NUMBERS ARE:");
do
{
printf("%5d",i);
i=i+1;
}
while(i<=n);
}

iii) for statement: for is also a loop control statement used for repetitive execution of
statements. The general format of a for statement is:

Syntax: for(Initialization ; Condition ; Increment/Decrement)


{
- - -
- - - Block Statements
- - -
}

Flowchart:

Initialization

Condition F

Block Statements

Increment /
Decrement

Here,

Page 61
 First control reaches to Initialization section. Initialization starts with assigning a
value to the variable and executes only once at the start of the loop. Then control
enters into Condition section.
 Condition is evaluated and produces either TRUE or FALSE.
 If the outcome of the Condition is TRUE, then Block Statements are executed by the
compiler. After executing Block Statements, control reaches to Increment/Decrement
section.
 Increment/Decrement section updates the control variables. After updating the
control variable, again control reaches to Condition section and is evaluated.
 This procedure is repeated until the condition becomes FALSE.
 When Condition outcome becomes FALSE, then control is transferred out of the loop.

/* PROGRAM TO PRINT FIRST N NATURAL NUMBER USING FOR STATEMENT */


main()
{
int i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nNATURAL NUMBERS ARE:");
for(i=1;i<=n;i++)
printf("%5d",i);
}

Programs:

1. Write a program to read a list of numbers and print even and odd sum, even and odd
count from the list.
2. Write a program to print distance travelled by a vehicle in regular intervals of time
using the equation distance = ut + 0.5 a t2 ; Where, u is velocity, t is time period and a
is acceleration.

Features of for loop:

1. More than one variable can be initialized at a time in the for statement. In such
situations the variables are separated with comma operator. Similarly, the
Increment/Decrement section may also have more than part.
Ex: for(i = 1, j = 5 ; j >= 1 ; i++ , j--)
{
printf(“\n”);
printf(“%d \t %d”,i,j);
}

2. In condition section, it may have any compound relations.


Ex: for(i = 1, j = 5 ; i < = 5 && j >= 1 ; i++ , j--)
{
printf(“\n%d \t %d”,i,j);
}

Page 62
3. An important feature of for loop is that one or more sections (Initialization and
Increment/Decrement) can be omitted. In such situations, initialization has
been done before the for statement and the control variable is incremented or
decremented inside the loop.
Ex: i = 1;
j = 5;
for ( ; i<=5; )
{
printf(“\n%d \t %d”,i,j);
i++;
j--;
}

NESTED LOOPS

Loop control statements can be placed within another loop control statement. Such
representation is known as nested loops. In these situations, inner loop is completely
embedded within outer loop.

Example: for( i=1; i<=n; i++) outer loop


{
----
for( j=1; j<=i; j++) inner loop
{
---
}
----
}

Write C programs to generate the following formats

1) 1 2) 1 3) 3 2 1 4) *
12 22 21 **
123 333 1 ***

/* PROGRAM TO GENERATE PASCAL'S TRIANGLE */

#include<stdio.h>
#include<conio.h>
main()
{
int k,n=1,q=0,x,n;
clrscr();
printf("\nEnter how many Rows:");
Page 63
scanf("%d",&p);
printf("\nRESULT IS:\n");
while(q<p)
{
for(k=20-q;k>=1;k--)
printf(" ");
for(x=0;x<=q;x++)
{
if(x==0||q==0)
n=1;
else
n=(n*(q-x+1))/x;
printf(" %d",n);
}
printf("\n");
++q;
}
}

c) BRANCH (or) JUMP CONTROL STATEMENTS: Branch control statements


are used to transfer the control from one place to another place. C language provides three
branch control statements. Those are:

i) break statement ii) continue statement iii) goto statement

i) break statement: The break statement is used in loop control statements such as while,
do-while, for and switch statements to terminate the execution of the loop or switch
statement. The general format of break statement is:

Syntax: break;

When the keyword break is encountered inside any C loop, control automatically skip
entire loop and passes to the statements available after the loop.

/* Example program for break statement */


main()
{
int i,x,sum=0;
clrscr();
for(i=1;i<=5;i++)
{
printf("\nEnter Number %d:",i);
scanf("%d",&x);
if(x<0)
break;
sum=sum+x;
}
printf("\nTotal:%d",sum);
}

Page 64
ii) continue statement: The continue statement is used in while, do-while and for
statements to terminate the current iteration of the loop. The general format of continue
statement is:

Syntax: continue;

When the keyword continue is encountered inside any C loop, compiler skips the
remaining statements available after the continue statement and control reaches to next
iteration of the loop.

/* Example program for continue statement */

main()
{
int i,x,sum=0;
clrscr();
for(i=1;i<=5;i++)
{
printf("\nEnter Number %d:",i);
scanf("%d",&x);
if(x<0)
continue;
sum=sum+x;
}
printf("\nTotal:%d",sum);
}
iii) goto statement: The goto statement is used to alter the normal sequence of program
execution by transferring the control to some other part of the program. In its general form,
the goto statement can be written as:

Syntax: goto Label;

Where,
Label is an identifier used to specify the target statements to which control will be
necessary to transfer. The target statements must be labeled and the label must be followed
by a colon as:

Syntax: Label : Statements

Each label statement with in the program must have a unique name.
Depending on passing the control, goto statements can be classified as forward jump and
backward jump.

Forward jump Syntax: Backward jump Syntax:

___ Label : _ _ _
goto Label; _ __
___ __ _
___ goto Label;
Label : _ _ _ ___
Page 65
___ ---

/* Example program for FORWARD JUMP */ /* Example program for BACKWARD JUMP */

main() main()
{ {
int i,x,sum=0; int i,x,sum;
clrscr(); clrscr();
for(i=1;i<=5;i++) tp:
{ sum=0;
printf("\nEnter Number %d:",i); for(i=1;i<=5;i++)
scanf("%d",&x); {
if(x<0) printf(“\nEnter Number %d:”,i);
goto tp; scanf(“%d”,&x);
sum=sum+x; if(x<0)
} goto tp;
tp: sum=sum+x;
printf("\nTotal:%d",sum); }
} printf(“\nTotal :%d”,sum);
}
Additional Statements

i) return statement:

The return statement is used to return from a function. The general form of a return
statement is:

Syntax: return value;

If the function does not return any value, simply use the syntax as:

Syntax: return;

ii) exit() function:

The exit() function causes immediate termination of the entire program execution.
The general form of the exit() function is:
Syntax: exit();

The exit() function information is available in stdio.h header file.

***

ARRAYS

An array is a collection of homogeneous/similar data type elements that are stored in


successive memory locations. An array is referred by specifying the array name followed by
one or more subscripts, with each subscript is enclosed in square brackets. The number of

Page 66
subscripts determines the dimensionality of the array. Depending on the number of
subscripts used, arrays can be classified into different types as:
1. Single (or) One dimensional arrays
2. Double (or) Two dimensional arrays
3. Multi dimensional arrays

1. Single (or) One dimensional arrays

The general format of a single dimensional array is:


Syntax: datatype ArrayName[size];

Where,
 datatype specifies the type of the elements that will be stored in the array.
 ArrayName specifies the name of the array that follows same rules as a valid
identifier.
 size indicates the maximum number of elements that can be stored inside the array.

Example: int x[5];

For this, the memory allocation will be:

Index Values 0 1 2 3 4
x

1000 1002 1004 1006 1008 Addresses


Array Name

Note: In C language, array index starts from 0th location.

Let ‘m’ is the size of an array, the one dimensional array can be defined as – “One
dimensional array is a collection of m homogeneous data elements that are stored in m
memory locations”.

With the above example,

1. Each memory location size is 2 bytes. Since, the data type is int. Compiler allocates
a total of 10 bytes.
2. All memory locations share a common name as ‘x’.
3. An individual element of the array is accessed with index as:

0th index element as x[0],


1st index element as x[1] and soon.

/* EXAMPLE PROGRAM TO READ A ONE DIMENSIONAL ARRAY AND PRINT IT */

main()
{
int n,i,x[10];
clrscr();
printf("\nEnter how many elements:");
Page 67
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Element %d:",i+1);
scanf("%d",&x[i]);
}
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",x[i]);
}

INITIALIZATION OF SINGLE DIMENSIONAL ARRAYS

1) We can initialize the elements of the array in the same way as the ordinary variables
when they are declared. The general form of initializing the one dimensional array is:
Syntax: datatype ArrayName[size] = {List of Values};

Here, List of Values is separated by comma operator.


Example: int k[5] = {11,22,33,44,55}; /* 11 22 33 44 55 */

/* EXAMPLE PROGRAM FOR INITIALIZING SINGLE DIMENSTIONAL ARRAY */

main()
{
int x[5]={11,22,33,44,55}, i;
clrscr();
printf("\nArray Elements Are:");
for(i=0;i<=4;i++)
printf(" %d",x[i]);
}

2) While initializing elements, size may be omitted. In such cases, the compiler
allocates sufficient memory for all initialized elements.
Example: int k[ ] = {11,22,33,44,55}; /* 11 22 33 44 55 */

3) While initializing elements by specifying size, even one element is initialized; by


default remaining elements are initialized with ‘0’s by the compiler.
Example: int k[5 ] = {11,22}; /* 11 22 0 0 0 */

2. Double (or) Two dimensional arrays

The general format of a double dimensional array is:


Syntax: datatype ArrayName[size1][size2];

Where,
 datatype specifies the type of the elements that will be stored in the array.
 ArrayName specifies the name of the array that follows same rules as a valid
identifier.

Page 68
 size1specifies row size i.e., number of rows.
 size2specifies column size i.e., number of columns.

Example: int k[3][4];

For this, memory allocation will be:

0 1 2 3

K 1

For double dimensional arrays, memory is allocated in terms of table format


that contains collection of rows and columns. So, that double dimensional arrays are useful
for matrix representation of given elements.

Let ‘m’ is the row size and ‘n’ is the column size, then a double dimensional array can
be defined as – “Double dimensional array is a collection of m x n homogeneous data
elements that are stored in m x n successive memory locations”.

/* PROGRAM TO READ A DOUBLE DIMENSIONAL ARRAY AND PRINT IT */

main()
{
int m,n,i,j,x[10][10];
clrscr();
printf("\nEnter how many rows:");
scanf("%d",&m);
printf("\nEnter how many columns:");
scanf("%d",&n);
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&x[i][j]);
}

printf("\nArray Elements Are:");


for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf(" %d",x[i][j]);
}
}

INITIALIZATION OF DOUBLE DIMENSIONAL ARRAYS

Page 69
1) Like one-dimensional arrays, double dimensional arrays can also be initialized by
placing a list of values enclosed within braces as:
Syntax: datatype ArrayName[size1][size2] = {List of Values};

Here, List of Values is separated by comma operator.


Example: int k[2][3] = {11,22,33,44,55,66};

/* EXAMPLE PROGRAM FOR INITIALIZING DOUBLE DIMENSIONAL ARRAY */

main()
{
int x[2][3] = {11,22,33,44,55,66},i,j;
clrscr();
printf("\nArray Elements Are:");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf(" %d",x[i][j]);
}
}

2) List of values can also be initialized in the form of a matrix representation as:
Syntax: datatype ArrayName[size1][size2] = { {Row1 Values},
{Row2 Values},
----
--- -
};

Example: int k[3][3] = { {1,2,3}, {4,5,6}, {2,4,5} };

3) While initializing list of values, size1 (Row Size) may be omitted. In such cases,
the compiler allocates sufficient memory for all initialized elements.
Example: int k[ ][3] = { {1,2,3}, {4,5,6}, {2,4,5} };

4) At the time of initializing, even one element is initialized; by default remaining


elements are initialized with ‘0’s by the compiler.
Example: int k[2][3] = {1,2,3,4};
3. Multidimensional arrays

Multidimensional array uses three or more dimensions. The general format of a


multidimensional array is:
Syntax: datatype ArrayName[size1][size2] - - - - - - [sizen];
Example: int k[2][3][4];

The above example is a three dimensional array. Here, compiler allocates memory as
in terms of tables.

Let m1, m2, - - - , mn are the sizes, then a multidimensional array can be defined as –
“Multidimensional array is a collection of m1 x m2 x - - - - x mn homogeneous data elements
that are stored in m1 x m2 x - - - - x mn successive memory locations”.
Page 70
/* PROGRAM TO READ A MULTDIMENSIONAL ARRAY AND PRINT IT */

main()
{
int m,n,p,i,j,k,x[10][10][10];
clrscr();
printf("\nEnter how many Tables:");
scanf("%d",&m);
printf("\nEnter how many rows:");
scanf("%d",&n);
printf("\nEnter how many columns:");
scanf("%d",&p);
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<p;k++)
scanf("%d",&x[i][j][k]);
}
}
printf("\nArray Elements Are:");
for(i=0;i<m;i++)
{
printf("\n");
printf("\n");
for(j=0;j<n;j++)
{
printf("\n");
for(k=0;k<p;k++)
printf("%5d",x[i][j][k]);
}
}
}

INITIALIZATION OF MULTIDIMENSIONAL ARRAYS

1) The general form of initialization of a multidimensional array is:


Syntax: datatype ArrayName[size1][size2]- - - -[sizen] = {List of Values};

Here, List of Values is separated by comma operator.


Example: int k[2][3][2] = {11,22,33,44,55,66,77,88,99,10,11,12};

/* EXAMPLE PROGRAM FOR INITIALIZING MULTIDIMENSIONAL ARRAY */

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

main()

Page 71
{
int x[2][3][2]={1,2,3,4,5,6,7,8,9,10,11,12},i,j,k;
clrscr();
printf("\nArray Elements Are:\n\n\n");
for(i=0;i<2;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf("\n");
for(k=0;k<2;k++)
printf(" %d",x[i][j][k]);
}
}
}

2) List of values can also be initialized in the form of a table representation as:
Example: int k[2][3][2] = { { {1,2}, {4,5},{6,7}}, {{8,9},{10,11},{12,13}} };

3) While initializing list of values, size1 may be omitted. In such cases, the compiler
allocates sufficient memory for all initialized elements.
Example: int k[ ][3][2] = {11,22,33,44,55,66,77,88,99,10,11,12};

4) At the time of initializing, even one element is initialized; by default remaining


elements are initialized with ‘0’s by the compiler.
Example: int k[2][3][2] = {1,2,3,4};

***

STRINGS

A String is defined as “an array of characters”. The general form of declaration of a


string variable is:

Syntax: char StringName [size];

Ex: char str[10];

 Any group of characters defined between double quotation marks is a constant string.
Ex: “KAVALI”
 Each string is terminated by the null character (‘\0’), which indicates the end of the
string.
 When the compile assigns a character string to a character array, it automatically
supplies a null character at the end of the string.
 %s format specification is used to read and write a string.
 The ampersand ‘&’ symbol is not required before the variable name in scanf()
function while reading strings.

Page 72
 Main problem with the scanf() function is that it terminates its input on the first white
space it found.

/* EXAMPLE PROGRAM TO READ AND PRINT A STRING */

main()
{
char city[10];
clrscr();
printf("\nEnter City Name:");
scanf("%s",city);
printf("\nRESULT:%s",city);
}

/* PROGRAM TO READ A CHARACTER ARRAY AND PRINT ENTIRE STRING*/

main()
{
char city[10];
int i,n;
clrscr();
printf("\nEnter how many Characters:");
scanf("%d",&n);
printf("\nEnter %d Characters:",n);
for(i=0;i<n;i++)
scanf("%c",&city[i]);
city[i]='\0';
printf("\nRESULT:%s",city);
}

gets() and puts() functions: gets() and puts() functions are library functions used for to read
and write an entire line of text including blank spaces.

Syntax: gets(string);
puts(string);

Each of these library functions accepts a single argument as string. These functions
are defined in “stdio.h” head file. In gets(), the string will be entered from the keyboard and
terminated with a new line character.

/* EXAMPLE PROGRAM */

main()
{
char str[50];
clrscr();
printf("\nEnter a line of text:");
gets(str);
printf("\nRESULT:");
puts(str);
Page 73
}

****************

UNIT – III

FUNCTIONS: A function is a self-contained program segment that carries out some


specific, well-defined task. C program consists of one or more functions. One of these
functions must be called by main() function. Program execution will always begin by
carrying out the instructions in the main() function. Additional functions will be subordinate
to the main() function.
If a program contains multiple functions, their definitions may appear in any order
and they must be independent of one another i.e., one function definition can’t be embedded
within another.

Ex: main() main()


{ {
-- --
-- --
Statement-x call set
-- --
-- --
Statement-x call set
-- --

Page 74
} }
set()
{
--
}
Advantages:

1. It avoids redundant repeated code.


2. It makes program significantly easier to understand and maintain by breaking them up
into easily manageable parts.
3. main program can consist of a series of function calls rather than countless lines of
code. It can be executed any number of times.
4. Well-defined and written functions may be reused in multiple programs.
5. Another main advantage is that different programmers working on one large project
can divide the workload by writing different functions.

FUNCTION TYPES

C functions are classified into two types as: Library functions and User-defined
functions.

a) Library functions: Functions that are predefined by the compiler are known as
library functions.
Ex: scanf(), printf(), getch(), getche(), etc.,

For all the library functions, definitions and necessary information is available in
header files. Some of the important header files are:
stdio.h - Standard Input and Output header file
conio.h - Console Input and Output header file
stdlib.h - Standard library header file
ctype.h - Character type header file
math.h - Mathematical header file

ctype.h - Character type header file

ctype.h header file provides several library functions used for character testing and
conversions.

Functions:

1. isalnum(): Syntax: isalnum(ch)


Where, ch is a character type variable.
Function determines whether the given argument is alpha numeric or not. If the
character is alpha numeric, it returns a non-zero value that represents TRUE; otherwise, it
returns ‘0’ that represents FALSE.

2. isalpha(): Syntax: isalpha(ch)

Page 75
Function determines whether the given argument is alphabet or not. If the character is
alphabet, it returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.

3. isdigit(): Syntax: isdigit(ch)


Function determines whether the given argument is digit or not. If the character is
digit, it returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.

4. isspace(): Syntax: isspace(ch)


Function determines whether the given argument is space or not. If the character is
space, it returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.

5. islower(): Syntax: islower(ch)


Function determines whether the given argument is in lowercase or not. If it is in
lowercase, then returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.

6. isupper(): Syntax: isupper(ch)


Function determines whether the given argument is in uppercase or not. If it is in
uppercase, then returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.

7. tolower(): Syntax: tolower(ch)


Function converts the given argument from upper case to lower case.

8. toupper(): Syntax: toupper(ch)


Function converts the given argument from lower case to upper case.

Programs

1. Write a program to count number of alphabets, digits, words and special symbols of a given line.
2. Write a program to convert lower case characters into upper case characters and vice-versa of a
given line.
3. Write a program to accept a line and print number of vowels, consonants, blank spaces, digits and
special characters.

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

main()
{
char str[100];
int i,nv,nc,nb,nd,sp;
clrscr();
nv=0;
nc=0;
nb=0;
nd=0;

Page 76
sp=0;
printf("\nEnter A Line=");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(isalpha(str[i]))
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||
str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
nv=nv+1;
else
nc=nc+1;
}
else if(isspace(str[i]))
nb=nb+1;
else if(isdigit(str[i]))
nd=nd+1;
else
sp=sp+1;
}
printf("\n Number of Vowels = %d",nv);
printf("\nNumber of Consonants = %d",nc);
printf("\nNumber of Blank Spaces = %d",nb);
printf("\nNumber of Digits = %d",nd);
printf("\nNumber of Special Characters = %d",sp);
}

math.h - Mathematical header file

math.h header file provides several library functions used for mathematical operations.

1. sin(): Syntax: sin(d)

Where, d is a double type argument.


Function receives a double type argument and returns the sine value as double.
Ex: printf(“%lf”, sin(45));

2. cos(): Syntax: cos(d)


Function receives a double type argument and returns the cosine value as double.
Ex: printf(“%lf”, cos(45));

3. tan(): Syntax: tan(d)


Function receives a double type argument and returns the tangent value as double.
Ex: printf(“%lf”, tan(45));

4. log(): Syntax: log(d)


Function receives a double type argument and returns the natural logarithm (base e)
value as double.
Ex: printf(“%lf”, log(10));

5. log10(): Syntax: log10(d)


Page 77
Function receives a double type argument and returns the logarithm (base 10) value as
double.
Ex: printf(“%lf”, log10(10));

6. sqrt(): Syntax: sqrt(d)


Function receives a double type argument and returns the square root value as double.
Ex: printf(“%lf”, sqrt(81));

7. pow(): Syntax: pow(d1, d2)


Function receives two double type arguments and returns the d1 raised to the d2
power value as double.
Ex: printf(“%lf”, pow(3,4));

8. exp(): Syntax: exp(d)


Function receives a double type argument and returns the e to the power d value as
double.
Ex: printf(“%lf”, exp(4));

9. ceil(): Syntax: ceil(d)


Function receives a double type argument and returns the value rounded up to the next
lowest integer as double.
Ex: printf(“%lf”, ceil(3.85));

10. floor(): Syntax: floor(d)


Function receives a double type argument and returns the value rounded down to the
previous highest integer as double.
Ex: printf(“%lf”, floor(3.85));

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

main()
{
float a,b,c,r1,r2,dis;
clrscr();
printf("\nEnter a,b and c values:");
scanf("%f%f%f",&a,&b,&c);
dis=(b*b)-(4*a*c);
if(dis = =0 )
{
printf("\nROOTS ARE REAL AND EQUAL");
r1=-b/(2*a);
r2=-b/(2*a);
printf("\nROOT 1 = %.2f",r1);
printf("\nROOT 2 = %.2f",r2);
}
else if(dis>0)
{
Page 78
printf("\nROOTS ARE REAL AND DIFFRENT");
r1=(-b+sqrt(dis))/(2*a);
r2=(-b-sqrt(dis))/(2*a);
printf("\nROOT 1 = %.2f",r1);
printf("\nROOT 2 = %.2f",r2);
}
else
printf("\nROOTS ARE IMAGINARY");
}

b) User-Defined functions: User-defined functions are defined by the user


according to their requirements. While defining functions, function places are classified into
three parts as:
1. Function prototype
2. Function call
3. Function definition

1. Function prototype: Function prototype specifies the declaration statement of the


function that intimates to the compiler about function information before executed it.
Function prototype includes function name, list of arguments and type of the data
returned. The general format of a function prototype is:

Syntax: ReturnType FunctionName (datatype arg1, - - - - - - - , datatype argn);

Where,
 FunctionName is the name given to the function, which allows the same rules as valid
identifier.
 ReturnType specifies the type of the data returned from the function to calling
function.
 datatype arg1, - - - - are the arguments used to perform the function implementation.
Argument names arg1, -- , argn are optional.

Example: int Fact(int); (or) int Fact(int x);

2. Function call: The function call statement invokes the function by passing
arguments. The arguments which passed at the function call are called “actual arguments”.
The general format of a function call is:

Syntax: VariableName = FunctionName(var1, var2, --- varn);

Where, var1,----, varn are actual values passed to the function definition.

Note: The function name, type, number and order of arguments listed in the function call
statement must match with that of the function prototype and function definition.

Example: p = Fact(5);

Page 79
3. Function body (or) definition: Function definition contains implement code of
the function. The general format of a function definition is:

Syntax: ReturnType FunctionName (datatype arg1, - - - - - - - , datatype argn)


{
Local Variable Declarations
--
-- (Implementation Code)
--
return value;
}
Where,
 arg1, arg2, --- , argn arguments are known as “formal arguments”. List of values
passed from the function call are temporarily stored in these formal parameters.
 Variables declared in the function definitions are called local variables.
 After completing implementation of the function, it should return a value to the
calling function with a return statement.
 The syntax of a return statement is:
Syntax: return value;
If the function should not return any value, then simply placed as:
Syntax: return;
Or omit the statement. If we omit the statement, it is automatically invokes by the
compiler.

Example: int Fact(int k)


{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}

Now, the total representation can be placed as:

---
Function proto type
- --
main()
{
--
Function call Calling Function
--
}
Function definition
{
-- Called Function
--
}

Page 80
/* PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER USING FUNCTIONS */
#include<stdio.h>
#include<conio.h>
int Fact(int);
main()
{
int p,n;
clrscr();
printf("\nEnter a Value:");
scanf("%d",&n);
p=Fact(n);
printf("\nFactorial Value:%d",p);
}
int Fact(int k)
{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}

FUNCTION CATEGORIES

Depending on whether arguments are passed or not and function returns any value or
not, functions are classified into different categories as:

Case 1: Functions without arguments and without return value


Case 2: Functions with arguments and without return value
Case 3: Functions without arguments and with return value
Case 3: Functions with arguments and with return value

Case 1: When a function has no arguments, it does not receive any data from the
calling function. Similarly when it does not return any value, the calling function does not
receive any data from the called function.
Note: If the function does not return any value, return type must be void.

/* EXAMPLE PROGRAM */

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

void sum();

main()
{
clrscr();
sum();
}
void sum()
Page 81
{
int x,y,z;
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=x+y;
printf("\nResult = %d",z);
}
Case 2: In this case, calling function send data to the called function. But, called
function does not return any value after completing function implementation.

/* EXAMPLE PROGRAM */

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

void sum(int,int);

main()
{
int x,y;
clrscr();
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
sum(x,y);
}
void sum(int p,int q)
{
int z;
z=p+q;
printf("\nResult = %d",z);
}

Case 3: In this case, calling function does not send data to the called function. After
implementation of the function, called function return value to the calling function.

/* EXAMPLE PROGRAM */

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

int sum();

main()
{
int p;
clrscr();
p=sum();
printf("\nResult = %d",p);

}
int sum()
{
int x,y,z;

Page 82
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=x+y;
return z;
}

Case 4: In this case, calling function send data to the called function and called
function also returns some value to the function call after completing the function
implementation.

/* EXAMPLE PROGRAM */

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

int sum(int,int);

main()
{
int x,y,z;
clrscr();
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=sum(x,y);
printf("\nResult = %d",z);
}
int sum(int p,int q)
{
int t;
t=p+q;
return t;
}

Programs:

1. Write a program to calculate npr value


2. Write a program to calculate ncr value

INTER FUNCTION COMMUNICATION

The data flow between the calling and called functions can be divided into three
strategies as:

 A downward flow from the calling function to the called function.


 An upward flow from the calling function to the called function.
 A bi-directional flow in both directions.

Downward flow

Calling Function In downward communication, the calling


function sends data to the called function. After
Page 83
Called Function
implementation of the function, the called function does
not send any values to the calling function.

Upward flow

Calling Function In upward communication, the calling


function does not send any data to the called function.
After implementation of the function, the called
function sends data values to the calling function.
Called Function

Bi-directional flow

Calling Function In bi-directional communication, the


calling function sends data to the called function. After
implementation of the function, the called function also
sends data values to the calling function.
Called Function
NESTED FUNCTIONS

Functions can also be included within another function. Such representation is known
as nested functions.

Syntax: main() Fun1() Fun2()


{ { {
-- -- --
-- Fun2(); --
Fun1(); -- }
-- }
}

/* EXAMPLE PROGRAM FOR NESTED FUNCTIONS */

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

void fun1();
void fun2();

main()
{
clrscr();
printf("\nMAIN STARTS");
fun1();
printf("\nMAIN ENDS");
}
void fun1()

Page 84
{
printf("\nFUNCTION 1 STARTS");
fun2();
printf("\nFUNCTION 1 ENDS");
}
void fun2()
{
printf("\nFUNCTION 2 STARTS");
printf("\nFUNCTION 2 ENDS");
}

RECURSION

A function calls itself is called recursion and the function is called as recursive
function. The main advantage of recursion is to avoid the length of the code.

Ex: main()
{
--
main();
--
}

Recursion can be classified into two types as:


1. Direct recursion
2. Indirect recursion

1. Direct recursion: A function calls itself is known as direct recursion.

Ex: void sum()


{
--
sum();
--
}

2. Indirect recursion: A function calls another function, which initiates to call of the initial
function is known as indirect recursion.

Ex: void sum() void call()


{ {
--- ----
call(); sum();
--- ----
} }

Note:
1. Recursion uses more memory compare to non-recursive functions.

Page 85
2. While using recursion, control may falls into infinite loop. This disadvantage can be
avoided by placing a return statement associated with if-else statement somewhere to force
the control without calling recursive call.

So that in recursion concept, two types of conditions must be placed. Those are base
condition and recursive condition. Base condition avoids the recursive call and recursive
condition calls the recursive procedure.

/* PROGRAM TO PRINT FACTORIAL OF A GIVEN NUMBER USING RECURSION */

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

int Fact(int);
main()
{
int p,k;
clrscr();
printf("\nEnter a Value:");
scanf("%d",&k);
p=Fact(k);
printf("\nFactorial Value:%d",p);
}

int Fact(int n)
{
if(n= =1)
return 1;
else
return n*Fact(n-1);
}

LOCAL VARIABLE Vs GLOBAL VARIABLE

Variables declared inside the function definition or block is called local variables.
Local variables can be used by only that particular function or block where it was defined.
Variables declared outside the function definition are called global variables. Global
variables can be used by any function at any time.

/* EXAMPLE PROGRAM FOR LOCAL VARIABLES */

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

void change();
main()
{
int x=10;
clrscr();
printf("\nValue 1:%d",x);

Page 86
change();
printf("\nValue 2:%d",x);
}
void change()
{
int x;
x = 20;
printf("\nValue 3:%d",x);
}

/* EXAMPLE PROGRAM FOR GLOBAL VARIABLE */

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

void change();
int x=10;

main()
{
clrscr();
printf("\nValue 1:%d",x);
change();
printf("\nValue 2:%d",x);
}
void change()
{
x=x+10;
printf("\nValue 3:%d",x);
x=x+10;
}

STORAGE CLASSES

Storage class deals with scope and life time of variables with four access specifiers
namely auto, extern, static and register. Storage class access specifiers provide access
permission of the variables.

Scope of a variable defines in which parts of the program a variable is actually


available for use. Life-time of a variable defines at what extent the variable can be alive
without destroying.

C language supports four access specifiers as: auto, extern, static and registers that
are used with data type in the declaration statement of a variable. Hence, the storage classes
are termed as:

 Automatic Storage class


 External Storage class
 Static Storage class
 Register Storage class

Page 87
1. Automatic Storage class:

Variables declared inside the function or block starts with the keyword ‘auto’ are
termed as automatic variables. The general format of an automatic variable is:

Syntax : auto datatype identifier;

Example : auto int x;

 For automatic variables memory is allocated in the memory unit.


 The default value of the automatic variable is garbage value.
 Automatic variables are created when the function is called and destroyed
automatically when the function is exited. Therefore, automatic variables are local to
the function in which they are declared. So that automatic variables are also known as
local or internal variables.
 Scope of the automatic variable is within the block or function where it is defined and
the life time is until the end of the block or function.

Note: Variables declared inside the function or block without a storage class specification,
by default compiler assigns ‘auto’ keyword and treated as automatic variables.

/* EXAMPLE PROGRAM FOR AUTOMATIC VARIABLES */

#include<stdio.h>
#include<conio.h>
void Fun();
main()
{
auto int x=100;
clrscr();
printf("\nValue 1:%d",x);
Fun();
}

void Fun()
{
int y=20;
printf("\nValue 2:%d",y);
}

2. External Storage class:

Variables declared outside the function with the keyword ‘extern’ are termed as
external variables. The general format of an external variable is:

Syntax : extern datatype identifier;

Example : extern int x;

 For external variables memory is allocated in the memory unit.


 The default value of an external storage class variable is zero.

Page 88
 External variables are declared outside of all functions. Hence, an external variable is
also known as a global variable.
 Scope of the external variable is entire file and other files also and the life time is until
the program execution comes to end (global).

Note: Variables declared outside the function without a storage class specification, by
default compiler assigns ‘extern’ keyword and treated as external variables.

/* EXAMPLE PROGRAM FOR EXTERNAL VARIABLES */

#include<stdio.h>
#include<conio.h>
void Fun();

extern int x=100;


int y=200;

main()
{
clrscr();
printf("\nValue 1:%d",x);
Fun();
}
void Fun()
{
printf("\nValue 2:%d",y);
}
3. Static Storage class:

Variables declared inside the function or outside the function with the keyword
‘static’ are termed as static variables. The general format of a static variable is:

Syntax : static datatype identifier;

Example : static int x;

 For external variables memory is allocated in the memory unit.


 The default value of the static variable is zero.
 Static variables are initialized only once at the time of the first call.
 The main advantage of static variable is for retaining updated values between the
function calls.

Depending on the place of declaration, static variables may be classified as:

i) Internal static variables


ii) External static variables

Internal static variables: Variables declared inside the function with ‘static’
access specifier are known as internal static variables.

Page 89
The scope of internal static variable is up to the end of the function in which they are
defined and life time is throughout the remainder of the program.

/* EXAMPLE PROGRAM FOR INTERNAL STATIC VARIABLES */

#include<stdio.h>
#include<conio.h>
void Fun();
main()
{
int i;
clrscr();
for(i=1;i<=3;i++)
Fun();
}

void Fun()
{
static int x=10;
x=x+5;
printf("\nValue :%d",x);
}

External static variables: Variables declared outside the function with ‘static’
access specifier are known as internal static variables.
These variables are available to all functions. The scope of external static variable is
only in that file and the life time is global.

/* EXAMPLE PROGRAM FOR EXTERNAL STATIC VARIABLES */

#include<stdio.h>
#include<conio.h>
void Fun();
static int x=10;
main()
{
int i;
clrscr();
for(i=1;i<=3;i++)
{
printf("\nValue :%d",x);
Fun();
}
}
void Fun()
{
x=x+5;
}
4. Register Storage class:

User can also be possible to tell the compiler that a variable should be kept in register
unit, instead of keeping in memory unit by using the keyword ‘register’. Such variables are
called register variables. The general format of a register variable is:
Page 90
Syntax : register datatype identifier;

Example : register int x;

 Register variables are declared inside the function or block.


 For register variables memory is allocated in the memory unit.
 The default value of the register variable is garbage value.
 The main advantage of register variable is that the way of accessing is very fast when
compared to memory unit.
 Scope of the register variable is within the block or function where it is defined and
the life time is until end of the block or function.

/* EXAMPLE PROGRAM FOR REGISTER VARIABLES */

#include<stdio.h>
#include<conio.h>
main()
{
register int x;
clrscr();
x=10;
printf("\nValue :%d",x);
}
/* PROGRAM TO FIND LCM OF GIVEN TWO VALUES USING RECURSION */

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

int LCM(int,int);

main()
{
int x,y,z;
clrscr();
printf("\nEnter Two Values = ");
scanf("%d%d",&x,&y);
z=LCM(x,y);
printf("\nLCM Result Value = %d",z);
}

int LCM(int p,int q)


{
static int temp=1;
if(temp%p==0&&temp%q==0)
{
return temp;
}
temp=temp+1;
LCM(p,q);
return temp;
}

Page 91
SYMBOLIC CONSTANTS

Symbolic constant is a constant representation that does not change during program
execution. #define statement is used for defining symbolic constants.

Syntax: #define symbolicname constantvalue


Example: #define PI 3.14159

Rules:

i. Symbolic names have the same form as a valid identifier.


ii. No blank space between # and define.
iii. #define statements must not end with a semicolon.
iv. Symbolic names are not declared with data types.

/* EXAMPLE PROGRAM FOR SYMBOLIC CONSTANTS */

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

#define PI 3.14159

main()
{
float R,Area;
clrscr();
printf("\nEnter Radius of the Circle:");
scanf("%f",&R);
Area=PI*R*R;
printf("\nAREA OF THE CIRCLE IS:%.2f",Area);
}

TYPE QUALIFIERS

C provides three type qualifiers const, volatile and restrict.

const and volatile qualifiers can be applied to any variables, but restrict qualifier may only
applied to pointer.

Constant variable

A variable value can be made unchanged during program execution by declaring it as


a constant. For this the keyword const is placed before the variable declaration.

Syntax: const datatype variablename = Value;

Example: const int x = 10;

/* EXAMPLE PROGRAM FOR CONSTANT VARIABLE */


#include<stdio.h>

Page 92
#include<conio.h>

main()
{
const int x=10;
clrscr();
printf("\nResult = %d",x);
}
Volatile variable

Variables that can be changed at any time by external programs or the same program
are called as volatile variables. For this the keyword volatile is placed before the variable
declaration.

Syntax: volatile datatype variablename;

Example: volatile int x;

/* EXAMPLE PROGRAM FOR VOLATILE VARIABLE */

#include<stdio.h>
#include<conio.h>
main()
{
volatile int x=10;
clrscr();
printf("\nResult 1= %d",x);
x=20;
printf("\nResult 2= %d",x);
}
C PREPROCESSOR COMMANDS / DIRECTIVES

C compiler is made with two programs namely preprocessor program and translator
program.
Preprocessor is a program that processes the source code before it passes through the
compiler. Preprocessing is done under the control of preprocessor commands or directives.

Compilation Process

- - Pre - - - - Trans - - - --

- - Processor lator - - - --
- - - -
- - Translation - - - --

Source Compiler Object


Program Program

All preprocessor directives are begin with the symbol ‘#’ and do not require a
semicolon at the end. Preprocessor directives are placed in the source program before the
main () function.

Page 93
In C language, preprocessor directives are divided into three categories as:

1. Macro substitution directives


2. File inclusion directives
3. Conditional compilation directives

1. Macro substitution directives

a) The way of representing a symbolic constant statement is known as macro


substitution.

Syntax: #define MacroName MacroValue


Example: #define PI 3.14159

In this representation, the identifier in the program replaced with the macro value.
This type of macro’s are called simple macros.

b) Macro can also have arguments called argument macro substitution.

Consider the following example.

#include<stdio.h>
#include<conio.h>
#define area(x) 3.14159*x*x
main()
{
float R=3.97,A;
clrscr();
A=area(R);
printf("\nAREA OF THE CIRCLE IS:%.2f",A);
}

In this program, wherever the preprocessor found area(x), it expands it into the
statement as 3.14159*x*x. After the code has passed through the preprocessor, compiler
works on this as:
main()
{
float R=3.97,A;
clrscr();
A=3.14159*R*R;
printf("\nAREA OF THE CIRCLE IS:%.2f",A);
}

c) Simple programming code with multiple lines can also be replaced by using macro
substitution. In such cases, a ‘\’ character is used at the end of each line while defining the
macro.

/* EXAMPLE PROGRAM */

#include<stdio.h>

Page 94
#include<conio.h>

#define Max(x,y) if(x>y) \


printf("\n%d is Maximum",x); \
else \
printf("\n%d is Maximum",y);

main()
{
int a=35,b=79;
clrscr();
Max(a,b);
}
When this program passed through the processor, then compiler works on this as:

main()
{
int a=35,b=79;
clrscr();
if(a>b)
printf(“\n%d is Maximum”,a);
else
printf(“\n%d is Maximum”,b);
}

2. File inclusion directives

File inclusion directives causes’ one file to be included in another file. The file may
contain functions or macro definitions. The preprocessor command for a file inclusion is:

Syntax: 1. #include <FileName>


(or)
2. #include “FileName”

First format is used to direct the preprocessor for including header files from the
system library.
Second format is used to direct the preprocessor for including header files from the
user defined directories.

Example: #include “math.h” #include <math.h>

3. Conditional compilation directives:

Conditional compilation allows the user to control the compilation process by


including or excluding statements. The following commands are used in conditional
compilation.

COMMAND MEANING
#if Expression When Expression is TRUE, then the code that follows is
included for compilation

Page 95
#endif Terminates the conditional command
#else Specifies alternative code in two way decision
#elif Expression Specifies alternative code in multi way decision
#ifdef MacroName Expression Abbreviation for #if defined macro
#error Reporting errors by the preprocessor

The main advantages with conditional compilation are:

 It provides a compile-time parameterization facility.


 Decisions can be made at compile time rather than at run-time.

/* EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION */


#define vax 1
#define sun 0
main()
{
clrscr();
#if vax
printf("\nTRUE");
#else
printf("\nFALSE");
#endif
}
***

POINTERS

Accessing the address of a variable: Suppose ‘x’ is a variable that represents a


particular data item as:

Example: int x;

Then compiler will allocate a memory cell for this data item. The data item can be
accessed, if we know the location (i.e., address) of the item. The address of a variable is
accessed with address operator &, which is a unary operator preceded by the variable.
Address of the variable is always unsigned integer.

Example: &x;

/* EXAMPLE PROGRAM FOR ADDRESS OPERATOR */

#include<stdio.h>
#include<conio.h>
main()
{ x
int x;
clrscr(); 10
printf("\nAddress of x:%u",&x);
x=10; 65524

Page 96
printf("\nValue of x:%d",x);
}

Note:

1. The address operator & can be used only with a simple variable (or) an array
element.
2. Address operator cannot act upon constants, and arithmetic expression.

Example: &125 → INVALID


&(x+y) → INVALID

***
POINTERS

A pointer is a variable which holds the memory address of another variable.

Pointer Declaration: As similar to an ordinary variable, pointer variables must be


declared before they are using. A pointer variable is declared by preceding its name with an
asterisk * symbol. The symbol indicates that the variable is a pointer variable. The general
format of declaring a pointer variable is:

Syntax: datatype *ptrvariable;


Where,
 ptrvariable is name of the pointer variable that follows same rules as a valid identifier.
 ‘*’ tells the compiler that ptrvariable is a pointer variable.
 datatype is the type of the data that the pointer is allowed to hold the address.

Example: int *ptr1;


Here, ptr1 is a pointer variable that can points to an integer variable.

Example: float *ptr2;


Here, ptr2 is a pointer variable that can points to a float variable.

Example: char *ptr3;


Here, ptr3 is a pointer variable that can points to a character variable.

Example: int *ptr1; float *ptr2; char *ptr3;

2 bytes 2 bytes 2 bytes

ptr1 ptr2 ptr3

Note: Any type of pointer occupies only 2 bytes of memory. Since, pointer holds address of
the variable which is always an unsigned integer.

Page 97
Initializing Pointers: Once a pointer variable has been declared, it can be initialized
using an assignment operator as:

Syntax: ptrvariable = &ordinaryvariable;

Example: ptr = &x;

Where, x is an ordinary variable.


Here, address of the variable x is stored in ptr. With this, a link is formed from
pointer variable to ordinary variable.

Example: int x,*ptr;


x=10;
ptr=&x;

65592 65594
10 65592
x ptr

A pointer variable can also be initialized at the time of its declaration itself.
Example: int x, *ptr = x;

Accessing variable value through pointer: The value of a variable can be accessed
through pointer variable using a unary operator ‘*’, usually known as indirection operator.
The operator refers to “value at the address in”.

Example: *ptr refers to value at the address in ptr

/* EXAMPLE PROGRAM TO DEMONSTRATE POINTERS CONCEPT */

main()
{
int x,*ptr;
clrscr();
printf("\nAddress of x is:%u",&x);
printf("\nAddress of ptr is:%u",&ptr);
x=10;
printf("\nx value using x:%d",x);
ptr=&x;
printf("\nValue in p:%u",ptr);
printf("\nx value using ptr:%d",*ptr);
}

***

/* Write a program to demonstrate every pointer variable same (2 bytes) amount of memory space */

Page 98
#include<stdio.h>
#include<conio.h>
main()
{
char *p; int *q; float *r; double *s;
clrscr();
printf(“\n Memory Size of Char Pointer Variable = %d Bytes”,sizeof(p));
printf(“\n Memory Size of Int Pointer Variable = %d Bytes”,sizeof(p));
printf(“\n Memory Size of Float Pointer Variable = %d Bytes”,sizeof(p));
printf(“\n Memory Size of Double Pointer Variable = %d Bytes”,sizeof(p));
}
***
PASSING PARAMETERS TO FUNCTIONS

Arguments can be passed to a function in two ways. Those are,


1. Call by value (or) Pass by value
2. Call by address (or) Pass by address

1. Call by value: The process of passing actual value of the variable as an argument to a
function is known as call by value (or) pass by value.
In this mechanism, a copy of the value is passed from calling function to the called
function. Now, this value is stored temporarily in the formal argument of the called function.
At this stage, if we made any changes inside the function definition with the received
value, those changes are not effect on the original variable. Entire changes effected only on
the formal arguments of the called function.

/* EXAMPLE PROGRAM FOR CALL BY VALUE */

#include<stdio.h>
#include<conio.h>
void change(int,int);
main()
{
int x,y;
clrscr();
printf(“\nEnter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\nBefore Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
change(x,y);
printf("\nAfter Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
}
void change(int p,int q)
{
p=p+5;
q=q+5;
}

2. Call by address: The processing of passing address of the variable as an argument to a


function is known as call by address (or) pass by address.

Page 99
In this mechanism, when we pass address of the variable as an argument to a function,
the receiving argument at the called function must be a pointer variable. When the pointer
variable received the address, it points to the actual variable.
At this stage, if made any changes inside the function definition; those changes are
effected on the original variable. Since, pointer variable points the original argument.

/* EXAMPLE PROGRAM FOR CALL BY ADDRESS */


/* PROGRAM TO SWAP THE GIVEN TWO VALUES USING POINTERS */

#include<stdio.h>
#include<conio.h>
void change(int *,int *);
main()
{
int x,y;
clrscr();
printf(“\nEnter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\nBefore Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
change(&x,&y);
printf("\nAfter Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
}
void change(int *p,int *q)
{
*p=*p+5;
*q=*q+5;
}
***

POINTER ARITHMETIC OPERATIONS

A pointer arithmetic operation offers a restricted set of arithmetic operators for


manipulating address in pointers.

Valid Operations:

1. Addition or Subtraction of an integer value from a pointer variable is valid. In these


cases, one operand is a pointer variable and other operand is an integer value.
When the value is added / subtracted from a pointer variable, the value is in
terms of the length of the data type pointed by the pointer variable. The final value is
termed as a “Scale Factor”.
.
Example: int *p, x;
p = &x;
p = p+2;
p = p-1;

2. A pointer variable can be subtracted from another pointer variable.

Page 100
Example: int *p1,*p2, x, y, z;
p1 = &x;
p2 = &y;
z = p1 – p2;

3. Pointer variable comparisons with relational operators are valid.


Example: int *p1,*p2, x, y;
p1 = &x;
p2 = &y;
p1 < p2
p1 > p2
p1 <= p2
p1 >= p2
p1 == p2
p1 != p2 are valid operations.

/* EXAMPLE PROGRAM FOR POINTER ARITHMETIC OPERATIONS */

main()
{
int *p1,*p2,x,y;
clrscr();
p1=&x;
p2=&y;
printf("\np1 Address:%u",&p1); /* 65518 */
printf("\np1 value:%u",p1); /* 65522 */
printf("\np2 Address:%u",&p2); /* 65520 */
printf("\np2 value:%u",p2); /* 65524 */
x=p2-p1;
printf("\nx value:%d",x); /* 1 */
p1=p1+2;
printf("\np1 value:%u",p1); /* 65526 */
p2=p2-1;
printf("\np2 value:%u",p2); /* 65522 */
}

Invalid Operations:

1. Multiplication of a pointer variable with an integer value is invalid operation.

Example: int *P;


P = P * 3; Invalid operation

2. Division of a pointer variable with an integer value is invalid operation.

Example: int *P;


P = P / 3; Invalid operation

Page 101
3. Addition, Multiplication and division of two pointer variables is also invalid
operation.

Example: int *P1,*P2,Z;


Z = P1 + P2;
Z = P1 * P2;
Z = P1 / P2; are invalid operations.

***
VOID POINTER

A void pointer is a special type of pointer that can points to any data type variables.
The general format of a void pointer variable is:

Syntax : void *ptrvariable;

Example : void *ptr;


int X;
float Y;
ptr = &X;
ptr = &Y;

For accessing value of the variable with the pointer variable, type casting must be
placed to refer the specific data item.

/* EXAMPLE PROGRAM FOR VOID POINTER */

main()
{
int x=10;
double y=3.45678;
void *ptr;
clrscr();
ptr=&x;
printf("\nValue 1 =%d",*(int *)p);
ptr=&y;
printf("\nValue 2 =%lf",*(double *)p);
}

NULL POINTER

A pointer variable can also be initialized in such a way that it does not point to any
data type. Such a pointer is known as a NULL pointer.
A null pointer is a special type of pointer that cannot points to anywhere. Null pointer
is assigned by using the predefined constant NULL; which is defined by several header files
including stdio.h, stdlib.h and alloc.h.

Example: int *p=NULL;

/* EXAMPLE PROGRAM FOR NULL POINTER */

Page 102
#include<stdio.h>
main()
{
int *p;
clrscr();
p=NULL;
printf("\nValue :%d",*p);
}
POINTERS AND ARRAYS

In C language, there is a close relationship between array and pointers. An array


name in C language is very much like a pointer but there is a slight difference between each
other. The difference is that the pointer is a variable that can appear on the left side of an
assignment operator; whereas the array name acts as a constant and cannot appear on the left
side of the assignment operator.

When an array is declared, the compiler allocates a base address and sufficient
amount of storage space for storing all the elements of the array in successive memory
locations. The name of the array is the beginning address (first element index 0) of the array,
called the base address. So, that the array name is referred to as an address constant.

Example: int x[5] = {10,20,30,40,50};

0 1 2 3 4 Index Values
x 10 20 30 40 50 Element Values

1000 1002 1004 1006 1008 Address

Base Address

Here,
x = &x[0] = &x all are referred to the address location 1000.

With the relationship between the array and pointer, array subscripts can also be
defined in terms of pointer arithmetic operations which are known as indexing pointers.

For single dimensional arrays,

int x[3], i=0;

&x[0] = x+0 x[0] = *(x+0)


&x[1] = x+1 x[1] = *(x+1)
&x[2] = x+2 x[2] = *(x+2)

i.e., &x[i] = x+i x[i] = *(x+i)

Page 103
Similarly, for double dimensional arrays,

&x[i][j] = (*(x+i)+j) x[i][j] = *(*(x+i)+j)

/* PROGRAM TO READ A ONE DIMENSIONAL ARRAY AND PRINT IT USING POINTERS */

main()
{
int x[10],i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",x+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",*(x+i));
}

(OR)

main()
{
int x[10],i,n,*p;
clrscr();
p=x;
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",*(p+i));
}

/* WRITE A PROGRAM TO READ LIST OF FLOATING POINT NUMBERS AND PRINT SUM
OF THE ARRAY ELEMENTS USING POINTERS */

main()
{
float x[10],*p,sum;
int i,n;
clrscr();
p=x;
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)

Page 104
scanf("%f",p+i);
sum=0;
for(i=0;i<n;i++)
sum=sum+*(p+i);
printf("\nTotal :%.2f",sum);
}

/* PROGRAM TO READ A DOUBLE DIMENSIONAL ARRAY AND PRINT IT USING POINTERS */

main()
{
int x[10][10],i,j,m,n;
clrscr();
printf("\nEnter how many Rows:");
scanf("%d",&m);
printf("\nEnter how many Columns:");
scanf("%d",&n);
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(x+i)+j);
}
printf("\nArray Elements Are:");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%5d",*(*(x+i)+j));
}
}
(OR)

main()
{
int x[10][10],i,j,m,n,(*p)[10];
clrscr();
printf("\nEnter how many Rows:");
scanf("%d",&m);
printf("\nEnter how many Columns:");
scanf("%d",&n);
p=x;
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(p+i)+j);
}
printf("\nArray Elements Are:");
for(i=0;i<m;i++)

Page 105
{
printf("\n");
for(j=0;j<n;j++)
printf("%5d",*(*(p+i)+j));
}
} ***
ARRAY OF POINTERS

Array of pointers are used to define more than one pointer variable of the same data
type. The general format of declaring array of pointers is:

Syntax: datatype *ptrvariable[size];


Where,
Datatype specifies type of the data that can be pointed by each pointer variable.
Ptrvariable is name of the pointer variable that follows same rules as a valid identifier.
Size represents maximum number of elements.

Example: int *ptr[10];

/* EXAMPLE PROGAM 1 FOR ARRAY OF POINTERS */

main()
{
int i,*p[5],x,y,z;
clrscr();
x=10;
y=20;
z=30;
p[0]=&x;
p[1]=&y;
p[2]=&z;
printf("\nElements Are:");
for(i=0;i<3;i++)
printf("%5d",*p[i]);
}

/* EXAMPLE PROGRAM 2 FOR ARRAY OF POINTERS */

main()
{
int i,j,*p[5];
int x[]={1,2,3},y[]={4,5,6},z[]={7,8,9};
clrscr();
p[0]=x;
p[1]=y;
p[2]=z;
printf("\nElements Are:");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)

Page 106
printf("%5d",*(*(p+i)+j));
}
}

***
POINTERS AND STRINGS

A string is an array of characters that terminated with a null character ‘\0’. As similar
to arrays, string contents can also be accessed with the pointer variable.

/* EXAMPLE PROGRAM FOR PONTER TO STRING */

main()
{
char s[50]="KAVALI",*p;
int i;
clrscr();
p=s;
printf("\nString Elements Are:");
for(i=0;*(p+i)!='\0';i++)
printf("%c",*(p+i)));
}

A string constant is like an array name by itself, it is treated by the compiler as a


pointer. Here, base address of the location is stored in the variable name.

/* EXAMPLE PROGRAM */

main()
{
char s[50]="KAVALI",*p="NELLORE";
int i;
clrscr();
printf("\nResult 1:");
puts(s);
printf("\nResult 2:");
puts(p);
}
***

POINTER TO POINTER (OR) MULTIPLE INDIRECTION

A pointer variable that holds address of an ordinary variable is known as pointer-to-


variable.
A pointer variable that holds address of another pointer variable is known as pointer-
to-pointer. For this, add an asterisk symbol for each level of reference.

Example: int x = 10;


int *p;
p=&a;
int **q;
Page 107
q=&p;

/* EXAMPLE PROGRAM FOR POINTER TO POINTER VARIABLE */

main()
{
int a=5,*p,**q;
clrscr();
p=&a;
q=&p;
printf("\nValue with p is:%d",*p);
printf("\nValue with q is:%d",**q);
}

/* PROGRAM THAT SHOWS FOR READING AND PRINTING A VARIABLE VALUE USING
POINTER-TO-POINTER */

main()
{
int x,*p,**q;
clrscr();
p=&x;
q=&p;
printf("\nEnter a value:");
scanf("%d",&x);
printf("\nValue with x is:%d",x);
printf("\nEnter another value with p:");
scanf("%d",p);
printf("\nValue with p is:%d",*p);
printf("\nEnter another value with q:");
scanf("%d",*q);
printf("\nValue with q is:%d",**q);
}

***

DYNAMIC MEMORY ALLOCATION

The memory allocation may be classified as static memory allocation and dynamic
memory allocation.

Static memory allocation: Memory for the variables is created at the time of compilation
is known as static memory.

Dynamic memory allocation: Memory for the variables is allocated at the time of
execution of the program is called dynamic memory. The following functions are used for
dynamic memory allocation which are defined in stdlib.h and alloc.h header files.
1. malloc() 2. calloc() 3. realloc() 4. free()

malloc(), calloc() and realloc() are memory allocation functions and free() is a memory
releasing function.

Page 108
Memory allocation process

LOCAL VARIABLES
STACK

FREE MEMORY HEAP

GLOBAL VARIABLES
PERMANENT
STORAGE
PROGRAM INSTRUCTIONS AREA

The program instructions, global and static variables are stored in a region known as
permanent storage area. Local variables are stored in another region called stack. The
memory spaced located between stack and permanent storage area is available for dynamic
memory allocation during execution of the program. This free memory region is called as
heap.

1. malloc() function: malloc() function is used to allocate memory for the variables
at run time. The malloc() function reserves a single block of memory with the specified size
and returns a pointer of type void. With this, we can assign it to any type of pointer. The
general form of malloc() function is:

Syntax: prtvariable = (casttype*)malloc(size);


Where,
ptrvariable is a pointer variable of type casttype.
size represents number of bytes of memory to be allocated.

Example: int *X;

X = (int*)malloc(10); (or) X = (int*)malloc(5*sizeof(int));

For this, memory allocation will be:

X Garbage Values

10 BYTES

/* EXAMPLE PROGRAM FOR MALLOC() FUCNTION */

main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");

Page 109
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}

2. calloc() function: calloc() function is another memory allocation function used


for dynamic memory allocation for storing derived data types such as arrays and structures
etc.,
malloc() function allocates a single block of storage space, whereas calloc() function
allocates multiple blocks of storage space with each of same size and all locations are
initialized with ‘0’. The general form of calloc() function is:

Syntax: ptrvariable = (casttype*)calloc(n,elesize);

Where,
ptrvariable is a pointer variable of type casttype.
n represents number of blocks.
elesize represents block size.

All blocks are initialized with ‘0’ and a pointer of the first block is returned. If there
is not enough space to allocate, then it returns a NULL pointer.

Example: int *X;

X = (int*)calloc(5,sizeof(int));

For this, memory allocation will be:

X 0 0 0 0 0
10 BYTES

/* EXAMPLE PROGRAM FOR CALLOC() FUNCTION */

main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);

Page 110
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}

/* EXAMPLE PROGRAM THAT DEMONSTRATES THE DIFFERENCE BETWEEN MALLOC()


AND CALLOC() FUNCTIONS */

main()
{
int *p,*q,i,m,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&m);
p=(int*)malloc(m*sizeof(int));
printf("\nArray Elements Are:");
for(i=0;i<m;i++)
printf(" %d",*(p+i));
printf("\nEnter how many numbers:");
scanf("%d",&n);
q=(int*)calloc(n,sizeof(int));
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(q+i));
}

3. realloc(): Suppose previously allocated dynamic memory is not sufficient (or) memory
is much larger than the requirement, in both cases some memory changes are required.
Memory changes can be done by using a library function called realloc() function.

realloc() function provides the altering the size of the memory allocation and the
process is called reallocation of memory. The general form of realloc() function is:

Syntax: ptrvariable = (casttype*)realloc(ptrvariable,newsize);

Where,
ptrvariable is a pointer variable of type casttype.

Here,
This function allocates a new memory space of the specified newsize and returns a
pointer variable that represent first byte of the new memory block. The newsize may be
larger or smaller than the previous size.

Note:

I. The new memory block may or may not be begin at the same place as the old one. In
case, it is not able to find additional space in the same region, it will create the same
in an entirely new region and moves the contents of the old block into the new block.
II. If the function is unsuccessful to allocate the memory space, it returns a NULL
pointer and the original block is lost.

Page 111
/* EXAMPLE PROGRAM FOR REALLOC() FUNCTION */

main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
p=(int*)realloc(p,(n+2)*sizeof(int));
printf("\nEnter %d Elements:",n+2);
for(i=0;i<n+2;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n+2;i++)
printf(" %d",*(p+i));
}

4. free(): The memory allocation done by malloc(), calloc() and realloc() functions at
run time are released by invoking the function free() by the user explicitly. The releasing of
storage space becomes very important when the storage is space is limited. The general form
of free() function is:

Syntax: free(ptrvariable);

Example: free(ptr);

***
VARIABLE LENGTH ARRAYS

In C89 version, array dimensions must be declared using constant expressions.

Example: int x[10];

In C99 version, array dimensions can be specified by any valid expression, those
whose value is known only at run time. Such a representation is known as variable-length
array.

Example: void show(int k)


{
int arr[k]; /* Variable Length Integer Array */
- ----
- ----
- ----
}
FUNCTION WITH ARRAYS

Like the simple variables, it is also possible to pass values of an array as an argument
to functions. Arrays can be passed as an argument in two ways. Those are:
Page 112
1. Passing individual elements as an argument
2. Passing entire array as an argument

1. Passing individual elements as an argument:

When an individual element of the array is passed as an argument to a function, it just


likes an ordinary value. In such case, an ordinary variable is enough to receive at called
function. Then if we made any changes inside the function with the received value, those
changes are not effected on the original array.

/* Example program for passing individual element of the array as an argument to a function */

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

void change(int);

main()
{
int x[10],i,n;
clrscr();
printf("\nEnter How Many Values=");
scanf("%d",&n);
printf("\nEnter %d Elements=",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\nBefore Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
change(x[3]);
printf("\nAfter Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}
void change(int p)
{
p=p+5;
}

2. Passing entire array as an argument:

For passing entire array as an argument to a function, list name of the array and size
of the array at the calling function. In such cases, an array or pointer is required to receive
the array at the called function. Then if we made changes inside the function with the
received argument, those changes are effected on the original array.
/* Example program for passing entire array as an argument to a function */

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

void sort(int[],int);

Page 113
main()
{
int x[10],i,n;
clrscr();
printf("\nEnter How Many Values=");
scanf("%d",&n);
printf("\nEnter %d Elements=",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\nBefore Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
sort(x,n);
printf("\nAfter Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}
void sort(int p[10],int k)
{
int i,j,temp;
for(i=0;i<=k-2;i++)
{
for(j=i+1;j<=k-1;j++)
{
if(p[i]>p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
}

/* Example program for passing entire array as an argument to a function using pointers */

#include<stdio.h>
#include<conio.h>
void sort(int *,int);
main()
{
int x[10],i,n;
clrscr();

printf("\nEnter How Many Values=");


scanf("%d",&n);
printf("\nEnter %d Elements=",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\nBefore Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
Page 114
printf(" %d",x[i]);
sort(x,n);
printf("\nAfter Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}
void sort(int *p,int k)
{
int i,j,temp;
for(i=0;i<=k-2;i++)
{
for(j=i+1;j<=k-1;j++)
{
if(*(p+i)>*(p+j))
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
}
}
/* Example program for passing a double dimensional array as an argument to a function */

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

void change(int[][],int,int);

main()
{
int x[10][10],i,r,c,j;
clrscr();
printf("\nEnter How Many Rows=");
scanf("%d",&r);
printf("\nEnter How Many Columns=");
scanf("%d",&c);
printf("\nEnter Matrix Elements=");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&x[i][j]);
}
printf("\nBefore Passing To Function Matrix Values Are=\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf(" %d",x[i][j]);
}
change(x,r,c);
printf("\nAfter Passing To Function Matrix Values Are=\n");

Page 115
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf(" %d",x[i][j]);
}
}
void change(int p[10][10],int m,int n)
{
p[0][0]=10;
p[1][1]=20;
p[2][2]=30;
}

***

RETURNING MORE THAN ONE VALUE FROM A FUNCTION

Functions usually return only one value from called function to the calling function
after completion of the function implementation.
Pointers allow the user to return more than one value by allowing the arguments to be
passed by address, which allows the function to alter the values that pointed to and thus
return more than one value from the function.

/* Example program to return a sorted array from the function */

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

int* sort(int*,int);

main()
{
int x[5]={77,11,33,88,55},*k,i;
clrscr();
printf("\nBefore Sorting Elements Are:");
for(i=0;i<5;i++)
printf(" %d",x[i]);
k=sort(x,5);
printf("\nAfter Sorting Elements Are:");
for(i=0;i<5;i++)
printf(" %d",*(k+i));
}
int* sort(int *p,int n)
{
int i,j,temp;
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
Page 116
{
if(*(p+i)>*(p+j))
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
}
return p;
}

/* Program to return reverse of a passed string */

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

char* rev(char*);

main()
{
char *s=”C LAB”,*p;
clrscr();
printf(“\nOriginal String:”);
puts(s);
p=rev(s);
printf(“\nReverse String:”);
puts(p);
}
char* rev(char *k)
{
strrev(k);
return k;
}

***

POINTER TO FUNCTION

In C language every variable has an address except register variables. Similarly, C


functions also have an address. This address is the entry point of the function and used when
the function is called. So, that function can also invoked by using its address.

/* EXAMPLE PROGRAM TO DISPLAY THE ADDRESS OF LIBRARY FUNCTIONS */

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

main()
{
clrscr();
printf("\nAddress of printf function is:%u",printf);
printf("\nAddress of scanf function is:%u",scanf);
printf("\nAddress of clrscr function is:%u",clrscr);
}

/* EXAMPLE PROGRAM TO DISPLAY THE ADDRESS OF USER-DEFINED FUNCTIONS */

#include<stdio.h>
#include<conio.h>
void show();
main()
{
clrscr();
show();
printf("\nAddress of the Function:%u",show);
}
void show()
{
printf("\nFunction Called");
}

The address of the function can also be assigned to a pointer variable. For this, the
general form of declaring the pointer variable as pointer-to-function is:

Syntax: datatype (*ptrvariable)( );


Here,
ptrvariable is name of the pointer variable and the parenthesis indicates that it is a
pointer variable to function.

/* EXAMPLE PROGRAM TO CALL A FUNCTION WITH POINTER-TO-FUNCTION */

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

int show(int,int);
main()
{
int x,y,z,(*p)();
clrscr();
x=10;
y=20;
p=show;
z=(*p)(x,y);
Page 118
printf("\nResult=%d",z);
}
int show(int a,int b)
{
return a+b;
}

***

Differences between Variables and Pointers

VARIABLE POINTER

1. Variable is capable to hold ordinary 1. Pointer is a variable that holds address


values. of another variable.
2. The general form of an ordinary 2. The general form of a pointer variable
variable declaration is : declaration is :
Syntax : Datatype Identifier; Syntax : Datatype *PtrVaribale;
Example : int x; Example : int *ptr;
3. The general form of initializing a 3. The general form of initializing a
variable is: pointer variable is:
Syntax : Variable = Value; Syntax : PtrVariable = &Variable;
Example : int x; Example: int x, *p;
x = 10; p = &x;
4. For ordinary variables compiler 4. For any type pointer variables compiler
allocates memory based on their data allocates only 2 bytes of memory.
types.
Example: int x; char y; Example: int *p; char *q;

For x compiler allocates 2 Bytes and For p compiler allocates 2 Bytes and
for y compiler allocates 1 Byte for q also compiler allocates 2 Bytes
memory. memory.
5. For ordinary variables only static 5. For pointer variables dynamic memory
memory allocation is possible. allocation is possible.
6. /* Example program for Variables */ 6. /* Example program for Pointer */

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int x = 10; int x = 10, *p=&x;
clrscr(); clrscr();
printf(“\nResult = %d”,x); printf(“\nResult = %d”,*p);
} }

Differences between Arrays and Pointers

Page 119
ARRAY POINTER

1. Array is a collection of homogeneous 1. Pointer is a variable that holds address


data elements that are stored in of another variable.
successive memory locations.
2. The general form of array declaration 2. The general form of a pointer variable
is : declaration is :
Syntax : Datatype ArrayName[size]; Syntax : Datatype *PtrVaribale;
Example : int x[10]; Example : int *ptr;
3. The general form of initializing a array 3. The general form of initializing a
is: pointer variable is:
Syntax : Syntax : PtrVariable = &Variable;
Datatype Array[size]={List of values};
Example: int x, *p;
Example: int x[4] = {2,5,1,7}; p = &x;
4. For an array, compiler allocates 4. For any type pointer variables compiler
memory space based on the size of the allocates only 2 bytes of memory.
array.
Example: int x[5]; Example: int *p; char *q;

Here, compiler allocates 10 bytes of For p compiler allocates 2 Bytes and


memory for the variable x. for q also compiler allocates 2 Bytes
memory.
5. sizeof(arrayname) gives the number of 5. sizeof(pointervaraible) returns only 2
bytes of the memory occupied by the bytes.
array.
6. For arrays only static memory 6. For pointer variables dynamic memory
allocation is possible. allocation is possible.
7. Arrays can’t be resized. 7. Pointer allocation can be resized using
realloc() function.
8. It cannot be reassigned. 8. It can be reassigned.
9. /* Example Program */ 9. /* Example program for Pointer */

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main()
main() {
{ int x = 10, *p=&x;
int x[5]={2,4,6,1,3},i; clrscr();
clrscr(); printf(“\nResult = %d”,*p);
printf(“\nArray Elements Are=”); }
for(i=0;i<5;i++)
printf(“ %d”,x[i]);
}

USES OF POINTERS

 Pointer variable holds address of another variable.

Page 120
 Pointer enables us to access a variable that is defined outside the function.
 Pointers support dynamic memory allocation for saving lot of memory space.
 Pointers allow returning more than one value from a function.
 Pointers reduce length and complexity of the program.
 Pointers increase execution speed of the program.
COMMAND LINE ARGUMENTS

The arguments that pass to main() function at the command prompt of the operating system
are called command line arguments. The general format of the main() function with command line
arguments is:

Syntax: int main(int argc, char *argv[])

 main() function returns an integer value on successful completion.


 The first argument of main() function argc is an integer argument called argument counter,
that counts number of arguments passed at the command prompt.
 The second argument argv is called argument vector; which is an array of pointer to strings.
Arguments are stored in terms of strings.
 The arguments passed at the command prompt are stored in argv[0], argv[1] and so on. Here,
argv[0] is reserved for to store name of the executing program.

/* WRITE A PROGRAM TO PERFORM ADDITION OF GIVEN NUMBERS USING COMMAND


LINE ARGUMENTS */
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main(int argc,char *argv[])
{
int x,y;
clrscr();
x=atoi(argv[1]);
y=atoi(argv[2]);
printf("\nNumber of arguments:%d",argc);
printf("\nAddition Result:%d",x+y);
return 1;
}
UNIT – IV
STRUCTURE

“Structure is a collection of non-homogeneous / heterogeneous / different data


elements that can be grouped together under a common name”.

Structure Declaration and Definition

A structure definition is specified by the keyword “struct”. The keyword is followed


by a user defined name surrounded by pair of braces, which describes the members of the
structure. The general format of a structure declaration is:

Page 121
Syntax: struct Tag
{
Datatype Member1;
Datatype Member2;
---
---
Datatype Membern;
};

 struct is a keyword used to define structure declaration.


 Tag is name of the structure that follows same rules as a valid identifier.
 Members declared inside the structure declaration are called structure elements (or)
structure members.
 Structure declaration must be ended with a semicolon.
 Structure is a user-defined data type.

Example: struct Book


{
char BName[50];
int Pages;
float Price;
};

Declaration of the structure does not reserve any storage space. Memory is allocated
only at the time of defining a structure variable. The general format of defining a structure
variable is:

Syntax: struct Tag varname1, varname2, - - - - - , varnamep;

Example: struct Book B1,B2;


Now, the compiler allocates memory for B1 and B2 as:

BName : BName :
B1 B2
Pages : Pages :

Price : Price :

i.e., Memory is allocated individually for each structure variable as well as individual
memory area for each member of the structure.

Accessing members of the structure

Page 122
‘.’ Dot operator is used to access members of the structure with its structure variable.
Here dot operator is also known as member operator (or) period operator. It forms link
between structure member and structure variable. The general format of accessing a structure
member with structure variable is:

Syntax: structurevariable.member;

Example: B1.Pages;

/* EXAMPLE PROGRAM FOR PRINTING BOOK DETAILS USING STRUCTURE */

#include<stdio.h>
#include<conio.h>
struct Book
{
char BName[50];
int Pages;
float Price;
};
main()
{
struct Book B1;
clrscr();
printf("\nEnter Titile of the Book:");
gets(B1.BName);
printf("\nEnter Number of Pages:");
scanf("%d",&B1.Pages);
printf("\nEnter Cost of the Book:");
scanf("%f",&B1.Price);
printf("\nBOOK TITLE:%s",B1.BName);
printf("\nNUMBER OF PAGES:%d",B1.Pages);
printf("\nBOOK COST:%.2f RS",B1.Price);
}

Note:
Structure declaration and definition can also be combined into a single statement. For this,
use the syntax as:

Syntax: struct Tag


{
Datatype Member1;
Datatype Member2;
---
---
Datatype Membern;
}
varname1, varname2, - - - - - , varnamep;

/* EXAMPLE PROGRAM FOR PRINTING CURRENT DATE */


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

struct Date
{
int Day,Month,Year;
}x;

main()
{
clrscr();
printf("\nEnter Current Day:");
scanf("%d",&x.Day);
printf("\nEnter Current Month:");
scanf("%d",&x.Month);
printf("\nEnter Current Year:");
scanf("%d",&x.Year);
printf("\nTODAY DATE:%d/%d/%d",x.Day,x.Month,x.Year);
}
INITIALIZING A STRUCTURE

A structure can be initialized with a list of values at the time of defining the structure
variable. But, individual member initialization inside the structure declaration is not possible.
The general format of initializing a structure is:

Syntax: struct Tag varname = { List of Values };

Example: struct Date x ={7,11,2010};

struct Book b = {“Let Us C”,350,125.75};

 Initialization values for a structure must be enclosed within a pair of braces.


 The constants to be assigned to the members of the structure must be in the same
order as that in which the members are specified.
 If some of the structure members are not initialized, then C compiler will
automatically initialized as:
o For int, float and double data type members, default value is zero.
o For char and string data type members, default value is ‘\0’.

/* EXAMPLE PROGRAM FOR INITIALIZING A STRUCTURE */

#include<stdio.h>
#include<conio.h>
struct product
{
Page 124
int pid;
char pname[10];
float price;
};
main()
{
struct product s1={111,"soap",25.00};
clrscr();
printf("\nProduct Code=%d\n”,s1.pid);
printf(“\nProduct Name=%s\n”,s1.pname);
printf(“\nProduct Cost=%.2f Rs",s1.price);
}

COPY AND COMPARISON OF STRUCTURE VARIABLES

Copy:

 Two variables of the same structure type can be copied in the same way as ordinary
variables. In this case, use assignment operator for copying.

Example: Let B1 and B2 are two structure variables of the same structure type,
and then the details of B1 are copied into B2 as:

B2 = B1;
Here,
Each individual member of the B1 is copied into individual member of B2.

/* PROGRAM TO COPY CONTENTS OF ONE STRUCTURE INTO ANOTHER STRUCTURE */

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

struct product
{
int pid;
char pname[10];
float price;
};
main()
{
struct product s1={111,"soap",25.00},s2;
clrscr();
printf("\nOriginal structure is:");
printf("\n%d\t%s\t%.2f",s1.pid,s1.pname,s1.price);
s2=s1;
printf("\nCopied structure is:");
printf("\n%d\t%s\t%.2f",s2.pid,s2.pname,s2.price);
}

Comparison:

Page 125
 Direct comparison of one structure variable with another structure variable using relational
operators is not possible.

i.e., Let B1 and B2 are two structure variables of the same structure type, and then the
comparisons like
B1>B2, B1<B2, B1<=B2, B1>=B2, B1==B2 and B1!=B2 are invalid operations.

However, for comparing structure variables individual member comparions is valid.

/* PROGRAM TO COMPARE THE GIVEN TWO STRUCTURES */

#include<stdio.h>
#include<string.h>

struct product
{
int pid;
char pname[10];
float price;
};
main()
{
struct product s1,s2;
clrscr();
printf("\nEnter Product 1 id:");
scanf("%d",&s1.pid);
fflush(stdin);
printf("\nEnter Prouduct 1 Name:");
gets(s1.pname);
printf("\nEnter Product 1 Cost:");
scanf("%f",&s1.price);
printf("\nEnter Product 2 id:");
scanf("%d",&s2.pid);
fflush(stdin);
printf("\nEnter Prouduct 2 Name:");
gets(s2.pname);
printf("\nEnter Product 2 Cost:");
scanf("%f",&s2.price);
if((s1.pid==s2.pid)&&((strcmp(s1.pname,s2.pname))==0)&&(s1.price==s2.price))
printf("\nBOTH ARE EQUAL");
else
printf("\nBOTH ARE DIFFERENT");
}

ARRAYS WITHIN STRUCTURES

C permits the use of array as structure members. i.e., an array can also be placed as a
member of a structure.

/* EXAMPLE PROGRAM FOR ARRAYS WITHIN STRUCTURES */

Page 126
#include<stdio.h>
#include<conio.h>
struct student
{
char name[50];
int sub[3],total;
}s;
main()
{
int i,j,n;
clrscr();
printf(“\nEnter student Name =”);
gets(s.name);
printf(“\nEnter 3 subject Marks:”);
for(i=0;i<3;i++)
scanf(“%d”,&s.sub[i]);
s.total=0;
for(i=0;i<3;i++)
s.total=s.total + s.sub[i];
printf(“\nStudent Name = %s”,s.name);
printf(“\nTotal Marks = %d”,s.total);
}

ARRAY OF STRUCTURES

A similar type of structure variables placed with a common variable name is called an
array of structures. Array of structure concept is used to define more than one structure
variable of the same type.

The general format of defining array of structures is:

Syntax: struct Tag


{
datatype member1;
datatype member2;
-----
-----
datatype membern;
}
Variable[size];

Where,
 struct is a keyword used to define the structure.
 Tage specifies name of the structure that follows same rules as a valid identifier.
 Member1, Member2, - - - - , Membern are the elements of the structure.
 Variable species name of the structure variable that follows same rules as a valid
identifier.
 Size represents maximum number of structure variables.

Page 127
/* EXAMPLE PROGRAM TO READ A LIST OF STUDENTS INFORMATION AND PRINT THEM IN
ASCENDING ORDER OF THEIR AVERAGE MARKS USING ARRAY OF STRUCTURES */

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

struct student
{
char name[50],branch[5];
int sub1,sub2,sub3;
float avg;
}s[10];

main()
{
int i,j,n;
struct student temp;
clrscr();
printf("\nEnter how many students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fflush(stdin);
printf("\nEnter student %d Name:",i);
gets(s[i].name);
fflush(stdin);
printf("\nEnter student %d Branch:",i);
gets(s[i].branch);
printf("\nEnter 3 subject Marks:");
scanf("%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3);
}
for(i=1;i<=n;i++)
s[i].avg=(s[i].sub1+s[i].sub2+s[i].sub3)/3.0;

for(i=1;i<=n-1;i++)
{
for(j=i+1;j<=n;j++)
{
if(s[i].avg>s[j].avg)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}

printf("\nStudent Details As Per Their Averge Marks Are:");


for(i=1;i<=n;i++)
printf("\n%s\t%s\t%.2f",s[i].name,s[i].branch,s[i].avg);
}
Initializing Array of Structures:

Page 128
Array of structures can be initialized at the time of its declaration by a list of values
placed within pair of braces.

Example: struct student


{
char name[50],branch[5];
int sub1,sub2,sub3;
}
s[10] = { { “satish kumar”,”cse”,67,89,90} ,
{ “praveen”, “it”,45,78,89}
};

/* EXAMPLE PROGRAM FOR INITIALIZING ARRAY OF STRUCTURES */

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

struct student
{
char name[50],branch[5];
int sub1,sub2,sub3;
}
s[10] = { { “satish kumar”,”cse”,67,89,90} , { “praveen”, “it”,45,78,89}};

main()
{
int i;
clrscr();
printf(“\nStudents Details Are=\n”);
for(i=0;i<2;i++)
printf(“%s\t%s\t%d\t%d\t%d”,s[i].name,s[i].branch,s[i].sub1,s[i].sub2,s[i].sub3);
}

NESTED STRUCTURES (OR) STRUCTURE WITHIN STRUCTURE

When a structure is declared as the member of another structure, such representation


is known as nested structures (or) structure within structure. The general format of nested
structures is:

Syntax: struct Outer


{
---
---
struct Inner
{
---
---
}InnerVariable;
---
---
}OuterVariable;

Page 129
Example: struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st;

 Dot operator is used to access the members of the innermost as well as the outermost
structures. The general format of accessing inner structure members is:

Syntax: OuterStructureVariable.InnerStructureVariable.InnerMember;

Example: st.Join.d;

/* EXAMPLE PROGRAM FOR NESTED STRUCTURES */

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

struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st;
main()
{
clrscr();
printf("\nEnter Name of the Employee:");
gets(st.name);
printf("\nEnter Date of Joining:");
scanf("%d%d%d",&st.Join.d,&st.Join.m,&st.Join.y);
printf("\nEnter Salary of the Employee:");
scanf(“%f”,&st.salary);
printf("\nEMPLOYEE NAME:%s",st.name);
printf("\nSALARY :%.2f RS",st.salary);
printf("\nJOIN DATE :%d / %d / %d",st.Join.d,st.Join.m,st.Join.y);
}

/* EXAMPLE PROGRAM FOR INITIALIZING NESTED STRUCTURES */

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

struct Employee

Page 130
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st = {“Ravi Kumar”,10,6,2014,23456.25};
main()
{
clrscr();
printf("\nEMPLOYEE NAME:%s",st.name);
printf("\nSALARY :%.2f RS",st.salary);
printf("\nJOIN DATE :%d / %d / %d",st.Join.d,st.Join.m,st.Join.y);
}

STRUCTURES AND POINTERS

A structure pointer variable is created as similar to the creation of a structure variable.


A pointer to a structure is not itself a structure, but it’s a variable that holds the address of the
structure variable. For this type of pointer variable also compiler allocates only 2 bytes of
memory. The general format of structure pointer variable declaration is:

Syntax: struct Tag *PtrVariable;

Here, PtrVariable can be assigned to any other structure of the same type, and can be used to
access the members of its structure.

Example: struct Account


{
int Acno;
float AcBalance;
}S, *P;
P = &S;

‘→’ Arrow operator is used to access members of the structure with its pointer variable. ‘→’
operator is formed with the combination of a minus (-) sign and a greater than(>) symbol.
The general format of accessing structure member with the structure pointer variable is:

Syntax : PtrVariable → Member;

Example : P → Acno;

The same representation can also be placed with dot operator is as:

Syntax : (*PtrVariable) . Member;

Example : (*P).Acno;

/* EXAMPLE PROGRAM FOR STRUCTURE POINTER VARIABLE */

Page 131
#include<stdio.h>
#include<conio.h>
struct Account
{
int Acno;
float AcBalance;
}S={111,35000.75}, *P;

main()
{
clrscr();
P=&S;
printf("\nACCOUNT INFORMATION IS:");
printf("\n%d\t%.2f",P→Acno,P→AcBalance);
}

/* PROGRAM FOR ACCESSING STRUCTURE MEMBERS IN DIFFERENT WAYS */

#include<stdio.h>
#include<conio.h>
struct demo
{
int x;
float y;
char z;
};
main()
{
struct demo s={10,345.72,'K'},*p;
clrscr();
printf("\nWith Variable and Dot Operator:");
printf("\n%d\t%.2f\t%c",s.x,s.y,s.z);
p=&s;
printf("\nWith Pointer Variable and Arrow Opeator:");
printf("\n%d\t%.2f\t%c",p→x,p→y,p→z);
printf("\nWith Pointer Variable and Dot Opeator:");
printf("\n%d\t%.2f\t%c",(*p).x,(*p).y,(*p).z);
}

STRUCTURES AND FUNCTIONS

A structure can also be passed as an argument to a function in three ways. Those are:

Case 1: Passing individual member of the structure as an argument


Case 2: Passing entire structure as an argument
Case 3: Passing address of the structure as an argument
Case 1: When an individual member of the structure is passed as an argument to a
function, a copy of member value is passed from calling function to the called function.
Here, Member value is copied into the formal argument of the called function.

Page 132
Then if we made any changes inside the function with the received value, those
changes are not recognized by the outside function. Since, entire changes are effects only on
the formal arguments.

/* PROGRAM TO PASS INDIVIDUAL MEMBER OF THE STRUCTURE AS AN ARGUMENT */

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

struct cricket
{
char name[15];
int matches;
float avg;
}s={"sachin",400,56.78};

void change(int);

main()
{
clrscr();
printf("\nBefore Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
change(s.matches);
printf("\nAfter Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
}
void change(int x)
{
x=410;
}

Case 2: When entire structure is passed as an argument to a function from calling


function to the called function, the receiving argument at the called function must be a
structure of the same type. Here, a copy of the entire structure is copied into the formal
structure of the called function.

Then if we made any changes inside the function with the received argument, those
changes are not recognized by the outside function. Since, entire changes effects only on the
formal structure.

/* PROGRAM TO PASS ENTIRE STRUCTURE AS AN ARGUMENT */

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

struct cricket
{
char name[15];

Page 133
int matches;
float avg;
}s={"sachin",400,56.78};

void change(struct cricket);

main()
{
clrscr();
printf("\nBefore Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
change(s);
printf("\nAfter Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
}
void change(struct cricket x)
{
strcpy(x.name,"sehwag");
x.matches=250;
x.avg=50.23;
}

Case 3: When address of the structure is passed as an argument to a function from


calling frunction to the called function, the receiving argument at the called function must be
a structure pointer variable of the same structure type. With this the pointer variable
indirectly points to the original structure.

Then if made any changes inside the function on structure, those changes are
recognized by outside function. So, that all changes are effects on the original structure.

/* EXAMPLE PROGRAM TO PASS ADDRESS OF THE STRUCTURE AS AN ARGUMENT */

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

struct cricket
{
char name[15];
int matches;
float avg;
}s={"sachin",400,56.78};

void change(struct cricket *);

main()
{
clrscr();
printf("\nBefore Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
change(&s);
printf("\nAfter Passing:");

Page 134
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
}
void change(struct cricket *k)
{
strcpy(k→name,"sehwag");
k→matches=250;
k→avg=50.23;
}
TYPEDEF (TYPE DEFINITION)

The typedef keyword allows the user to specify a new name for the existing data
types. The general format of the declaration statement using the typedef keyword is:

Syntax : typedef ExistingDataType NewName;

Where,
ExistingDataType may be either a primitive data type of user-defined data type.

Note: typedef declaration does not create any new data types. It just adds a new name for
the existing data type.

Example: 1. typedef int Integer;


Integer x,y,z;

2. typedef char Gender;


Gender x=’F’, y=’M’;
3. typedef char String[10];
String Name;

 typedef keyword is very useful in the case of user-defined data types like structure.
While using typedef keyword with the structure creation, structure tag is optional.

Example: typedef struct


{
float real, imag;
}Complex;

Complex k;

/* EXAMPLE PROGAM OF TYPEDEF WITH STRUCTURE */

#include<stdio.h>
#include<conio.h>
typedef struct
{
float real,imag;
}Complex;

main()
{
Complex k;

Page 135
clrscr();
printf("\nEnter Real Part:");
scanf("%f",&k.real);
printf("\nImaginary Part:");
scanf("%f",&k.imag);
printf("\nComplex Number is =%.2f + i %.2f",k.real,k.imag);
}
***
BIT FIELDS

In C language, bits are manipulated in two ways. Those are:

1. Implementation of bit-wise operators


2. Utilization of bit fields within structure.

1. Implementation of Bit-wise Operators: C language supports Bit-wise AND, Bit-


wise OR, Bit-wise Exclusive-OR, One’s complement, Left Shift and Right Shift operators as
bit-wise operators that are used for manipulating data at bit level of the operands.

OPERATOR MEANING

& Bit-wise AND


| Bit-wise OR
^ Bit-wise Exclusive-OR
~ One’s Complement
<< Left Shift
>> Right Shift

2. Utilization of bit fields within structure:

Bit fields utilization with the structure allows using the bit fields to hold data items
and hereby pack several data items in a single word of memory.

The name and size of bit fields are defined using structure. For bit fields memory is
allocated in adjacent bits. The general format of bit field definition is:

Syntax: struct tag


{
unsigned int member1 : bitwidth1;
unsigned int member2 : bitwidth2;
------
------
unsigned int membern : bitwidthn;
} variable;

Here,

 The data type of each member must be unsigned integer.


 Each bitwidth specifies number of bits used for the members.
 Each member is followed by a colon.
Page 136
Example : struct test
{
unsigned int x:5;
unsigned int y:4;
unsigned int z:6;
}val;

The main advantage of bit fields is to save some memory as against storing variables.
By this technique, the exact number of bits required by the bit field is specified. This way a
whole word is not required to hold the field. This helps in packing a number of bit fields into
single word of memory.

Note: scanf() function is not possible for reading values in bit field members. Since,
we can’t access address of a bit field member.

/* EXAMPLE PROGRAM FOR BIT FIELDS */

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

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

struct day
{
unsigned int d:5;
unsigned int m:4;
unsigned int y:4;
}val;

main()
{
val.d=16;
val.m=10;
val.y=15;
clrscr();
printf("\nCurrent Date =%u / %u / %u",val.d,val.m,val.y);
}
It is also possible to force a gap in between the data member fields. Consider the
following example program that forces bit gaps in between the data member fields.

/* EXAMPLE PROGRAM TO FORCE BIT GAP IN BETWEEN BIT FIELDS */

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

Page 137
struct day
{
unsigned int d:5;
:2;
unsigned int m:4;
:1;
unsigned int y:4;
}val;

main()
{
val.d=16;
val.m=10;
val.y=15;
clrscr();
printf("\nCurrent Date =%u / %u / %u",val.d,val.m,val.y);
}

ENUMERATION TYPES
An enumeration is a user defined data type. Enumeration data types are data items
whose values may be any member of a symbolically declared set of values. The symbolically
declared members are known as “enumeration constants”.

The general format of creating enumeration data type is:

Syntax : enum Tag


{
Member1, Member2, - - - - - , Membern
};

Where,
 enum keyword is used to define enumeration data types.
 Tag specifies name of the data type that follows same rules as a valid identifier.
 enum Tag forms as the user defined data type.
 Member1, Member2, - - -, Membern are called enumerators (or) enumeration
constants (or) enumeration list.

Each enumeration member is assigned with an integer value by the compiler. By


default, Member1 is given the value 0, Member2 is given the value 1 and so on. i.e., each
member value is obtained by adding 1 to the previous member value.

Example : enum Days


{
Mon, Tue, Wed, Thu, Fri, Sat, Sun
};

Once the enumeration list has been defined, corresponding enumeration variables can
be created as:

Syntax : enum Tag Variable1, Variable2, - - - -, Variablep;

Page 138
Example : enum Days start,end;

/* EXAMPLE PROGRAM FOR ENUMERATED DATA TYPE */

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

enum Days
{
Mon, Tue, Wed, Thu, Fri, Sat, Sun
};
main()
{
enum Days start,end;
clrscr();
start=Mon;
end=Sun;
printf(“\nStarting Value = %d”,start);
printf(“\nEnding Value = %d”,end);
printf(“\nMemory Size of start = %d Bytes”,sizeof(start));
printf(“\nMemory Size of end = %d Bytes”,sizeof(end));
}
Note:

Enumeration provides a convenient way to associate constant values with names as


alternative to #define statements.

Example: #define TRUE 1


#define FALSE 0

An alternative representation with enumeration data type is :

Example: enum flag


{
FALSE, TRUE
};

Initializing Enumerated Constants

It is also to associate numbers other than the sequence starting at zero with the names
in the enum data type by including a specific initialization in the variable name list.

/* EXAMPLE PROGRAM FOR INITIALIZING ENUMERATION CONSTANTS */

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

enum coins
{
p1,p2=45,p3,p4=80
};
Page 139
main()
{
clrscr();
printf("\nValue of p1:%d",p1);
printf("\nValue of p2:%d",p2);
printf("\nValue of p3:%d",p3);
printf("\nValue of p4:%d",p4);
}
ANONYMOUS ENUMERATION

The process of specifying an enumeration without tag is known as anonymous


enumeration. The general format of defining anonymous enumeration is:

Syntax : enum
{
Member1, Member2, - - - - - - , Membern
};
/* EXAMPLE PROGRAM FOR ANONYMOUS ENUMERATION */

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

enum
{
a,b,c
};
main()
{
clrscr();
printf("\nMember 1 Value=%d",a);
printf("\nMember 2 Value=%d",b);
printf("\nMember 3 Value=%d",c);
} ***
UNION

Union is also a user-defined data type which is similar to structure. i.e., Union is a
collection of non-homogeneous / heterogeneous / different data type elements that can be
grouped together under a common name.

The general format of a union declaration is:

Syntax : union Tag


{
Datatype Member1;
Datatype Member2;
---
---
Datatype Membern;
};
Where,

Page 140
 union is a keyword used to declare the union data type.
 Tag is name the union that follows same rules as a valid identifier.
 Members declared inside the union are known as union members (or) union elements.
 Union declaration must be ended with a semicolon.

Example : union Account


{
int acno;
float balance;
char type;
};

Memory is allocated for the union only at the time of creating union variable. The
general form of creating union variables is:

Syntax : union Tag Variable1, Variable2, - - - - - , Variablep;

Example : union Account X;

For this, the memory allocation will be:

 In union, compiler selects the member which occupies highest memory, and that
memory is reserved only. So, that all the members of the union are shared that
common memory. It implies that, although a union may contain many members of
different types, it can handle only one member at a time.

 Dot operator is used to access member of the union with the union variable. The
general format of accessing union members with union variable is:

Syntax : UnionVariable . Member;

Example : X . balance;

/* PROGRAM TO CREATE ACCOUNT DATABASE USING UNION */

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

union Account
{

Page 141
int acno;
char actype[10];
float acbalance;
};

main()
{
union Account x;
clrscr();
printf("\nEnter Account Number:");
scanf("%d",&x.acno);
printf("\nAccount Number:%d",x.acno);
fflush(stdin);
printf("\n\n\nEnter Account Type:");
gets(x.actype);
printf("\nAccount Type:%s",x.actype);
printf("\n\n\nEnter Balance Amount:");
scanf("%f",&x.acbalance);
printf("\nBalance Amount:%.2f RS",x.acbalance);
}

Program

1. Write a program to print memory size of union members and union variable.

Note:

1. The main difference between a structure and union is in terms of their storage space.
In structure, each member has its own storage location. Whereas. In union all
members shared a common memory.
2. The main advantage of union is to save memory compared to the structure with same
members.

/* Example program to show the difference between structure and union */

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

struct demo1
{
char a;
int b;
float c;
double d;
};

union demo2
{
char a;
int b;
float c;
double d;
};

Page 142
main()
{
struct demo1 sd;
union demo2 ut;
clrscr();
printf("\nMemory Size of Structure = %d Bytes",sizeof(sd));
printf("\nMemory Size of Union = %d Bytes",sizeof(ut));
}

3. A union may be a member of a structure and structure may by a member of union.

/* EXAMPLE PROGRAM TO USE STRUCTURE WITHIN UNION */

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

struct demo
{
int x;
float y;
};
union hello
{
float z;
struct demo p;
int k;
};
main()
{
union hello ut;
clrscr();
printf("\n Memory Size = %d Bytes”, sizeof(ut));
}

/* EXAMPLE PROGRAM TO USE UNION WITHIN STRUCTURE */

#include<stdio.h>
#include<conio.h>
union demo
{
int x;
float y;
};
struct hello
{
float z;
union demo p;
int k;
};
main()
{
struct hello ut;
clrscr();
printf("\n Memory Size = %d Bytes”, sizeof(ut));

Page 143
}

UNIT - V
INPUT OUTPUT STATEMENTS

C language supports various library functions that are used to perform input and
output operations.
In C language, input and output statements are classified into two types as:
i) Non-formatted Input Output Statements
ii) Formatted Input Output Statements

Input-Output Statements

Non-formatted input output statements Formatted input output statements

Non-formatted Non-formatted Formatted Formatted


Input statements Output statements Input statements Output statements

getchar() putchar() scanf() printf()


getch() putch()
getche() puts()
gets()

Non-formatted Input Statements

getchar(), getch() and getche() functions are known as non-formatted character input
statements. All these functions are used for reading a single character from the console input device –
Keyboard.
Page 144
a) getchar() Function:

getchar() library function is used for reading a single character from the keyboard.
The general format of getchar() function is:

Syntax : VariableName = getchar();


Where,
VariableName is a valid identifier of char data type.

When the statement is encountered, control waits for input character and key pressing. When
the enter key is pressed after typing the character, function accepts the character value with echoing
on the screen and then assigns to left hand side variable.

getchar() library function information is available in stdio.h header file.


/* EXAMPLE PROGRAM FOR getchar() FUNCTION */

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

main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getchar();
printf("\nResult Character=%c",ch);
}
b) getch() Function:

getch() library function is used for reading a single character from the keyboard. The
general format of getch() function is:

Syntax : VariableName = getch();


Where,
VariableName is a valid identifier of char data type.

When the statement is encountered, control waits for input character. When the character is
typed, function accepts the character without echoing on the screen and immediately assigns to left
hand side variable without pressing any key.

getch() library function information is available in conio.h header file.

/* EXAMPLE PROGRAM FOR getch() FUNCTION */

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

main()
{
char ch;
clrscr();
printf("\nEnter A Character=");

Page 145
ch=getch();
printf("\nResult Character=%c",ch);
}
b) getche() Function:

getche() library function is used for reading a single character from the keyboard.
The general format of getche() function is:

Syntax : VariableName = getche();


Where,
VariableName is a valid identifier of char data type.

When the statement is encountered, control waits for input character. When the character is
typed, function accepts the character with echoing on the screen and immediately assigns to left hand
side variable without pressing any key.

getche() library function information is available in conio.h header file.


/* EXAMPLE PROGRAM FOR getche() FUNCTION */

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

main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getche();
printf("\nResult Character=%c",ch);
}
Non-formatted Output Statements

putchar() and putch() functions are known as non-formatted character output statements. All
these functions are used for printing a single character on the console output device – Monitor.

a) putchar() Function:

putchar() library function is used for printing a single character on the monitor. The
general format of putchar() function is:

Syntax : putchar(VariableName);
Where,
VariableName is a valid identifier of char data type.

When the statement is encountered, function displays the character value on the monitor.

putchar() library function information is available in stdio.h header file.

/* EXAMPLE PROGRAM FOR putchar() FUNCTION */

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

Page 146
main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getchar();
printf("\nResult Character=”);
putchar(ch);
}
a) putch() Function:

putch() library function is used for printing a single character on the monitor. The
general format of putch() function is:

Syntax : putch(VariableName);
Where,
VariableName is a valid identifier of char data type.

When the statement is encountered, function displays the character value on the monitor.

putchar() library function information is available in conio.h header file.

/* EXAMPLE PROGRAM FOR putch() FUNCTION */

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

main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getchar();
printf("\nResult Character=”);
putch(ch);
}

Formatted Input Statements

scanf() function is known as formatted input statement.

scanf() Function:

scanf() library function is used for reading data from the console input device – Keyboard.
The general format of a scanf() function is:

Syntax : scanf(“Control String”, &Variable1, ------ , &Variablen);


Where,
 The control string consists of format of data being received. It forms with the combination of
% symbol followed by the conversion character of different data types.
 scanf() function requires & operator called address operator to locate memory location of the
identifier to store values.
 scanf() library function information is available in stdio.h header file.

Page 147
Format Specifications:

1) To read a character, provide at least one white space character in the conversion specification.

Example : scanf(“ %c”,&ch);

2) Conversion character should preceded with * symbol. It tells the compiler that the next input
field is to be read but not stored.

Example : int x;
float y;
scanf(“%d %*c%f”,&x,&y);

The above statement accepts one integer value, one character value and one real value. But it
stores only integer and real values.
Formatted Output Statements

printf() function is known as formatted output statement.

printf() Function:

printf() library function is used for displaying information on console output device –
Monitor. The general format of printf() function is:

Syntax : printf(“Control String”, Varible1, ------ ,Variablen);

Where,
 Control String specifies type of the data to be displayed. It forms with the combination of %
symbol followed by the conversion character of different data types. In addition to this,
control string allows three types of formats as:

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

Example : printf(“New Programs”);

Output : New Programs

2) Escape sequence characters are valid to print the output information in different ways.

Example : printf(“New \n Programs”);

Output : New
Programs

3) Format Specifications:

a) Output of Integer Values:

i. The format specification for printing an integer number is:

Page 148
Syntax : %Wd

Where, W specifies minimum field width for the output.

Example : printf(“%d”,7492); 77 4 9 2

ii. If the number size is greater than the specified field width size, then the compiler
automatically extends the field width to fit the output value.

Example : printf(“%2d”,7492);
7 4 9 2

iii. If the number size is less than the specified field width size, then the value is right
justified with leading blank spaces.

Example : printf(“%6d”,7492); 7 4 9 2
iv. It is possible to add zero’s at blank spaces by placing a ‘0’ before the field width
specifier.

Example : printf(“%06d”,7492); 0 0 7 4 9 2

v. “%#o” format specifier is used to add a leading ‘0’ for printing octal numbers.

Example : int p=071;


printf("%o",p); 71
printf("%#o",p); 071

vi. “%#x” format specifier is used to add a leading ‘0x’ for printing hexa decimal
numbers.

Example : int p = 0x71;


printf("%x",p); 71
printf("%#x",p); 0x71

vii. “%X” format specifier is used for printing hexa decimal numbers in capital letters.

Example : int p = 0xA6C1;


printf("%x",p); a6c1
printf("%X",p); A6C1

b) Output of Real Values:

i. The format specification to print the decimal notation of a floating point number is:

Syntax : %W.Pf
Where,

W specifies the minimum number of positions that are used for displaying the value.
P indicates the number of digits to be displayed after the decimal point.
While printing the value is rounded to P decimal places, and printed as right-justified.

Example : printf(“%f”,7491.2579); 7491.257900

Page 149
printf("%6.2f",7491.2579); 7491.26
printf("\n%6.2f",5678.3); 5678.30

ii. The format specification to print an exponential form of a floating point number is:

Syntax : %W.Pe

Ex: printf("%6.2e",7491245.2579); 7.49e+06

b) Output of Character Values:

The format specification for printing character values is:

Syntax : %Wc
Where,
The character will be displayed as right-justified in the field width of W columns.

Example : printf(“%3c”,’K’); K

d) Output of String Values:

The format specification for printing string values is:

Syntax : %Ws
Where,
The string will be displayed as right-justified in the field width of W columns.

Example : printf(“%5s”,”LAB”); L A B

d) Output of Mixed Values:

Different values can also be printed with in a single statement of prinf() statement.

Example : printf(“\n%s%4c%6d”,”LAB”,’@’,2015);

*****

Page 150
STRINGS

STRING

A String is defined as “an array of characters”. The general form of declaration of a


string variable is:

Syntax : char StringName [size];


Example : char str[100];

STRING INPUT/OUTPUT FUNCTIONS

gets() and puts() library functions are known as string input/output functions. These
functions are used for reading and print an entire line as a string including blank spaces.
These library functions information is available in stdio.h header file.

gets() function: gets() is a library function used for reading an entire line as a
string including blank spaces. The general format of a gets() function is:

Syntax : gets(string);

Example : gets(str);

puts() function: puts() is a library function used for printing an entire line as a
string including blank spaces. The general format of a puts() function is:

Syntax : puts(string);

Example : puts(str);

/* EXAMPLE PROGRAM FOR READING AND PRINT A STRING */

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

Page 151
main()
{
char str[50];
clrscr();
printf("\nEnter a line of text:");
gets(str);
printf("\nRESULT:");
puts(str);
}

STRING HANDLING FUNCTIONS

string.h header file provides various library function that are used for manipulating
the given strings in different ways. Some of the important library functions are:

1. strlen(): It refers to string length function.

The general format of strlen() function is:

Syntax : int strlen(string);

Function accepts a single argument as string and return length of the passed
string. Here, function counts number of characters as length includes blank spaces and
excluding the NULL character (‘\0’).

/* PROGRAM TO FIND LENGTH OF THE GIVEN STRING */

#include<string.h>
main()
{
char str[50];
int n;
clrscr();
printf("\nEnter a string:");
gets(str);
n=strlen(str);
printf("\nSTRING LENGTH IS:%d",n);
}

2. strcat() function: It refers to string concatenation function.

The general format of strcat() function is:

Syntax : strcat(targetstring , sourcestring);

Function is used to add the given two strings. Here, the contents of the source string
are added at the end of the target stirng.

/* PROGRAM TO ADD THE GIVEN TWO STRINGS */


Page 152
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
strcat(str1,str2);
printf("\nSTRING 1:");
puts(str1);
printf("\nSTRING 2:");
puts(str2);
}

3. strcpy() function: It refers to string copy function.

The general format of strcpy() function is:

Syntax : strcpy(targetstring , sourcestring);

Function is used to copy the contents of one string into another string. Here, the
contents of source string are copied into the target string.

Note: While declaring target string, its size should be equal or greater than the size of the
source string.

/* PROGRAM TO COPY THE CONTENTS OF ONE STRING INTO ANOTHER STRING */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
strcpy(str1,str2);
printf("\nSTRING 1:");
puts(str1);
printf("\nSTRING 2:");
puts(str2);
}

4. strcmp() function: It refers to string comparison function.

The general format of strcmp() function is:

Page 153
Syntax: int strcmp(string1 , string2);

Function is used to compare the given two strings.

Function performs comparison between two strings character by character until there
is a mismatch or end of the strings is reached, whichever occurs first. If the two strings are
identical, function returns 0 value. If they are not identical, function returns numerical
difference between the ASCII values of the first non-matching characters.

/* PROGRAM TO COMPARE THE GIVEN TWO STRINGS */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
int k;
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
k=strcmp(str1,str2);
if(k>0)
printf("\nSTRING 1 IS GREATER THAN STRING 2");
else if(k<0)
printf("\nSTRING 2 IS GREATER THAN STRING 1");
else
printf("\nBOTH STRIGNS ARE IDENTICAL");
}

5. strcmpi() function: It refers to string comparison ignore case function.

The general format of strcmpi() function is:

Syntax: int strcmpi(string1 , string2);

Function is used to compare the given two strings without case consideration.
/* PROGRAM TO COMPARE THE GIVEN TWO STRINGS WITHOUT CASE */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");

Page 154
gets(str2);
if((strcmpi(str1,str2))==0)
printf("\nBOTH STRIGNS ARE SAME");
else
printf("\nBOTH STRINGS ARE DIFFERENT");
}
6. strrev() function: It refers to string reverse function.

The general format of strrev() function is:

Syntax: strrev(string);

Function is used to reverse the contents of the given string.

/* PROGRAM TO PRINT A STRING IN REVERSE ORDER */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String:");
gets(str);
strrev(str);
printf("\n Reverse String =");
puts(str);
}

7. strlwr() function: It refers to string lower function.

The general format of strlwr() function is:

Syntax: strlwr(string);

Function is used to convert all characters in the given string from upper case to lower
case characters.

/* PROGRAM TO PRINT A STRING IN LOWER CASE */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String in Upper Case:");
gets(str);
strlwr(str);
printf("\nResult String in Lower Case =");

Page 155
puts(str);
}

8. strupr() function: It refers to string upper function.

The general format of strupr() function is:

Syntax: strupr(string);

Function is used to convert all characters in the given string from lower case to upper
case characters.

/* PROGRAM TO PRINT A STRING IN UPPER CASE */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String in Lower Case:");
gets(str);
strupr(str);
printf("\nResult String in Upper Case =");
puts(str);
}

9. strncat() function: The general format of strncat() function is:

Syntax: strncat(targetstring , sourcestring, n);

Where, n is an integer argument. Function appends atmost n characters of source


string to target string.

/* EXAMPLE PROGRAM */

#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
strncat(str1,str2,3);
printf("\nSTRING 1:");
puts(str1);
printf("\nSTRING 2:");
puts(str2);
}

Page 156
10. strncpy(): The general format of strncpy() function is:

Syntax: strncpy(targetstring , sourcestring , n);

Where, n is an integer argument. Function copies atmost n characters of source string


to target string.

/* EXAMPLE PROGRAM */

#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
strncpy(str2,str1,3);
str2[3]='\0';
printf("\nRESULT 1:");
puts(str1);
printf("\nRESULT 2:");
puts(str2);
}

11. strncmp() function: The general format of strncmp() function is:

Syntax: strncmp(string1 , string2 , n);

Where, n is an integer argument. Function compares atmost n characters of the given


two strings.

/* EXAMPLE PROGRAM */

#include<string.h>

main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
if((strncmp(str1,str2,3))==0)
printf(“\n Both Are Same”);
else
printf(“\n Both Are Different”);
printf("\nRESULT:%d",strncmp(str1,str2,3));
}

12. strncmpi() function: The general format of strncmpi() function is:

Page 157
Syntax: strncmpi(string1 , string2 , n);

Where, n is an integer argument. Function compares atmost n characters of the given


two strings without case consideration.

/* EXAMPLE PROGRAM */

#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
if((strncmpi(str1,str2,3))==0)
printf(“\n Both Are Same”);
else
printf(“\n Both Are Different”);
}

/* Write a program to check whether the given string is palindrome or not */

#include<string.h>
main()
{
char str1[50],str2[50];
int i,k;
clrscr();
printf("\nEnter a String :");
gets(str1);
strcpy(str2,str1);
strrev(str1);
if((strcmp(str1,str2))==0)
printf("\nPALINDROME");
else
printf("\nNOT PALINDROME");
}

PROGRAMS

1. Write a program to print length of the given string without using library functions.

main()
{
char str[50];
int i;
clrscr();
printf("\nEnter a String:");

Page 158
gets(str);
for(i=0;str[i]!='\0';i++);
printf("\nLength is:%d",i);
}

2. Write a program to copy contents of one string to another without using library functions.

main()
{
char str1[50],str2[50];
int i;
clrscr();
printf("\nEnter a String:");
gets(str1);
printf("\nOriginal String is:");
puts(str1);
for(i=0;str1[i]!='\0';i++)
str2[i]=str1[i];
str2[i]='\0';
printf("\nCopied String is:");
puts(str2);
}

3. Write a program to add the given two strings without using library functions.

main()
{
char str1[50],str2[50];
int i,j;
clrscr();
printf("\nEnter String 1:");
gets(str1);
printf("\nEnter String 2:");
gets(str2);
for(i=0;str1[i]!='\0';i++);
for(j=0;str2[j]!='\0';j++)
str1[i+j]=str2[j];
str1[i+j]='\0';
printf("\nResult String is:");
puts(str1);
}
4. Write a program to perform string comparison without using library functions.
main()
{
char str1[50],str2[50];
int i,k;
clrscr();
printf("\nEnter String 1:");
gets(str1);
printf("\nEnter String 2:");
gets(str2);
k=0;

Page 159
for(i=0;str1[i]!='\0'||str2[i]!='\0';i++)
{
if(str1[i]!=str2[i])
{
k=str1[i]-str2[i];
goto temp;
}
}
temp:
if(k>0)
printf("\nSTRING 1 IS GREATER THAN STRING 2");
else if(k<0)
printf("\nSTRING 1 IS LESS THAN STRING 2");
else
printf("\n BOTH ARE SAME");
}

5. Write a program to reverse the given string without using library functions.

/* PROGRAM TO REVERSE THE GIVEN STRING WITHOUT USING LIBRARY FUNCTIONS */

#include<stdio.h>
#include<conio.h>
main()
{
char str[50],temp;
int i,j,k;
clrscr();
printf("\nEnter A String =");
gets(str);
printf("\nOriginal String =%s",str);
for(k=0;str[k]!='\0';k++);
for(i=0,j=k-1;i<j;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
printf("\nReverse String =%s",str);
}

6. Write a program to check whether the given string is palindrome or not without using library
functions.
main()
{
char str1[50];
int i,n,j,k=0;
clrscr();
printf("\nEnter a String :");
gets(str1);
for(n=0;str1[n]!='\0';n++);
for(i=0,j=n-1;i<j;i++,j--)
{

Page 160
if(str1[i]!=str1[j])
{
printf(“\n NOT PALINDROME”);
exit();
}
}
printf("\nPLAINDROME");
}

7. Write a program to insert a sub string into the main string.

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[100],sub[50];
int len1,len2,pos,i,j;
clrscr();
printf("\nEnter Main String =");
gets(str);
printf("\nEnter Sub String To Insert =");
gets(sub);
printf("\nEnter Position To Insert =");
scanf("%d",&pos);
len1=strlen(str);
len2=strlen(sub);
if(pos>len1)
printf("\nINSERTION NOT POSSIBLE");
else
{
for(i=len1;i>=pos-1;i--)
str[i+len2]=str[i];
for(i=pos-1,j=0;j<len2;i++,j++)
str[i]=sub[j];
}
printf("\nResultant String is = %s",str);
}

8. Write a program to delete specified number of characters from the main string.

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[50];
int i,len,pos,nc;
clrscr();
printf("\nEnter Main String:");
gets(str);
printf("\nEnter Position to Delete:");
scanf("%d",&pos);

Page 161
printf("\nEnter Number of Characters to Delete:");
scanf("%d",&nc);
len=strlen(str);
for(i=pos-1;i<len;i++)
str[i]=str[i+nc];
printf("\nResultant String is =%s",str);
}

INITIALIZATION OF STRINGS

 The general format of initializing a string is:

Syntax : char stringname[size] = “string value”;

Here, collection of characters is placed within double quotation marks and termed as
string constant.

Example : char str[50] = “Language in 1972”;

/* EXAMPLE PROGRAM FOR INITIALING A STRING */

#include<stdio.h>
#include<conio.h>
main()
{
char str[50]="Language in 1972";
clrscr();
printf("\nResult String = %s",str);
}

 Strings can also be initialized in the form of character array. In such cases, explicitly it is
necessary to add the NULL character (‘\0’) at the end of the string value.

Syntax : char stringname[size] = { ‘value1’ , ‘value2’, … , ‘\0’};

Example : char str[10] = {‘H’ , ‘E’ , ‘L’ , ‘L’ , ‘O’ , ‘\0’};

 A string can also be initialized by omitting the string size. In such cases, compiler
automatically allocates sufficient memory for the string by counting number of
initialized characters.

Example : char str[ ] = “HELLO”;

TWO DIMENSIONAL ARRAY OF CHARACTERS (OR) ARRAY OF STRINGS

Collection of strings is treated as two dimensional array of characters (or) array of


strings. The general format of array of strings is:

Syntax : char stringname[size1][size2];


Where,
Stringname is name of the string that follows same rules as valid identifier.

Page 162
Size1 represents maximum number of strings and size2 represents maximum number
of characters in each string.
Example: char str[10][15];

/* PROGRAM TO PRINT LIST OF NAMES IN ALPHABETICAL ORDER */

#include<stdio.h>
#include<string.h>
main()
{
char x[15][15],temp[15];
int i,j,n;
clrscr();
printf("\nEnter how many names:");
scanf("%d",&n);
printf("\nEnter %d Names:",n);
for(i=0;i<n;i++)
{
fflush(stdin);
gets(x[i]);
}
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if((strcmp(x[i],x[j]))>0)
{
strcpy(temp,x[i]);
strcpy(x[i],x[j]);
strcpy(x[j],temp);
}
}
}
printf("\nLIST OF NAMES IN ALPHABETICAL ORDER ARE:\n");
for(i=0;i<=n-1;i++)
puts(x[i]);
}
INITIALIZATION OF TWO DIMENSIONAL CHARACTER ARRAYS

 The general format of initializing array of strings is:

Syntax : char arrayname[size1][size2] = {“string1” , “string2” , ……… };

Example : char x[3][10]={ “India” , “Pakistan” , “Srilanka”};

/* PROGRAM FOR INITIALIZING ARRAY OF STRINGS */

#include<stdio.h>
#include<conio.h>
main( )

Page 163
{
char x[3][10]={ “India” , “Pakistan” , “Srilanka”};
clrscr();
printf(“\n List of Strings Are =\n”);
for(i=0;i<3;i++)
puts(x[i]);
}

 Array of strings can also be initialized in the form of array of characters.

Syntax : char arrayname[size1][size2] = { {‘char1’ , ‘char2’ , …… , ‘\0’} ,


{‘char1’ , ‘char2’ , …… , ‘\0’} ,
-
-
{‘char1’ , ‘char2’ , …… , ‘\0’}
};

Example : char x[3][10]={ {‘I’ , ‘n’ , ‘d’ , ‘i’ , ‘a’ , ‘\0’} ,


{‘P’ , ‘a’ , ‘k’ , ‘i’ , ‘s’ , ‘t’ , ‘a’ , ‘n’ , ‘\0’} ,
{‘S’ , ‘r’ , ‘i’ , ‘l’ , ‘a’ , ‘n’ , ‘k’ , ‘a’ }
};

 While initializing array of strings, size1 can be omitted. In such cases, compiler
allocates sufficient memory by counting number of initialized strings.

Example : char x[ ][10]={ {‘I’ , ‘n’ , ‘d’ , ‘i’ , ‘a’ , ‘\0’} ,


{‘P’ , ‘a’ , ‘k’ , ‘i’ , ‘s’ , ‘t’ , ‘a’ , ‘n’ , ‘\0’} ,
{‘S’ , ‘r’ , ‘i’ , ‘l’ , ‘a’ , ‘n’ , ‘k’ , ‘a’ }
};

STRING / DATA CONVERSION FUNCTIONS

stdlib.h (standard library header file) header file supports various library functions
that are used to convert the given strings into other forms and vice-versa. Some of the
important library functions are:

1. atoi() function: atoi() function converts a string of digits into an integer value.
The general format of the atoi() function is:

Syntax: int atoi(string);

Function accepts a string as an argument and returns the result value as an integer.

/* EXAMPLE PROGRAM FOR atoi() FUNCTION*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
Page 164
char x[10]="2009";
int k;
clrscr();
k=atoi(x)+6;
printf("\nRESULT VALUE:%d",k);
}

2. itoa() function: atoi() function converts an integer value into a string. The
general format of the itoa() function is:

Syntax: char * itoa(int , char[] , int);


Where,
First argument is an integer value used for conversion.
Second argument is a string used to store the conversion value.
Third argument is an integer value that represents format of conversion such as
decimal, octal and hexa-decimal format.

/* EXAMPLE PROGRAM FOR itoa() FUNCTION*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>>
main()
{
char x[10];
int k=49;
clrscr();
itoa(k,x,10);
printf("\nDecimal Format:");
puts(x);
printf("\nOctal Format:");
itoa(k,x,8);
puts(x);
printf("\nHexadecimal Format:");
itoa(k,x,16);
puts(x);
}
3. atol() function: atol() function converts a string of digits into a long integer
value. The general format of the atol() function is:

Syntax: long int atol(string);

Function accepts a string as an argument and returns the result value as a long integer.

/* EXAMPLE PROGRAM FOR atol() FUNCTION*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
char x[10]="2009";

Page 165
long int k;
clrscr();
k=atol(x)+6;
printf("\nRESULT VALUE:%ld",k);
}

4. ltoa() function: ltoa() function converts a long integer value into a string. The
general format of the ltoa() function is:

Syntax: char * ltoa(long int , char[] , int);


Where,
First argument is a long integer value used for conversion.
Second argument is a string used to store the conversion value.
Third argument is an integer value that represents format of conversion such as
decimal, octal and hexa-decimal format.

/* EXAMPLE PROGRAM FOR ltoa() FUNCTION*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>>
main()
{
char x[10];
long int k=49;
clrscr();
ltoa(k,x,10);
printf("\nDecimal Format:");
puts(x);
printf("\nOctal Format:");
ltoa(k,x,8);
puts(x);
printf("\nHexadecimal Format:");
ltoa(k,x,16);
puts(x);
}

5. atof() function: atof() function converts a string of digits into a real value. The
general format of the atof() function is:

Syntax: float atof(string);

Function accepts a string as an argument and returns the result value as a real value.

/* EXAMPLE PROGRAM FOR atof() FUNCTION*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
char x[10]="2009";

Page 166
float k;
clrscr();
k=atof(x)+6;
printf("\nRESULT VALUE:%f",k);
}

RANDOM NUMBERS

A random number is a number selected from a set in which all members have the
same probability being selected.
C language supports rand() library function to generate pseudorandom numbers.
rand() library function information is available in stdlib.h header file. The general format of
rand() function is:

Syntax : int rand();

Function returns a pseudorandom integer value between 0 and 32,767.

/* PROGRAM TO GENERATE PSEUDO RANDOM NUMBERS */

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

main()
{
int k,n,i;
clrscr();
printf("\nEnter How Many Numbers =");
scanf("%d",&n);
printf("\nPseudo Random Numbers Are=\n");
for(i=1;i<=n;i++)
{
k=rand();
printf("\t%d",k);
}
}

I/O FUNCTIONS

Page 167
STREAM

A stream is a sequence of flow of data bytes, which is used to read and write data. The
streams that represent the input data of program are known as input streams and the streams that
represent the output data of program are known as output streams.

Input Stream
Input
Devices

C Program
Code

Output
Devices
Output Stream

Input streams interpret data from different input devices such as keyboard, mouse etc., and
provide as input data to the program.
Output streams obtain data from the program and write the data on different output devices
such as memory unit or print them on the screen.

Therefore, stream acts as an interface between a program and input/output devices.

I/O FUNCTIONS
Depending on type of the devices used for input output operations, I/O functions are classified
into three categories as:

1. Console I/O Functions : Functions to receive input from keyboard


and display on monitor

2. Disk I/O Functions : Functions to perform I/O operations on


secondary storage devices like floppy disk,
hard disk etc.,

3. Port I/O Functions : Functions to perform I/O operations on


various ports of the computer.

1. CONSOLE I/O FUNCTIONS

Console I/O functions always use the terminals keyboard and screen as the target place.
These functions work on console effectively as long as the data is small. Console representation is
not suitable to manage large volume of data.

Console I/O functions can further classified into two categories as formatted and un-
Formatted console I/O functions.

Page 168
Console I/O Functions

Formatted I/O Functions Un-formatted I/O Functions

scanf() getch()
printf() getche()
getchar()
putch()
putchar()
gets()
puts()

2. DISK I/O FUNCTIONS

Disk I/O functions are performed input and output operations with the utilization of secondary
storage devices like floppy disk, hard disk etc., In disk I/O operations data is stored interms of files.

FILES

A file is a collection of information that is stored at a particular area on the disk.

File stream is a sequence of bytes, which is used to read and write data on files.

File name is a string of characters that make up a valid name for the operating system. It
may contain two parts as a primary name and an optional period with an extension.

Syntax : PrimaryPart . SecondaryPart


Where,
Primary part specifies name of the file and secondary part specifies extension to locate type of
the file.

Example: Input.dat (Data File)


Sum.c (C Language File)
Cpath.bat (Batch File)
Hello.exe (Executable File) etc.,
Basic operations performed on the files are:

1. Defining (or) Naming a file


2. Opening a file
3. Reading data from a file
4. Writing data into a file
5. Closing a file.

Defining and Opening a File

All files should be declared as type FILE, which is a defined data type by the compiler. The
general format of declaring and opening a file is:

Page 169
Syntax : FILE *FilePointer; /* Declaration */

FilePointer = fopen(“FileName”, “Mode”); /* Opening */

Where,
 FilePointer defines as a “pointer to the data type FILE”.
 fopen() function receives two arguments – FileName and Mode.

o FileName is name of the file to be opened. FileName in C language can also contain
path information. The path specifies the drive and/or director where the file is
located.
o Mode specifies the type of job to be performed on the file. Mode can be any one of
the following.

MODE MEANING

r Open the file for reading only


w Open the file for writing only
a Open the file for appending data

 When the file is opened in read mode, if it exists, the file is opened with
current contents safe; otherwise, an error occurs.
 When the file is opened in write mode, if it exists, the file is opened with
current contents are deleted; otherwise, a file with specified name is created
by the compiler.
 When the file is opened in append mode, if it exists, the file is opened with
current contents safe and the file pointer placed at the end of the file;
otherwise, a file with specified name is created by the compiler.

Most of the recent compilers include additional modes of operations as

MODE MEANING

r+ Open the file for reading and writing


w+ Open the file for writing and reading
a+ Open the file for appending data and reading

Reading data from a file

Simplest input statement used for reading data from a file is getc() function.

getc() library function is used to read a character from the file that has been opened in read
mode. The general format of getc() function is:

Syntax : ch = getc(FilePointer);

Where,
ch is character type variable.
Here,
File Pointer is opened in read mode, and the function read the data character by character
from the file and assigned to the variable ch. Whenever the end of the file has been reached, getc()
function will return and end-of-file marker EOF.

Page 170
Writing data into a file

Simplest output statement used for writing data into the file is putc() function.

putc() library function is used to write a character into the file that has been opened in write
mode. The general format of putc() function is:

Syntax: putc(ch, FilePointer);

Where,
ch is character type variable.
Here,
FilePointer is opened in write mode and the function writes the data of ch into the file.

Closing a File

When all operations are completed over files, it is better to close the files explicitly by calling
fclose() function; when we want to open the same file in a different mode. For this, use the syntax as:

Syntax: fclose(FilePointer);

/* PROGRAM TO COPY THE CONTENTS OF ONE FILE INTO ANOTHER FILE */

#include<stdio.h>
main()
{
char ch;
FILE *fp1,*fp2;
clrscr();
fp1=fopen("demo.txt","r");
if(fp1==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
fp2=fopen("exam.txt","w");
while((ch=getc(fp1))!=EOF)
{
putc(ch,fp2);
}
fclose(fp2);
fclose(fp1);
}

***

ERROR HANDLING MECHANISM DURING I/O OPERATIONS

It is possible that errors may occur during I/O operations on files. Typical errors are:

 Trying to use a file that has not been opened.

Page 171
 Trying to perform an operation on a file, when the file is opened in another mode.
 Opening a file with an invalid name.
 Trying to read beyond the end-of-file mark etc.,

To handle most of these errors on files, C language provides two library functions ferror() and feof()
that can help us to detect I/O errors and perror() function for printing error messages.

1) When the file is opened using fopen() function, a file pointer is returned. If the file cannot be
opened with some reason, then the function returns a NULL pointer. This facility can be used
to test whether a file has been opened or not.

Example: if(fp == NULL)


{
---
---
}
2) feof() Function:

feof() is a library used to test for end-of-file condition. The general format of feof() function
is:

Syntax : feof(FilePointer)

Function accepts FilePointer as its only argument and returns a non-zero integer value if EOF
reached; otherwise, it returns zero.

3) ferror() Function:

ferror() is a library function used to report error status of the file indication. The general
format of ferror() function is:

Syntax: ferror(FilePointer)

Function accepts FilePointer as its only argument and returns a non-zero integer value if an
error has been detected up to that point during processing; otherwise, it returns zero.

4) perror() Function:

perror() is a standard library function used to print error messages specified by the compiler.

With this function, whenever an error occurred; the function prints error message to stderr.

The general format of perror() function is:


Syntax : perror(“string”);

Here, First the argument string is printed, then a colon, then a message corresponding to the current
value of error, finally a new line.

/* EXAMPLE PROGRAM FOR ERROR HANDLING MECHANISM */

#include<stdio.h>

Page 172
#include<conio.h>

main()
{
FILE *f;
char ch;
clrscr();
f=fopen("out.dat","w");
while(!feof(f))
{
ch=fgetc(f);
if(ferror(f))
{
perror("Error Occured:");
exit();
}
putchar(ch);
}
fclose(f);
}
/* WAP TO READ THE DATA FROM KEYBOARD AND WRITE IT INTO A FILE */

#include<stdio.h>
main()
{
char ch;
FILE *fp;
clrscr();
fp=fopen("demo.txt","w");
printf("\nEnter Text:");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
}
/* WRITE A PROGRAM TO READ THE DATA FROM A FILE AND PRINT IT ON MONITOR */

#include<stdio.h>
main()
{
char ch;
FILE *fp;
clrscr();
fp=fopen("demo.txt","r");
if(fp==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
printf("\nFile Contents Are:");
ch=getc(fp);

Page 173
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
}
/* WRITE A PROGRAM TO APPEND THE DATA INTO A FILE */

#include<stdio.h>
main()
{
char ch;
FILE *fp;
clrscr();
fp=fopen("demo.txt","a");
printf("\nEnter Additional Data:\n");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
}

/* WRITE A PROGRAM TO MERGE TWO FILES INTO A THIRD FILE */

#include<stdio.h>
main()
{
char ch;
FILE *f1,*f2,*f3;
clrscr();
f1=fopen("demo1.txt","r");
f3=fopen("result.txt","w");
if(f1==NULL)
{
printf("\nFile Opening Error");
exit();
}
while((ch=fgetc(f1))!=EOF)
fputc(ch,f3);
fcloseall();

f2=fopen("demo2.txt","r");
f3=fopen("result.txt","a");
if(f2==NULL)
{
printf("\nFile Opening Error");
exit();
}
while((ch=fgetc(f2))!=EOF)
fputc(ch,f3);

Page 174
fcloseall();
f3=fopen("result.txt","r");
if(f3==NULL)
{
printf("\nFile Opening Error");
exit();
}
printf("\nMERGING CONTENTS ARE:\n");
while((ch=fgetc(f3))!=EOF)
printf("%c",ch);
fclose(f3);
}
/* WRITE A PROGRAM TO READ THE DATA FROM A FILE AND PRINT NUMBER OF
CHARACTERS, WORDS, DIGITS, LINES AND SPECIAL SYMBOLS */

#include<stdio.h>
main()
{
char ch;
FILE *fp;
int nc=0,nd=0,nw=1,nl=1,nsp=0;
clrscr();
fp=fopen("check.txt","r");
if(fp==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
while((ch=getc(fp))!=EOF)
{
if((ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z'))
nc=nc+1;
else if(ch>='0'&&ch<='9')
nd=nd+1;
else if(ch==' '||ch=='\t')
nw=nw+1;
else if(ch=='\n')
{
nw=nw+1;
nl=nl+1;
}
else
nsp=nsp+1;
}
printf("\n No of Characters:%d",nc);
printf("\n No of Digits:%d",nd);
printf("\n No of Words:%d",nw);
printf("\n No of Lines:%d",nl);
printf("\n No of Special Symbols:%d",nsp);
fclose(fp);
}
Input and Output operations on Files

1. fgetc() and fputc() functions:

Page 175
fgetc() and fputc() are character oriented functions that provides same functionality as getc()
and putc() functions.

fgetc() function: fgetc() function is used to read a character from a file that has been opened in
read mode. The general format of the fgetc() function is:

Syntax: ch = fgetc(FilePointer);

Where,
ch is character type variable.
Here,
File Pointer is opened in read mode, and the function read the data character by character
from the file and assigned to the variable ch. Whenever the end of the file has been reached, fgetc()
function will return an end-of-file marker EOF.

fputc() function: fputc() function is used to write a character into a file that has been opened in
write/append mode. The general format of the fputc() function is:

Syntax: fputc(ch, FilePointer);

Where,
ch is character type variable.
Here,
FilePointer is opened in write/append mode and the function writes the data of ch into the file.

/* PROGRAM TO COPY THE CONTENTS OF ONE FILE INTO ANOTHER FILE CHARACTER BY CHARACTER*/

#include<stdio.h>
main()
{
char ch;
FILE *fp1,*fp2;
clrscr();
fp1=fopen("demo.txt","r");
if(fp1==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
fp2=fopen("exam.txt","w");
while((ch=fgetc(fp1))!=EOF)
{
fputc(ch,fp2);
}
fclose(fp2);
fclose(fp1);
}
2. fgets() and fputs() functions:

fgets() and fputs() functions are string oriented functions that can be handled an entire line as
a string at a time.

fgets() function: fgets() function is used to read a set of characters as a string from a
given file. The general format of the fgets() function is:
Page 176
Syntax: fgets(char[], int, FilePointer);
Where,
The first argument is the character array where the string is stored.
The second argument is the maximum size of the string.
The third argument is the FilePointer of the file to be read.
The function returns a NULL pointer if the end of file has been reached.

fputs() function: fputs() function is used to write a string into a file. The general format of the
fputs() function is:

Syntax: fputs(char[], FilePointer);

Where,
The first argument is the character array to be written into the file.
The second argument is the FilePointer of the file to write.
The function returns a non-negative value on successful completion; otherwise, it returns EOF.

/* PROGRAM TO COPY THE CONTENTS OF ONE FILE TO ANOTHER FILE LINE BY LINE */

#include<stdio.h>
#include<string.h>
main()
{
char ch[50];
FILE *fp1,*fp2;
clrscr();
fp1=fopen("check.txt","r");
if(fp1==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}

fp2=fopen("ptr.txt","w");
while((fgets(ch,sizeof(ch),fp1))!=NULL)
fputs(ch,fp2);
fclose(fp2);
fclose(fp1);
}
/* PROGRAM TO READ THE DATA FROM A FILE AND PRINT NUMBER OF LINES IN IT */

#include<stdio.h>
#include<conio.h>
main()
{
char ch[50];
FILE *fp;
int lines=0;
clrscr();
fp=fopen("check.txt","r");
if(fp==NULL)
{

Page 177
printf("\nFILE OPENING ERROR");
exit();
}
while((fgets(ch,sizeof(ch),fp))!=NULL)
{
lines=lines+1;
}
printf("\n No of Lines =%d",lines);
fclose(fp);
}
3. getw() and putw() functions:

getw() and putw() are number oriented functions are used to read and write integer values on
a given file.

getw() function: getw() function is used to read an integer value from a given file.
The general format of the getw() function is:

Syntax: getw(FilePointer);

This function receives FilePointer as an argument and returns next integer from the input file. It
returns EOF whenever end of file has been reached.

putw() function: putw() function is used to write an integer value into the specified file. The
general format of the putw() function is:

Syntax: putw(N,FilePointer);

Where,
N is an integer value to be written into the given file with FilePointer opened in write mode.

/* WRITE A PROGRAM TO CREATE AN INPUT DATA FILE WHICH CONTAINS A LIST OF


INTEGERS. READ THE SAME DATA FROM THE FILE AND WRITE EVEN AND ODD
NUMBERS INTO TWO SEPARTE FILES */

#include<stdio.h>
#include<conio.h>
main()
{
int item,n,i;
FILE *f1,*f2,*f3;
clrscr();
f1=fopen("input.dat","w");
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=1;i<=n;i++)
{
scanf("%d",&item);
putw(item,f1);
}
fclose(f1);
f1=fopen("input.dat","r");
if(f1==NULL)

Page 178
{
printf("\nFILE OPENING ERROR");
exit();
}
f2=fopen("even.dat","w");
f3=fopen("odd.dat","w");
while((item=getw(f1))!=EOF)
{
if(item%2==0)
putw(item,f2);
else
putw(item,f3);
}
fcloseall();
printf("\nEVEN NUMBERS ARE:");
f2=fopen("even.dat","r");
while((item=getw(f2))!=EOF)
printf("%6d",item);
fclose(f2);
printf("\nODD NUMBERS ARE:");
f3=fopen("odd.dat","r");
while((item=getw(f3))!=EOF)
printf("%6d",item);
fclose(f3);
}
4. fprintf() and fscanf() functions:

Most compilers support two functions namely fprintf() and fscanf() functions, that can handle
a group of mixed data simultaneously. The functions fprintf() and fscanf() perform I/O operations
that are identical to printf() and scanf() functions, except that they work on files.

fscanf() funcnton: fscanf() function is used to read mixed data simultaneously form a given file.
The general format of the fscanf() function is:

Syntax: fscanf(FilePointer, “ControlString”, List);

Where,
FilePointer associated with the file that has been opened for reading.
ControlString consists of format specification for the items in the list.
List may include variables, constants, strings etc.,
Function returns EOF marker whenever end of the file has been reached.

fprintf() function: fprintf() function is used to write mixed data simultaneously into a given file.
The general format of the fpritnf() function is:

Syntax: fprintf(FilePointer, “ControlString”, List);

Where,
FilePointer associated with the file that has been opened for writing.
ControlString consists of output format specification for the items in the list.
List may include variables, constants, strings etc.,

Page 179
/* WRITE A PROGRAM TO CREATE A FILE THAT CONTAINS INVENTORY DETAILS LIKE
PRODUCT NUMBER, PRODUCT NAME AND PRODUCT COST. READ THE SAME DATA
FROM THE FILE AND PRINT IT */

#include<stdio.h>
#include<conio.h>
struct product
{
int id;
char name[20];
float price;
}p;
main()
{
char flag='y';
FILE *f;
clrscr();
f=fopen("product.dat","w");
while(flag=='y')
{
printf("\nEnter product id:");
scanf("%d",&p.id);
fflush(stdin);
printf("\nEnter product name:");
gets(p.name);
printf("\nEnter product cost:");
scanf("%f",&p.price);
fprintf(f,"%d\t%s\t%f\n",p.id,p.name,p.price);
printf("\nDo you want add another record(y/n):");
fflush(stdin);
flag=getchar();
}
fclose(f);
f=fopen("product.dat","r");
if(f==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
printf("\nPRODUCT DETAILS ARE:\n");
while((fscanf(f,"%d%s%f",&p.id,p.name,&p.price))!=EOF)
printf("\n%d\t%s\t%.2f",p.id,p.name,p.price);
fclose(f);
}
STANDARD DOS SERVICES / STREAMS

fopen() function is used to open a file in a specified mode. Ms-Dos also predefines pointers
for five standard files. To access these pointers, we need not use fopen() function. Those standard
file pointers are:

STANDARD FILE POINTER DESCRIPTION

stdin Standard input device (Keyboard)


Page 180
stdout Standard output device (Monitor)
stderr Standard error device (Monitor)
stdaux Standard auxiliary device (Serial Port)
stdprn Standard printing device (Printer)

/* WRITE A PROGRAM TO READ DATA FROM STANDARD INPUT DEVICE AND PRINT IT
ON STANDARD OUTPUT DEVICE */

#include<stdio.h>
main()
{
char ch;
clrscr();
printf("\nEnter data:");
while((ch=fgetc(stdin))!=EOF)
fputc(ch,stdout);
}

/* WRITE A PROGRAM TO READ DATA FROM A FILE AND PRINT IT ON THE PRINTER */

#include<stdio.h>
main()
{
char ch;
FILE *f;
clrscr();
f=fopen("product.dat","r");
if(f==NULL)
{
printf("\nFile Opening Error");
exit();
}
while((ch=fgetc(f))!=EOF)
fputc(ch,stdprn);
}

FILE FORMATS

File formats can be categorized into two ways as: Text mode format and Binary mode
format. This classification arises at the time of opening the file.

When a file is opened either in “r”, “w” or “a” modes, default file format is text mode
format. If the user wants to open the file in binary format, explicitly necessary to specify as “rb”,
“wb”, or “ab”.

There are three main differences raised between a text file and binary files. Those are:
1. Handling of new lines
2. Representation of End-Of-File
3. Storage of numbers.

1. In text mode, a new line character is converted into the combination of carriage return – line
feed before being written into the disk.

Page 181
In binary mode, conversions not take place. A new line character is written into the disk as in
the original format.

2. In text mode, a special character is inserted after the last character in the file to mark the End-
Of-File. If this character is detected at any point in the file, then read function would return the EOF
signal to the program.
In binary format, there is no such special character present to mark the End-Of-File. The
binary mode files keep track of the End-Of-File from the number of characters present in the directory
entry of the file.

3. In text mode, while storing numbers in files, numbers are stored as string of characters.
Consider a number 4523.
In memory, it occupies 2 bytes. Whereas when the number placed on the disk, it would occupy 4
bytes as one byte per each character. Since, it depends on magnitude of the number.
In such case, large amount of data storage in a disk file is inefficient.
In binary mode, number would occupy same number of bytes on disk as it occupies in
memory unit. With this, the above number occupies only 2 bytes even on the disk file.
I/O Operations on Binary Files:

fread() and fwrite() functions are used to read and write data in binary format. The general
formats of fread() and fwrite() functions are:

Syntax: fread(&x, sizeof(x), 1, FilePointer);


fwrite(&x, sizeof(x), 1, FilePointer);
Here,
The first argument is address of the argument.
The second argument is size of the argument in bytes.
The third argument is number of arguments read or write at one time.
The final argument is the FilePointer.
/* WRITE A PROGRAM TO DEMONSTRATE THE DIFFERENCE BETWEEN TEXT MODE Vs
BINARY MODE FORMATS */
#include<stdio.h>
main()
{
int x;
float y;
char z='\n';
FILE *fp;
clrscr();
fp=fopen("Exam.txt","w");
printf("\nEnter One Integer and One Floating Number:\n");
scanf("%d%f",&x,&y);
fprintf(fp,"%d\n%f",x,y);
fclose(fp);
fp=fopen("Del.txt","wb");
fwrite(&x,sizeof(x),1,fp);
fwrite(&z,sizeof(z),1,fp);
fwrite(&y,sizeof(y),1,fp);
fclose(fp);
}
/* WRITE A PROGRAM TO MAINTAIN STRUDENT DATA BASE IN A FILE PRINT IT ON
THE MONITOR USING fread() AND fwrite() FUNCTIONS */

#include<stdio.h>

Page 182
typedef struct
{
int rno;
char name[25],branch[5];
}student;
main()
{
int i,n;
student s[20];
FILE *f=fopen("st.txt","wb");
clrscr();
printf("\nEnter how many students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter student %d details:",i);
scanf("%d%s%s",&s[i].rno,s[i].name,s[i].branch);
fwrite(&s[i],sizeof(s[i]),1,f);
}
fclose(f);
f=fopen("st.txt","rb");
printf("\n Database Details Are:\n");
for(i=1;i<=n;i++)
{
fread(&s[i],sizeof(s[i]),1,f);
printf("\n%d\t%s\t%s",s[i].rno,s[i].name,s[i].branch);
}
fclose(f);
}
FILE ACCESSING TECHNIQUES (or) FILE TYPES
Every open file has an associated file position indicator, which describes where read and write
operations take place in the file. The position is always specified in bytes from the beginning of the
file.
When a file is opened in either read (or) write mode, the position indicator is always at
beginning of the file i.e., at position ‘0’. If the file is opened in append mode, the position indicator is
at the end of the file.

File accessing techniques can be classified into two types as:

1. Sequential file processing


2. Random access file processing
1. Sequential File Processing: In sequential file processing, the file pointer moves character
by character without skipping data. i.e., read or write operations performed sequentially. getc(),
putc(), fgets(), fputs() etc., functions support sequential file processing.

2. Random Access File Processing: In random access file processing, the file pointer can
change from one location to another location according to user requirements. Here, operations are
performed in random access manner. Most important functions used in random access file processing
are:

a) fseek()
b) ftell()
Page 183
c) rewind()
a) fseek() function: fseek() function is used to move the position indicator to a desired location
within the file. The general format of the fseek() function is:

Syntax: fseek(FilePointer, OffSet, Position);

Where,
 OffSet is the number of bytes to be moved and it must be long integer. The value
may be positive of negative. If the OffSet value be positive, file pointer moves to
forward direction; otherwise, file pointer moves to backward direction.
 Position specifies the starting position in the file to move. Position can take any one
of the following three values.
VALUE MEANING

0 Beginning of File
1 Current Position
2 End of File

When the operation is successful, fseek() function returns zero; otherwise, it return -1.

Examples:

1. fseek(fp,0L,0) - Go to beginning of the file


2. fseek(fp,0L,1) - Stay at the current position
3. fseek(fp,0L,2) - Go to end of the file
4. fseek(fp,m,0) - Move to m bytes from beginning of the file
5. fseek(fp,m,1) - Go to forward by m bytes from current position
6. fseek(fp,-m,2) - Go to backward by m bytes from the end of file.

b) ftell() function: ftell() function is used to return the current position of the file pointer in the
file. The general format of the ftell() function is:

Syntax: N = ftell(FilePointer);

Where,
N is a long integer variable.

Function returns current position (in bytes) as long integer value. If any error encountered, then the
function returns -1.

c) rewind() function: rewind() function is used to reset the file pointer to beginning of the
file. The general format of the rewind() function is:

Syntax: rewind(FilePointer);

Function reset the file pointer at the beginning of the file.


/* WRITE A PROGRAM TO READ DATA FROM A FILE AND PRINT POSITION BYTE OF
EACH CHARACTER IN THE FILE */

#include<stdio.h>
main()
{
FILE *fp;
long n;
Page 184
char ch;
clrscr();
fp=fopen("win.dat","r");
if(fp==NULL)
{
printf("\nFile Opening Error");
exit();
}
while(1)
{
n=ftell(fp);
if((ch=fgetc(fp))==EOF)
exit();
printf("\n%c position is: %ld Byte",ch,n);
}
fclose(fp);
}
/* WRITE A PROGRAM TO PRINT THE CONTENTS OF A FILE IN REVERSE ORDER */

#include<stdio.h>
main()
{
FILE *fp;
long n,i;
char ch;
clrscr();
fp=fopen("den.txt","r");
if(fp==NULL)
{
printf("\nFile Opening Error");
exit();
}
fseek(fp,-1L,2);
n=ftell(fp);
printf("\nFile Contents in Reverse Order:\n");
for(i=1;i<=n+1;i++)
{
fseek(fp,-i,2);
putchar(fgetc(fp));
}
fclose(fp);
}
ADDITIONAL FUNCTIONS

1. fcloseall():
fcloseall() is a library function used to close all file streams opened explicitly by the
user. The general format of fcloseall() function is:

Syntax : int fcloseall();

Example : fcloseall();

Page 185
Function returns integer value that shows number of closed files if successful; otherwise, it
returns EOF marker.

2. fflush():
fflush() is a library function used to flush the contents of output stream. The general
format of fflush() function is:

Syntax : int fflush(FILE *);

Example : fflush(stdin);

Function returns zeof if successful; otherwise, it returns EOF marker.

Standard C Vs Unix File I/O

C was originally implemented for the UNIX operating system. Early versions of C support a
set of I/O functions that are compatible with UNIX. This set of I/O functions is sometimes referred as
Unix-like I/O System or Unbuffered I/O System.

When C was standardized, the Unix-like functions were not incorporated into the standard to
avoid redundancy.

Page 186

You might also like