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

IP-Notes

The document outlines the syllabus for the Introduction to Programming course for B.Tech students at PBR Visvodaya Institute of Technology & Science for the 2023-24 academic year. It covers fundamental programming concepts, problem-solving techniques, and the C programming language, with a focus on algorithms, control structures, arrays, pointers, and file handling. The course aims to develop students' coding skills, logical thinking, and teamwork through practical coding projects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

IP-Notes

The document outlines the syllabus for the Introduction to Programming course for B.Tech students at PBR Visvodaya Institute of Technology & Science for the 2023-24 academic year. It covers fundamental programming concepts, problem-solving techniques, and the C programming language, with a focus on algorithms, control structures, arrays, pointers, and file handling. The course aims to develop students' coding skills, logical thinking, and teamwork through practical coding projects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

I B.

TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Introduction to Programming
(23A05301A)
(Common to All Branches of Engineering)

I B.TECH, I Semester, 2023-24

PBR VITS (Autonomous) Page 1


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

PBR VISVODAYA INSTITUTE OF TECHNOLOGY & SCIENCE


(Autonomous)
B.TECH – I Semester L T P C
3 0 0 3

(23A05301A) INTRODUCTION TO PROGRAMMING


(Common to All Branches of Engineering)

COURSE OBJECTIVES:

 To introduce students to the fundamentals of computer programming.


 To provide hands-on experience with coding and debugging.
 To foster logical thinking and problem-solving skills using programming.
 To familiarize students with programming concepts such as data types, control
structures, functions, and arrays.
 To encourage collaborative learning and teamwork in coding projects.

COURSE OUTCOMES:
After completion of the course, the student will be able to:
CO1: Understand basics of computers, the concept of algorithm and algorithmic thinking. (K2)
CO2: Analyze a problem and develop an algorithm to solve it. (K4)
CO3: Implement various algorithms using the C programming language. (K3)
CO4: Understand more advanced features of C language. (K2)
CO5: Develop problem-solving skills and the ability to debug and optimize the code. (K3)

UNIT- I: Introduction to Programming and Problem Solving


History of Computers, Basic organization of a computer: ALU, input-output units, memory,
program counter, Introduction to Programming Languages, Basics of a Computer Program-
Algorithms, flowcharts (Using Dia Tool), pseudo code. Introduction to Compilation and
Execution, Primitive Data Types, Variables, and Constants, Basic Input and Output,
Operations, Type Conversion, and Casting.
Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem
solving strategies: Top-down approach, Bottom-up approach, Time and space complexities of
algorithms.

UNIT- II Control Structures


Simple sequential programs Conditional Statements (if, if-else, switch), Loops (for, while,
do-while) Break and Continue.

PBR VITS (Autonomous) Page 2


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

UNIT- III Arrays and Strings


Arrays indexing, memory model, programs with array of integers, two dimensional arrays,
Introduction to Strings.
UNIT- IV Pointers & User Defined Data types
Pointers, dereferencing and address operators, pointer and address arithmetic, array
manipulation using pointers, User-defined data types-Structures and Unions.

UNIT- V Functions & File Handling


Introduction to Functions, Function Declaration and Definition, Function call Return Types
and Arguments, modifying parameters inside functions using pointers, arrays as parameters.
Scope and Lifetime of Variables, Basics of File Handling.

TEXT BOOKS:

1. "The C Programming Language", Brian W. Kernighan and Dennis M. Ritchie,


Prentice-Hall, 1988.
2. Schaum’s Outline of Programming with C, Byron S Gottfried, McGraw-Hill
Education,1996.

REFERENCE BOOKS:

1. Computing fundamentals and C Programming, Balagurusamy, E., McGraw-Hill


Education, 2008.
2. Programming in C, Rema Theraja, Oxford, 2016, 2nd edition.
3. C Programming, A Problem Solving Approach, Forouzan, Gilberg, Prasad,
CENGAGE, 3rd Edition.

ONLINE LEARNING RESOURCES:

1. www.learn-c.org
2. www.github.com

***

PBR VITS (Autonomous) Page 3


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

UNIT – I

Introduction to Programming and Problem Solving


History of Computers, Basic organization of a computer: ALU, input-output units, memory,
program counter, Introduction to Programming Languages, Basics of a Computer Program-
Algorithms, flowcharts (Using Dia Tool), pseudo code. Introduction to Compilation and
Execution, Primitive Data Types, Variables, and Constants, Basic Input and Output,
Operations, Type Conversion, and Casting.
Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem
solving strategies: Top-down approach, Bottom-up approach, Time and space complexities of
algorithms.

***

COMPUTER Computer is an electronic device that takes data as input from input
devices, processes 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 known as information.

HISTORY OF COMPUTERS

 The first mechanical calculating apparatus was the abacus, which was invented in
500 BC.
 In 1823, Charles Babbage was introduced a programmable calculating machine.
 J.W. Mauchly and S.P. Eckert introduced the first general-purpose electronic digital
computer in 1946. It was called the ENIAC (Electronic Numerical Integrator and
Calculator).
 Desktop computers available from 1975 onwards. In 1981, IBM (International
Business Machines) used the 8088 microprocessor in the personal computer.
 32-Bit microprocessor chips arrived from 1986. Intel Pentium systems was designed
in 1993, a highly improved personal computer was available at an affordable price.
 From the year 2000 onwards there has been a tremendous effort to increase the speed
and computing capability of the processor resulting in the development of multi-core
processors.
 The arrival of microprocessors triggered the development of desktop computers, in
the form of personal computers and portable computers like the laptops and tablets.

PBR VITS (Autonomous) Page 4


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

GENERATION OF COMPUTERS

The generation of a computer is determined by the technology it uses. There are five
generation of computers. Those are:

1. First Generation (1946 – 1959)

First generation computers use vacuum tubes as the electric components to perform
operations. The first successful electronic computer was introduced as ENIAC (Electronic
Numeric Integrated And Calculator).

Examples: ENIAC, IBM-701, IBM-650 etc.

2. Second Generation (1959 – 1965)

Second generation computers were based on transistors instead of vacuum tubes. So


that size of the computers is reduced compared to first generation computers.

Examples: IBM 1401, B5000 etc.

3. Third Generation (1965 – 1971)

Third generation computers use integrated circuits instead of transistors. Integrated


circuit is a single component containing number of transistors.

Examples: IBM-360, IBM-370, HP 2100A etc.

4. Fourth Generation (1971 – 1980)

Fourth generation computers use microprocessor chip as an electric component to


perform any arithmetic and logical calculations. Graphics user interface (GUI) environment
was exploited to offer more comfort to users.

Examples: IBM PC, STAR 1000 etc.

5. Fifth Generation (1980 – onwards)

Fifth generation computers use artificial intelligence technology. This generation is


based on ULSI (Ultra Large Scale Integration) technology resulting in the production of
microprocessor chips having ten million electronic components.

Examples: Desktop, Laptop, NoteBook, UltraBook etc.

PBR VITS (Autonomous) Page 5


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

GENERATION YEAR TECHNOLOGY OPERATING SPECIFIC


SYSTEM COMPUTERS
First Generation 1946 – 1959 Vacuum Tubes None ENIAC, IBM-
701, IBM-650 etc.
Second Generation 1959 – 1965 Transistors None IBM 1401, B5000
etc.
Third Generation 1965 – 1971 ICs Yes IBM-360, IBM-
370, HP 2100A
etc.
Fourth Generation 1971 – 1980 LSI and VLSI Yes IBM PC, STAR
1000 etc.
Fifth Generation 1980 – Artificial Yes Desktop, Laptop,
onwards Intelligence, Expert NoteBook,
Systems and UltraBook etc.
Natural Language

ANATOMY / FUNTIONAL PARTS / BLOCK DIAGRAM OF A COMPUTER

A computer system can be divided into two parts-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. It includes all mechanical, electrical and electronic parts attached to
it. The most important hardware components are:
1. Input Devices
2. Output Devices
3. Central Processing Unit
4. Memory Unit

Central Processing Unit

Arithmetic Logic Unit

Input Devices Control Unit Output Devices

Register Unit

ROM RAM

Memory Unit

PBR VITS (Autonomous) Page 6


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

1. Input Devices:

Input devices are electronic equipment which communicating with the computer
system to submit data and instructions. The data and instructions are typed, submitted, or
transmitted to a computer through input devices.

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

2. Output Devices:

Output devices display information after processing the instructions to the computer.
The output information can be of visual or audio type depending on the type of output device
used. The most common output device is monitor or visual display unit.

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

3. Central Processing Unit:

Central processing unit (CPU) is brain of the computer. During processing of


operations, it locates and executes the program instructions. It also fetches data from
memory and input/output devices and sends data back.

Physically, it is an integrated circuit silicon chip, mounted on a small square plastic


slab, surrounded by metal pins. Microprocessor chip is referred to as a CPU.

CPU is formed with the combination of three functional units such as:
 Arithmetic Logic Unit (ALU)
 Control Unit (CU)
 Register Unit (RU)

Arithmetic Logic Unit is the part of the CPU that performs arithmetic operations
such as addition and subtraction, logical operations such as comparison of two values etc.

Register unit is a high-speed storage device used to store data temporarily while
executing the instructions. It consists of different types of registers such as Program counter,
Instruction register used for several purposes. Program counter is a a fundamental
component of a computer's central processing unit (CPU). It is a special register that keeps
track of the memory address of the next instruction to be executed in a program. Instruction
register (IR) is the part of a CPU's control unit that holds the instruction currently being
executed or decoded.

Control unit coordinates the processing by controlling the transfer of data and
instructions between main memory and the registers in the CPU. It also coordinates the
execution of ALU to perform operations on data stored in particular registers.

PBR VITS (Autonomous) Page 7


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

4. Memory Unit:

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 is called contents of the cell. Data is stored in memory as binary
digits called bits.

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
Kilobyte KB 1,024 Bytes
Megabyte MB 1,024 Kilobytes
Gigabyte GB 1,024 Megabytes
Terabyte TB 1,024 Gigabytes
Petabyte PB 1,024 Terabytes
Exabyte EB 1,024 Petabytes
Zettabyte ZB 1,024 Exabytes
Yottabyte YB 1,024 Zettabytes

Memory is divided into two types as:

a) Primary Memory
b) Secondary Memory

a) Primary Memory: Primary memory is the area where data and programs
are stored while the program is being executed along with the data. Primary memory is also
known as main memory.

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 is a


non-volatile memory. i.e., the data stored does not disappear even though the system is
switched off.

RAM stores programs, 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. Therefore, 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.

PBR VITS (Autonomous) Page 8


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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


cost and have large storage capacity. Secondary storage devices are also known as auxiliary
devices. Information stored in secondary storage devices is 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.

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. It also controls execution of all kinds of programs. Operating system is also
known as System Software.

Examples: DOS, Windows, Mac, UNIX etc.

USER 1 USER 2 USER N

OPERATING SYSTEM

HARDWARE COMPONENTS

PBR VITS (Autonomous) Page 9


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Main responsibilities/functionalities of the operating system are:

 Communicating with the computer hardware and the 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
 Controlling peripheral devices such disk drives, printers etc.,
 Coordination between other software components’ and the user.

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.

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

Example: Ms-office, Oracle, DB2, SQL etc.

COMPUTER LANGUAGES / PROGRAMMING 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 two types as:

1. Low-level languages
2. High-level languages

1. Low-level Languages

Machine language and Assembly language are low-level languages. Low-level


languages always tried to improve machine efficiency while designing the programs.

a) Machine language:
Machine language is formed with the combination of machine codes, which are
binary numbers as 0’s and 1’s. Machine language is also known as binary language. Machine
language is the language of the computer. Computer can understood only machine language.
Machine language is considered to be the first generation language (1GL).

Example: 1001 0001 0010 1100


0010 1111 0101 0011

PBR VITS (Autonomous) Page 10


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Advantages:

 It makes fast and efficient use of the computer system.


 Language directly understood by the computer.
 Translators are not required to translate the code.

Disadvantages:

 It is a machine dependent language.


 The way of designing is very complex and difficult to use.
 It is hard to locate and correct errors in the program.
 Difficult to debug and modify programs.
 Data security problems.

b) Assembly language:

Assembly language is formed with the combination of simple English words known
as mnemonic codes like ADD, SUB, MUL etc., Assembly language programs are formed
with the co-ordination of Registers concept. Assembly language is considered to be the
second-generation language (2GL).

Example: DATA SEGMENT


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

Advantages:

 Easy to understand compare to machine language.


 It is easy to locate errors.
 It is easily modified.

Disadvantages:

 It is a machine dependent language.


 It must necessary to learn registers concept.
 The programmer should know all about the logical structure of the computer.
 Programming is difficult and time consuming.
 Data security problems.

PBR VITS (Autonomous) Page 11


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

2. High-level Languages

High-level languages are formed with the combination of simple English sentences.
They always tried to improve program efficiency while designing the programs. i.e., they
allow the user to develop the program in simple context rather than the hardware technology.
Hence, high-level languages are easier to design programs compared to machine language
and assembly language. High-level languages are also called third generation languages
(3GL).

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

Advantages:

 Readability, Portability
 Easy debugging
 Ease in the development of software

High-level languages are further classified into different types such as:

a) Procedural languages
b) Structured programming languages
c) Object-oriented languages

a) Procedural languages:

 Program is divided into number of procedures and data can be moved from
one place to another place.

Examples: FORTRAN, BASIC, COBOL etc.

b) Structured programming languages:

 Program is divided into number of functions and data can be moved from
one function to another function.
 User-defined functions are introduced.

Examples: PASCAL, C etc.

c) Object-oriented languages:

 Program is divided into number of objects.


 Objects can communicate with each other through functions.
 Data can be accessed only by the specified object.
 Data security constraints are added.

Examples: C++, JAVA etc.

PBR VITS (Autonomous) Page 12


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* C PROGRAM TO PRINT A MESSAGE */

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

main()
{
clrscr();
printf(“ AUTONOMOUS ”);
}

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 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
process.

(Source Program) (Object Program)

Different types of translators are:

 Assembler
 Compiler
 Interpreter

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


machine codes and vice versa.

(Source Program) (Object Program)

PBR VITS (Autonomous) Page 13


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Compiler is a translator used to convert the high-level language programs into


machine codes and vice-versa.

Data

Interpreter is also used as a translator for high- level language programs. It accepts
source program line by line and translates it into machine language, which is immediately
executed.
Interpreter loaded
Source program Result
computer

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 scans the entire program before translating it into machine code
whereas interpreter translates and executes the program line by line.
 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.

ALGORITHM

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


general, algorithms are designed by using pseudo code. Pseudo code is a language
independent code. Apart of this, algorithms may be represented in different ways such as:

 Step-form Format
 Pseudo-code Format
 Flowchart Format
 Nassi–Shneiderman diagram Format

PBR VITS (Autonomous) Page 14


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

In step-form representation, the procedure of solving a problem statement is stated


with written statements. It uses just normal language to define each procedure. Every
statement that defines an action is logically related to the preceding statement.

The pseudo-code is a written form representation of the algorithm. It uses a restricted


vocabulary to define its action of solving the problem statement.

Flowchart and Nassi-Shneiderman diagram is a graphically oriented representation


of the algorithm. It uses specific symbols to represent each statement in a systematic way.

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:

1. Each algorithm will be logically enclosed by two statements START and STOP.
2. To accept data from user, the INPUT or READ statements are to be used.
3. To display any user message or the content in a variable, PRINT/WRITE/DISPLAY
statement will be used. The message will be enclosed within quotes.
4. ← symbol used to assign a value to the variable.
5. +, -, * and / symbols are used to indicate arithmetic operations such as addition,
subtraction, multiplication and division operations.
6. <, >, ≤, ≥, = and ≠ symbols are used to compare the given operand values.
7. AND, OR, NOT words used for conjunction, disjunction and negation operations.

PBR VITS (Autonomous) Page 15


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Example:

Algorithm for addition of given two values using step-form representation

Step 1: START
Step 2: Read two input values as X and Y
Step 3: Add X and Y values and store the result value in Z
Step 4: Print addition result value as Z
Step 5: STOP

Algorithm for addition of given two values using pseudo-code representation

Step 1: START
Step 2: INPUT X , Y
Step 3: Z←X+Y
Step 4: PRINT Z
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: INPUT X , Y
Step 3: Sum ← X + Y
Step 4: PRINT Sum
Step 5: STOP

b) Selection algorithm:

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.

PBR VITS (Autonomous) Page 16


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Example: Algorithm for maximum of given two numbers

Step 1: START
Step 2: INPUT X, Y values
Step 3: IF X > Y THEN
Max ← X
ELSE
Max ← Y
ENDIF
Step 4: PRINT 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, DO-WHILE and FOR statements.

Example: Algorithm for reverse of a given number

Step 1: START
Step 2: INPUT N value
Step 3: Rev ← 0
Step 4: Repeat WHILE N > 0
K ← N MOD 10
Rev ← Rev * 10 + K
N ← N / 10
EndRepeat
Step 5: PRINT Rev
Step 6: STOP

FLOWCHARTS

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


flowchart.

A flowchart comprises a set of standard shaped boxes that are interconnected by flow
lines. Flow lines have arrows to indicate the direction of the flow of control between the
boxes. The activity to be performed is written within the boxes.

Flowcharts are usually drawn using standard symbols. Flowcharts play a vital role in
the programming of a problem and are quite helpful in understanding the logic of
complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the
program in high-level language.

PBR VITS (Autonomous) Page 17


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Some of the important symbols used to draw flowcharts are:

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


statements is “Oval”.

Symbol :

Example :
START STOP

INPUT / OUTPUT STATEMENTS: The symbol used to represent input statements


and output statements is “Parallelogram”.

Symbol :

Example : INPUT X,Y PRINT 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

WRITE ‘Hello’

STOP

PBR VITS (Autonomous) Page 18


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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: 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/Rhombus”.

Symbol :

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

Example :

Is x>0 F

PBR VITS (Autonomous) Page 19


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Additional symbols that used for designing complex flowcharts are:

SYMBOL DESCRIPTION

DATA BASE

SUB ROUTINE

MULTIDOCUMENTS

IDEL OR WAITING STATE

EXTRACTS INDIVIDUAL SETS OF DATA ITEMS

MERGE

MERGE AND EXTRACT ACTIONS

Example: Draw a flowchart for addition of given two values

START INPUT X, Y

SUM ← X + Y

PRINT SUM STOP

Uses of Flowcharts:

 Understanding and readability purpose


 It provides a better communication between the users
 It shows a systematic way to solve the problem statements
 It gives a clear and simple way of solution to solve difficult problems

PBR VITS (Autonomous) Page 20


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 program. 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.
The compilation process consists of two steps: the analysis of the source program and the
synthesis of the object program.

The analysis phase uses the precise description of the source programming language.
A source program is described using lexical rules, syntax rules, and semantic rules.

Lexical rules specify the valid syntactic elements or words of the language. Syntax
rules specify the way in which valid syntactic elements are combined to form the statements
of the language. Semantic rules assign meaning to valid statements of the language.

PBR VITS (Autonomous) Page 21


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

First, the lexical analyzer takes successive line of a program and breaks them into
individual lexical items, namely identifier, operators and attaches a tag to each of these units.
It constructs a symbol table for each identifier and finds the internal representation of each
constant. In second stage, syntax analysis is done using techniques based on formal
grammar of the programming languages. In semantic analysis an intermediate code of the
final machine language is produced.

In final stage, code generator produces object code of the source program which is a
machine language program. The output machine language code is known as an 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

Program
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 a program is compiled and linked, each instruction and each item of data is
assigned an address. At execution time, the CPU finds instructions and data from these
addresses. For this, CPU uses Instruction register (IR) that holds the current instruction
being executed and Program Counter (PC) register that holds the address of the next
instruction to be executed in a program

PBR VITS (Autonomous) Page 22


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

In the beginning, CPU fetches and then executes the instruction found at this address.
Then PC increments the address to the next instruction. Based on the instructions, 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.

Finally, the entire process shown as:

Source
Program
Input Data

Translator Linker Loader

Object Modules Binary Program Results

PROBLEM-SOLVING STRATEGIES

In problem solving aspect, there are number of steps that can raise the level of
performance to obtain the solution of the given problem statement. In fact, there is no
universal method. Different strategies appear to work for different types of users. However,
some of the most common steps are:

a) Problem definition phase


 The preliminary investigation may be thought of as the problem definition
phase.
 This phase works out “what must be done rather than how to do it“.
 In this phase, we must extract a set of precisely defined tasks.

b) Getting started on a problem

 There are many ways to solve most of the problems and many solutions.
 Identify the number of possible solutions for the given problem statement.

c) Use of specific examples

 A useful strategy is to pick a specific example of the general problem


statement and try to work out the mechanism that will allow us to solve the
current problem statement.
 Different possible test cases can given us a degree of confidence to solve the
problem statement.

PBR VITS (Autonomous) Page 23


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

d) Similarities among problems

 The way of developing problem solving is the ability to view the problem
from a variety of ways.
 Identify the similarities by comparing with other related problem statements.

e) Working backwards from the solution

 In some cases assume that, we already have the solution to the problem and try
to work backwards to the starting conditions.

f) General problem-solving strategies

 There are number of computational strategies those are repeatedly used in


various applications. Some of the important methods are:

Divide-and-Conquer strategy,
Dynamic programming,
Greedy strategy,
Backtracking,
Branch-and-Bound etc.

The primary goal in computer problem solving is an algorithm which is capable of


being implemented as a correct and efficient computer program. Program approaches are
classified into two types as:

1. Top-Down approach
2. Bottom-up approach

1. Top-down Approach

Top-down design is a process of breaking the overall problem into sub problems and
then subdivides each sub-problem until the lowest level of details has been reached.

In this procedure, the actual problem statement is at the top level. Divide the problem
into appropriate sub-problems based on the specified constraints. While dividing into sub-
problems, assure that each sub problem definition must be independent of each other. Divide
to that extent until the sub problem is not possible for further division. Finally, those sub
problems individually solved and combine to produce the original solution.

PBR VITS (Autonomous) Page 24


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Problem Statement

Input Conditions Body of Algorithm Output Requirements

Sub-Task 1 Sub-Task 2 Sub-Task 3


Algorithm Algorithm

Sub-Task 4 Sub-Task 5
Algorithm Algorithm

2. Bottom-Up Approach

Already existing facilities are taken into consideration as a model for a new design.
In bottom-up strategy, use existing computer as a model for the new program. When we try
to utilize the existing design in a proper way, it gives a better solution for the current problem
statement.

Module 1 - - - - - - -- Module N

Problem Statement

ANALYSIS & EFFICIENCY OF ALGORITHMS

Any problem statement can be analyzed at two stages as:

 Apriori analysis
 Posterior analysis.

Apriori analysis means, the analysis is done for the problem before it run on the
machine. Posterior analysis is done after running the problem in a specific programming
language.

PBR VITS (Autonomous) Page 25


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Algorithm efficiency describes the properties of an algorithm, which relates to the


amount of resources used. An algorithm must be analyzed to determine its resource usage.

Analysis of algorithms (or) performance analysis refers to the task of determining


how much computing time (time complexity) and storage space (space complexity) of an
algorithm requires.

The time complexity of an algorithm is the amount of computer time it needs to run
to its completion. The space complexity of an algorithm is the amount of memory space it
needs to run to its completion.

Time and space complexities are calculated based on the size of the input data. Based
on the size of the input data, analysis can be divided into three cases as:

 Best case analysis


 Worst case analysis
 Average case analysis

Best case analysis: In best case analysis, problem statement takes minimum
number of computations for the given input parameters.

Worst case analysis: In worst case analysis, problem statement takes


maximum number of computations for the given input parameters.

Average case analysis: In average case analysis, problem statement takes


average number of computations for the given input parameters.

Based on the size of input requirements, complexities can be varied. Hence, exact
representation of time and space complexities is not possible. But they can be shown in
some approximate representation using mathematical notations known as asymptotic
notations. Those are:

a) Big “Oh” notation


b) Omega notation
c) Theta notation
d) Little “Oh” notation
e) Little omega notation

PBR VITS (Autonomous) Page 26


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Big ‘Oh’ notation (O):

The function f(n) = O(g(n)) iff there exist two positive constants c and n0 such that
f(n) ≤ c * g(n) for all n, n ≥ n0.

The graphical representation between n values on X-axis and f(n) values on Y-axis is as
follows:
Y

c*g(n)
Here, the functional value f(n) is always below the
estimated functional value c*g(n). Thus, the function n0
g(n) acts as upper bound value for the function f(n).
Hence, Big ‘Oh’ notation is treated as “Upper bounded f(n)
Function”.
f(n)

n X

Example:

Consider f(n) = 3n+2

Assume that 3n+2 ≤ 4n

Let n=1 3(1) + 2 ≤ 4(1) → 5≤4 FALSE


n=2 3(2) + 2 ≤ 4(2) → 8≤8 TRUE
n=3 3(3) + 2 ≤ 4(3) → 11 ≤ 12 TRUE
.
.

From this,
c=4 g(n) = n and n0 = 2

Hence, the function 3n+2 = O(n) iff there exist two positive constants 4 and 2 such
that 3n+2 ≤ 4n for all n, n ≥ 2.

In these complexities,
O(1) means constant
O(n) means linear
O(log n) means logarithmic
O(n2) means quadratic
3
O(n ) means cubic
O(2n) means exponential.

O(1) < O(log n) < O(n) < O(n logn) < O(n2) < O(n3) < - - - - - - - < O(2n) .

PBR VITS (Autonomous) Page 27


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Omega notation (Ω):

The function f(n) = Ω(g(n)) iff there exist two positive constants c and n 0 such that
f(n) ≥ c * g(n) for all n, n ≥ n0.

The graphical representation between n values on X-axis and f(n) values on Y-axis is as
follows:
Y f(n)

Here, the functional value f(n) is always above the


estimated functional value c*g(n). Thus, the function c*g(n)
g(n) acts as lower bound value for the function f(n).
Hence, Omega notation is treated as “Lower bounded f(n) n0
Function”.

n X
Example:
Consider f(n) = 3n+2
Assume that 3n+2 ≥ 3n

Let n=1 3(1) + 2 ≥ 3(1) → 5≥3 TRUE


n=2 3(2) + 2 ≥ 3(2) → 8≥6 TRUE
.
.
From this,
c=3 g(n) = n and n0 = 1
Hence, the function 3n+2 = Ω (n) iff there exist two positive constants 3 and 1 such
that 3n+2 ≥ 3n for all n, n ≥ 1.

Theta notation (Ө):

The function f(n) = Ө(g(n)) iff there exist three positive constants c1, c2 and n0 such
that c1 * g(n) ≤ f(n) ≤ c2 * g(n) for all n, n ≥ n0.

The graphical representation between n values on X-axis and f(n) values on Y-axis is as
follows:
Y
c2 * g(n)

Here, the functional value f(n) is always lies in f(n)


between the estimated functional values c1*g(n).
and c2*g(n). Thus, the function g(n) acts as lower f(n) c1 * g(n)
bound and upper bound value for the function f(n). n0
Hence, Theta notation is treated as “Bounded
Function”. n X

PBR VITS (Autonomous) n XPage 28


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Example:

Consider f(n) = 3n+2

Assume that 3n ≤ 3n+2 ≤ 4n

Let n=1 3(1) ≤ 3(1) + 2 ≤ 4(1) → 3≤5≤4 FALSE


n=2 3(2) ≤ 3(2) + 2 ≤ 4(2) → 6≤8≤8 TRUE
n=3 3(3) ≤ 3(3) + 2 ≤ 4(3) → 9 ≤ 11 ≤ 12 TRUE
.
.

From this,
c1 = 3 c2 = 4 g(n) = n and n0 = 2

Hence, the function 3n+2 = Ө(g(n)) iff there exist three positive constants 3,4 and 2
and n0 such that 3n ≤ 3n+2 ≤ 4n for all n, n ≥ 2.

Little ‘Oh’ notation (o):

The function f(n) = o(g(n)) iff there exist two positive constants c and n0 such that
f(n) < c * g(n) for all n, n ≥ n0.

(OR)

𝑓(𝑛)
The function f(n) = o(g(n)) iff Lim = 0
𝑔(𝑛)
n→∞

Little Omega notation (ω):

The function f(n) = ω(g(n)) iff there exist two positive constants c and n 0 such that
f(n) > c * g(n) for all n, n ≥ n0.

OR

𝑔(𝑛)
The function f(n) = ω(g(n)) iff Lim = 0
𝑓(𝑛)
n→∞

PBR VITS (Autonomous) Page 29


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 Waterfall 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


in terms 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

START

Step 1: START

Step 2: READ x, y READ x, y

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

Step 5: STOP
WRITE sum

STOP

PBR VITS (Autonomous) Page 30


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

3. Program Design: The flowchart and algorithm steps developed in the previous
phase are 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(“\n Enter Two Numbers =”);
scanf(“%d%d”,&X,&Y);
SUM = X + Y ;
printf(“\n Addition Result = %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 detected during neither compilation nor
execution nor cause any stoppage to the program execution. They only produce unwanted
outputs.
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.

PBR VITS (Autonomous) Page 31


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

6. Testing & Validation: In this phase, the program is tested by submitting proper
input values. 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 : Addition Result = 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.

***

PBR VITS (Autonomous) Page 32


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

History of ‘C’ Language

ALGOL Algorithmic Language

BCPL Basic Combined Programming


Language

B B Language

C C Language

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


1960’s.
 In 1967, Martin Richards developed a language called Basic Combined Programming
Language (BCPL).
 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.


C is a structured programming language because to solve a large problem, C
programming language divides the problem into smaller modules called functions or
procedures each of which handles a particular responsibility.

2. C is a middle-level language.
Depending on the efficiency and performance, programming languages are
classified into two types as:

PBR VITS (Autonomous) Page 33


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

 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.


In C language, pointers concept allows the user to allocate memory for the
variables at run time based on their requirements.

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

6. C is a core language.
In computing, C is a general purpose, block structured programming language.
A number of common and popular computer programming languages are based on C.
Having learnt C, it will be much easier to learn other languages such as C++, Java and
Perl.

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

CONSTANTS AND VARIABLES

A constant is a quantity that does not 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.

PBR VITS (Autonomous) Page 34


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

KEYWORDS

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

char int float double short long


signed unsigned if else switch case
break continue return while do for
far near goto void struct union
default typedef auto const static volatile
register enum

IDENTIFIER

The words which are defined by the user are called identifiers. Identifiers are treated
as user-defined words. An identifier is a name given to the variable, constant, array, structure
etc. Identifier names are assigned by the users according to their requirements based on the
problem statements.

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. In C language, data
types are classified into different types as:

Data Types

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


Data Types Data Types

int Array Structure


char Function Union
float Pointer Enumeration
double

PBR VITS (Autonomous) Page 35


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 SIZE RANGE


(BYTES) (BITS)

char 1 8 -128 to 127


unsigned char 1 8 0 to 255
signed char 1 8 -128 to 127

int 2 16 -32768 to 32767


unsigned int 2 16 0 to 65535
signed int 2 16 -32768 to 32767
short int 2 16 -32768 to 32767
unsigned short int 2 16 0 to 65535
signed short int 2 16 -32768 to 32767
long int 4 32 -2147483648 to 2147483647
unsigned long int 4 32 0 to 4294967295
signed long int 4 32 -2147483648 to 2147483647

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

double 8 64 1.7E-308 to 1.7E+308


long double 10 80 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.

PBR VITS (Autonomous) Page 36


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 variable. The
general format of declaring a variable is:

Syntax: DataType VariableName / Identifier;

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 / Identifiers:

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 cannot 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.

PBR VITS (Autonomous) Page 37


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

C-TOKENS

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

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”. All keywords must in lower
case characters. 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

2. Identifiers: The words which are defined by the user are known as identifiers.
These words are treated as user-defined words. i.e., Names given to variables, constants,
arrays, structures etc., are often knows as identifiers.

Example: X, y, Sum_Value etc.

3. Constants: A constant is a quantity that does not 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

PBR VITS (Autonomous) Page 38


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

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

Exponential Format: In exponential format, the whole number is followed by


e (exponent) and mantissa.

Example: 2179e-2

Character Constants: Character constant contains a single character enclosed within a pair of
single quotation marks. The character may be alphabet, digit and special symbol.

Example: ‘A’ ‘9’ ‘#’

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. The characters may be


any combination of letters, digits, special symbols and blank spaces. In C language, a
character array itself treated as a string.

Example: HELLO

5. Operators: Operator is a symbol that tells the compiler to perform some action. C
language supports different operators: Arithmetic operators, Relational operators, Logical
operators, Increment & Decrement operators, Conditional operators etc.

Example: + - & || ~ etc.

6. Special Symbols: C language supports various special symbols that perform different
types of actions. Those symbols are used in various applications for different purposes based
on the type of problem statements.

Example: # ; : etc.

PBR VITS (Autonomous) Page 39


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 according to user
requirements. 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

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”);
clrscr( );
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 1: #include<HeaderFileName>
Syntax 2: #include”HeaderFileName”

PBR VITS (Autonomous) Page 40


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Example: #include<stdio.h>
#include “stdio.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. The general
format of clrscr() function is:

Syntax: clrscr();

Example: clrscr();

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

BASIC INPUT / OUTPUT STATEMENTS

i) Reading Data from the Keyboard (Input Statement):

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:

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 %u - unsigned int


%c - char %ld - long int
%lf - double %o - octal
%f - float %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);

PBR VITS (Autonomous) Page 41


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

ii) Display Values on Monitor (Output Statement):

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.

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”);

PBR VITS (Autonomous) Page 42


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

Example:

/* C PROGRAM TO PRINT A MESSAGE */

#include<stdio.h> /* Inclusion of Standard I/O Header File */


#include<conio.h> /* Inclusion of Console I/O Header File */
main() /* Beginning of Main function */
{ /* Beginning of Function body */
clrscr(); /* Library function to clear the screen */
printf(“ KAVALI”); /* Output statement to print the message */
} /* Ending of Function body */

***

PBR VITS (Autonomous) Page 43


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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
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);
}

PBR VITS (Autonomous) Page 44


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

 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("\n Enter Two Numbers:");
scanf("%d%d",&x,&y);
sum = x + y;
sub = x - y;
mul = x * y;
div = x / y;
rem = x % y;
printf("\n Addition Value = %d",sum);
printf("\n Subtraction Value = %d",sub);
printf("\n Multiplication Value = %d",mul);
printf("\n Division Value = %d",div);
printf("\n Remainder Value = %d",rem);
}

PBR VITS (Autonomous) Page 45


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

/* EXAMPLE PROGRAM FOR RELATIONAL OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\n Result 1 = %d",14>78);
printf("\n Result 2 = %d",14<78);
printf("\n Result 3 = %d",25<=50);
printf("\n Result 4 = %d",25>=50);
printf("\n Result 5 = %d",100==100);
printf("\n Result 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

PBR VITS (Autonomous) Page 46


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 && Exp2 Exp1 || Exp2 ! Exp1

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

/* EXAMPLE PROGRAM FOR LOGICAL OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\n Result 1 = %d",(14>78)&&(24<78));
printf("\n Result 2 = %d",(14>78)||(24<78));
printf("\n Result 3 = %d",!45);
}

5. Increment & Decrement Operators

++ and -- operators are called increment and decrement operators. These operators
are unary operators 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

PBR VITS (Autonomous) Page 47


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

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 INCREMENT & DECREMENT OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x = 10;
y = ++x;
printf("\n Pre-Increment X Value = %d",x);
printf("\n Pre-Increment Y Value = %d",y);
y = x++;
printf("\n Post-Increment X Value = %d",x);
printf("\n Post-Increment Y Value = %d",y);
y = - -x;
printf("\n Pre-Decrement X Value = %d",x);
printf("\n Pre-Decrement Y Value = %d",y);
y = x - -;
printf("\n Post-Decrement X Value = %d",x);
printf("\n Post-Decrement Y Value = %d",y);
}

PBR VITS (Autonomous) Page 48


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

6. Conditional Operator

C language supports a ternary operator pair ? : known 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 or 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("\n Enter Two Numbers =");
scanf("%d%d",&A,&B);
Max = (A>B) ? A : B ;
printf("\n Maximum 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

PBR VITS (Autonomous) Page 49


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

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.

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

PBR VITS (Autonomous) Page 50


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

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 right shift operator is:

Syntax: VariableName >> NoOfBitPositions;

PBR VITS (Autonomous) Page 51


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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("\n Left Shift Result = %d",x<<2);
x = 24;
printf("\n Right Shift Result = %d",x>>2);
}

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;

PBR VITS (Autonomous) Page 52


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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("\n SIZE OF K = %d Bytes",sizeof(k));
printf("\n SIZE OF P = %d Bytes",sizeof(p));
printf("\n SIZE OF Z = %d Bytes",sizeof(z));
printf("\n SIZE OF T = %d Bytes",sizeof(t));
printf("\n SIZE OF INT = %d Bytes",sizeof(int));
printf("\n SIZE OF CHAR = %d Bytes",sizeof(char));
printf("\n SIZE OF FLOAT = %d Bytes",sizeof(float));
printf("\n SIZE OF DOUBLE = %d Bytes",sizeof(double));
printf("\n SIZE OF INT VALUE = %d Bytes",sizeof(100));
printf("\n SIZE OF CHAR VALUE = %d Bytes",sizeof('A'));
printf("\n SIZE OF FLOAT VALUE = %d Bytes",sizeof(23.45f));
printf("\n SIZE OF DOUBLE VALUE = %d Bytes",sizeof(456.678));
}

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.

PBR VITS (Autonomous) Page 53


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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("\n Enter X Value =");
scanf("%d",&x);
x + = 6;
printf("\n X 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 requires 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: ? :

PBR VITS (Autonomous) Page 54


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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: Y = 4 + 10 * 2;
Y
= + * 24
Y = 4 + 20
= +
Y = 24

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
*/% L→R
24 / 4 % 4
/% L→R
6%4
%
2

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

PBR VITS (Autonomous) Page 55


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Operator precedence & Associativity 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
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

/* EXAMPLE PROGRAM FOR OPERATOR PRECEDENCE & ASSOCIATIVITY */

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

main()
{
int y;
clrscr();
y = 2 + 10 * 2;
printf("\n Result 1 = %d",y);
y = 3 * 8 / 4 % 4 * 5;
printf("\n Result 2 = %d",y);
}

PBR VITS (Autonomous) Page 56


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

TYPE CONVERSION (or) CASTING

The process of converting data items 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;


= (2.000000 * 3.500000) + 4;
= 7.000000 + 4;
= 7.000000 + 4.000000;
= 11.000000

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.

PBR VITS (Autonomous) Page 57


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

In explicit type casting, there may be a loss of data while converting from higher data
type to 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 = 14.000000 / 3.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("\n Enter Three Values =");
scanf("%d%d%d",&x,&y,&z);
total = x + y + z;
Avg = (float) total / 3;
printf("\n Average Result = %f",Avg);
}

***

PBR VITS (Autonomous) Page 58


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

UNIT- II

Control Structures
Simple sequential programs Conditional Statements (if, if-else, switch), Loops (for, while,
do-while) Break and Continue.
***

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(“\n Result = %d”,z);
}

3. Control Statements

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


order from top to bottom. However, 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 one 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

PBR VITS (Autonomous) Page 59


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 statements: i) if statement


ii) if-else statement
iii) Nested if-else statement
Multi-way selection statements: iv) else-if ladder statement
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;

PBR VITS (Autonomous) Page 60


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

if(x = = 0)
y = 0;
if(x<0)
y = -1;
printf("\nY value = %d",y);
}

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

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);
}

PBR VITS (Autonomous) Page 61


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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
{
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("\n Enter Three Numbers =");
scanf("%d%d%d",&x,&y,&z);

PBR VITS (Autonomous) Page 62


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

if(x > = y)
{
if(x > = z)
printf("\n Maximum Number = %d",x);
else
printf("\n Maximum Number = %d",z);
}
else
{
if(y > = z)
printf("\n Maximum Number = %d",y);
else
printf("\n Maximum Number = %d",z);
}
}

iv) Else-If Ladder Statement: Else-If ladder statement is a multi-way selection


control 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.

PBR VITS (Autonomous) Page 63


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z;
clrscr( );
printf("\n Enter Three Numbers =");
scanf("%d%d%d",&x,&y,&z);
if(x > = y && x > = z)
printf("\n Maximum Number = %d",x);
else if(y > = z)
printf("\n Maximum Number = %d",y);
else
printf("\n Maximum Number = %d",z);
}

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

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.

PBR VITS (Autonomous) Page 64


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

 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("\n Enter Your Choice = ");
scanf("%d",&ch);

switch(ch)
{
case 1:printf("\n RED COLOUR SELECTED");
break;
case 2:printf("\n GREEN COLOUR SELECTED");
break;
case 3:printf("\n BLUE COLOUR SELECTED");
break;
default: printf("\n INVALID 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
}

PBR VITS (Autonomous) Page 65


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* 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("\n VOWEL");
break;
default: printf("\n CONSONANT");
}
}

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.
PBR VITS (Autonomous) Page 66
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM FOR CONDITIONAL EXPRESSION */

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

main()
{
int A,B,Max;
clrscr();
printf("\n Enter Two Numbers = ");
scanf("%d%d",&A,&B);
Max = (A>B) ? A : B ;
printf("\n Maximum 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
repeated until the test condition reaches to FALSE. The pre-test loop is also known as an
entry-controlled loop.

Condi FALSE
tion

TRUE
Statements

PBR VITS (Autonomous) Page 67


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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. The post-test loop is also known as an exit-controlled loop.

Statements

FALSE
Condi
tion

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 such as:

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

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

The general format of a while statement is:

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

PBR VITS (Autonomous) Page 68


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

/* PROGRAM TO PRINT THE FIRST ‘N’ NATURAL NUMBERS */

#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n Natural 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);

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.

PBR VITS (Autonomous) Page 69


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 */

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

main()
{
int i=1,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n NATURAL NUMBERS ARE = ");
do
{
printf(" %d",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
- - -
}

Here,
 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.

PBR VITS (Autonomous) Page 70


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n NATURAL NUMBERS ARE = ");
for(i = 1 ; i < = n ; i++)
printf(" %d",i);
}

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.

Example: 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.

Example: for(i = 1, j = 5 ; i < = 5 && j >= 1 ; i++ , j--)


{
printf(“\n %d \t %d”,i,j);
}

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.

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

PBR VITS (Autonomous) Page 71


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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
{
----
----
}
----
----
}

/* PROGRAM TO GENERATE FORMAT 1


1 2
1 2 3
1 2 3 4 */

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

main()
{
int i,j,N;
clrscr();
printf("\n Enter how many Rows =");
scanf("%d",&N);
printf("\n RESULT FORMAT = \n");
for(i = 1; i <= N; i++)
{
printf("\n");
for(j = 1; j < = i; j++)
printf(" %d",j);
}
}

PBR VITS (Autonomous) Page 72


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 */

#include<stdio.h>
#include<conio.h>
main()
{
int i,x,sum = 0;
clrscr();
for(i = 1 ; i < = 5 ; i++)
{
printf("\n Enter Number %d = ",i);
scanf("%d",&x);
if(x < 0)
break;
sum = sum + x;
}
printf("\n Total = %d",sum);
}

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.

PBR VITS (Autonomous) Page 73


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* Example program for continue statement */

#include<stdio.h>
#include<conio.h>
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 within 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 : _ _ _ ___
___ ---

PBR VITS (Autonomous) Page 74


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

#include<stdio.h> #include<stdio.h>
main() main()
{ {
int i,x,sum=0; int i,x,sum;
clrscr(); clrscr();
for(i=1;i<=5;i++) Target:
{ 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 Target; scanf(“%d”,&x);
sum=sum+x; if(x<0)
} goto Target;
Target: 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.

END

PBR VITS (Autonomous) Page 75


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

UNIT- III
Arrays and Strings
Arrays indexing, memory model, programs with array of integers, two-dimensional arrays,
Introduction to Strings.
***

ARRAYS

An array is a collection of homogeneous/similar data type elements those 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 within square brackets. The number
of 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

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 those are stored in m
successive memory locations”.

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 K[5];

For this, the memory allocation will be:

Index Values 0 1 2 3 4
K

1000 1002 1004 1006 1008 Addresses


Array Name

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

PBR VITS (Autonomous) Page 76


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 ‘K’.
3. An individual element of the array is accessed with index as:
0th index element as K[0],
1st index element as K[1] and soon.

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

#include<stdio.h>
#include<conio.h>
main()
{
int n,i,K[10];
clrscr();
printf("\n Enter how many elements = ");
scanf("%d",&n);
for(i = 0 ; i < n ; i++)
{
printf("\n Enter Element %d = ",i+1);
scanf("%d",&K[i]);
}
printf("\n Array Elements Are:");
for(i = 0 ; i < n ; i++)
printf(" %d",K[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 */

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 */

PBR VITS (Autonomous) Page 77


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM FOR INITIALIZING A SINGLE DIMENSTIONAL ARRAY */

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

2. Double (or) Two-dimensional arrays

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 those are stored in m x n successive memory locations”.

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.
 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. Therefore, that double dimensional arrays are
useful for matrix representation of given elements.

PBR VITS (Autonomous) Page 78


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

#include<stdio.h>
#include<conio.h>
main()
{
int R,C,i,j,K[10][10];
clrscr();
printf("\n Enter how many rows = ");
scanf("%d",&R);
printf("\n Enter how many columns = ");
scanf("%d",&C);
printf("\n Enter Array Elements =");
for(i = 0 ; i < R ; i++)
{
for(j = 0 ; j < C ; j++)
scanf("%d",&K[i][j]);
}
printf("\n Matrix Elements Are = ");
for(i = 0 ; i < R ; i++)
{
printf("\n");
for(j = 0 ; j < C ; j++)
printf(" %d",K[i][j]);
}
}

Initialization of Double dimensional arrays:

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};

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} };

PBR VITS (Autonomous) Page 79


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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};

/* EXAMPLE PROGRAM FOR INITIALIZING DOUBLE DIMENSIONAL ARRAY */

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

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

3. Multidimensional arrays

Multidimensional array uses three or more dimensions. 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 those are stored in m1xm2x-
- - - x mn successive memory locations”.

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. For multidimensional arrays,


compiler allocates memory as in terms of collection of tables.

PBR VITS (Autonomous) Page 80


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* PROGRAM TO READ A MULTDIMENSIONAL ARRAY AND PRINT IT */

main()
{
int T,R,C,p,i,j,K[10][10][10];
clrscr();
printf("\n Enter how many Tables = ");
scanf("%d",&T);
printf("\n Enter how many rows = ");
scanf("%d",&R);
printf("\n Enter how many columns = ");
scanf("%d",&C);
printf("\n Enter Array Elements = ");
for(i = 0 ; i < T ; i++)
{
for(j = 0 ; j < R ; j++)
{
for(p = 0 ; p < C ; p++)
scanf("%d",&K[i][j][p]);
}
}
printf("\n Array Elements Are = ");
for(i = 0 ; i < T ; i++)
{
printf("\n \n");
for(j = 0 ; j < R ; j++)
{
printf("\n");
for(p = 0 ; p < C ; p++)
printf(" %d",K[i][j][p]);
}
}
}

Initialization of multidimensional arrays:

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

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

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

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}} };

PBR VITS (Autonomous) Page 81


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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};

/* EXAMPLE PROGRAM FOR INITIALIZING MULTIDIMENSIONAL ARRAY */

main()
{
int K[2][3][2]={1,2,3,4,5,6,7,8,9,10,11,12},i,j,p;
clrscr();
printf("\n Array Elements Are = \n\n\n");
for(i = 0 ; i < 2 ; i++)
{
printf("\n\n");
for(j = 0 ; j < 3 ; j++)
{
printf("\n");
for(p = 0 ; p < 2 ; p++)
printf(" %d",K[i][j][p]);
}
}
}
***

STRINGS

A String is defined as a collection of characters. In C language, a character array


itself treated as a string. The general form of declaration of a string variable is:

Syntax: char StringName [size];

Example: char str[10];

 %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.
 Each string is terminated by the null character (‘\0’), which indicates the end of the
string.

Note: Main problem with the scanf() function is that it terminates its input on the occurrence
of first white space.

PBR VITS (Autonomous) Page 82


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

#include<stdio.h>
#include<conio.h>
main()
{
char city[10];
clrscr();
printf("\n Enter City Name =");
scanf("%s",city);
printf("\n RESULT = %s",city);
}

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>
main()
{
char str[50];
clrscr();
printf("\n Enter a line of text =");
gets(str);
printf("\n RESULT =");
puts(str);
}

PBR VITS (Autonomous) Page 83


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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() function: 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 K;
clrscr();
printf("\n Enter a string = ");
gets(str);
K = strlen(str);
printf("\n STRING LENGTH = %d",K);
}

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 string.

/* PROGRAM TO ADD THE GIVEN TWO STRINGS */


#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1 = ");
gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
strcat(str1,str2);
printf("\n Result String = %s”,str1);
}

PBR VITS (Autonomous) Page 84


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

/* 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("\n Enter string 1 = ");
gets(str1);
strcpy(str2,str1);
printf("\n Result String = %s”,str2);
}

4. strcmp() function: It refers to string comparison function.

The general format of strcmp() function is:

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();

PBR VITS (Autonomous) Page 85


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

printf("\n Enter string 1 = ");


gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
k = strcmp(str1,str2);
if(k = = 0)
printf("\n BOTH STRINGS ARE SAME");
else
printf("\n BOTH STRIGNS ARE DIFFERENT");
}

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("\n Enter string 1 = ");
gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
if((strcmpi(str1,str2)) = = 0)
printf("\n BOTH STRIGNS ARE SAME");
else
printf("\n BOTH 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.

PBR VITS (Autonomous) Page 86


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* PROGRAM TO PRINT A STRING IN REVERSE ORDER */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\n Enter 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("\n Enter a String in Upper Case = ");
gets(str);
strlwr(str);
printf("\n Result String in Lower Case =");
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.

PBR VITS (Autonomous) Page 87


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* PROGRAM TO PRINT A STRING IN UPPER CASE */

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

main()
{
char str[10];
clrscr();
printf("\n Enter a String in Lower Case = ");
gets(str);
strupr(str);
printf("\n Result 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 at most n characters of source


string to target string.

/* EXAMPLE PROGRAM */

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

main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1 = ");
gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
strncat(str1,str2,3);
printf("\n Result string = %s”,str1);
}

10. strncpy(): The general format of strncpy() function is:

Syntax: strncpy(targetstring , sourcestring , n);

Where, n is an integer argument. Function copies at most n characters of source


string to target string.

PBR VITS (Autonomous) Page 88


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM */

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

main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1= ");
gets(str1);
strncpy(str2,str1,3);
str2[3] = '\0';
printf("\n Result String = %s”,str2);
}

11. strncmp() function: The general format of strncmp() function is:

Syntax: strncmp(string1 , string2 , n);

Where, n is an integer argument. Function compares at most n characters of the given


two strings.

/* EXAMPLE PROGRAM */

#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1 = ");
gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
if((strncmp(str1,str2,3)) = = 0)
printf(“\n Both Are Same”);
else
printf(“\n Both Are Different”);
}

12. strncmpi() function: The general format of strncmpi() function is:

Syntax: strncmpi(string1 , string2 , n);

Where, n is an integer argument. Function compares at most n characters of the given


two strings without case consideration.

PBR VITS (Autonomous) Page 89


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* 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”);
}

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 a
string constant.
Example : char str[50] = “Language in 1972”;

/* EXAMPLE PROGRAM FOR INITIALING A STRING */

main()
{
char str[50] = "Language in 1972";
clrscr();
printf("\n Result 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”;

PBR VITS (Autonomous) Page 90


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.
Size1 represents maximum number of strings and size2 represents maximum number
of characters in each string.

Example : char str [10][15];

/* PROGRAM TO READ AND PRINT A LIST OF NAMES */

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

main()
{
char x[15][15];
int i,j,n;
clrscr();

printf("\n Enter how many names = ");


scanf("%d",&n);
printf("\n Enter %d Names = ",n);
for(i = 0 ; i < n ; i++)
{
fflush(stdin);
gets(x[i]);
}

printf("\n LIST OF NAMES ARE = \n");


for(i = 0 ; i < = n-1 ; i++)
puts(x[i]);
}

PBR VITS (Autonomous) Page 91


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Initialization of array of strings

1. The general format of initializing array of strings is:

Syntax : char StringName [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( )
{
char x[3][10]={ “India” , “Pakistan” , “Srilanka”};
clrscr();
printf(“\n List of Strings Are =\n”);
for(i=0;i<3;i++)
puts(x[i]);
}

2. Array of strings can also be initialized in the form of array of characters.

Syntax : char StringName [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’ , ‘\0’}
};

3. 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’}
};

PBR VITS (Autonomous) Page 92


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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()
{
char x[10] = "2009";
int k;
clrscr();
k = atoi(x)+6;
printf("\n RESULT VALUE = %d",k);
}

2. 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";
long int k;
clrscr();
k = atol(x)+6;
printf("\n RESULT VALUE = %ld",k);
}

PBR VITS (Autonomous) Page 93


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

3. 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";
float k;
clrscr();
k = atof(x)+6;
printf("\n RESULT VALUE = %f",k);
}

4. itoa() function: itoa() 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<stdlib.h>
main()
{
char x[10];
int k = 49;
clrscr();
printf("\n Octal Format = ");
itoa(k,x,8);
puts(x);
printf("\n Hexadecimal Format = ");
itoa(k,x,16);
puts(x);
}

PBR VITS (Autonomous) Page 94


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

5. 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<stdlib.h>>
main()
{
char x[10]; long int k=49;
printf("\n Hexadecimal Format = ");
ltoa(k,x,16);
puts(x);
}

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<stdlib.h>
main()
{
int k,n,i;
clrscr();
printf("\n Enter How Many Numbers = ");
scanf("%d",&n);
printf("\n Pseudo Random Numbers Are = \n");
for(i=1;i<=n;i++)
{
k = rand();
printf("\t%d",k);
}
} ***

PBR VITS (Autonomous) Page 95


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

UNIT- IV
Pointers & User Defined Data types
Pointers, dereferencing and address operators, pointer and address arithmetic, array
manipulation using pointers, User-defined data types-Structures and Unions.

***

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("\n Address of x = %u",&x);
x = 10; 65524
printf("\n Value 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

PBR VITS (Autonomous) Page 96


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 data type variable.

Example: float *ptr2;


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

Example: char *ptr3;


Here, ptr3 is a pointer variable that can points to a character data type 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.

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.

PBR VITS (Autonomous) Page 97


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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("\n Address of x is = %u",&x);
printf("\n Address of ptr is = %u",&ptr);
x = 10;
printf("\n x value using x = %d",x);
ptr = &x;
printf("\n Value in p = %u",ptr);
printf("\n x value using ptr = %d",*ptr);
}

/* Program to demonstrates every pointer variable occupies same (2 bytes) amount of memory
space */

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(q));
printf(“\n Memory Size of Float Pointer Variable = %d Bytes”,sizeof(r));
printf(“\n Memory Size of Double Pointer Variable = %d Bytes”,sizeof(s));
}

PBR VITS (Autonomous) Page 98


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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(“\n Enter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\n Before Passing to the Function Values Are = %d \t %d",x,y);
change(x,y);
printf("\n After Passing to the Function Values Are = %d \t %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.

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.

PBR VITS (Autonomous) Page 99


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 */

#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("\n Before Passing to the Function Values Are = %d \t %d",x,y);
change(&x , &y);
printf("\n After Passing to the Function Values Are = %d \t %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;

PBR VITS (Autonomous) Page 100


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

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.

Invalid Operations:

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


2. Division of a pointer variable with an integer value is invalid operation.
3. Addition, Multiplication and division of two pointer variables are invalid operations.

/* EXAMPLE PROGRAM FOR POINTER ARITHMETIC OPERATIONS */

#include<stdio.h>

main()
{
int *p1,*p2,x,y;
clrscr();
p1 = &x;
p2 = &y;

printf("\n p1 Address = %u",&p1); /* 65518 */


printf("\n p1 value = %u",p1); /* 65522 */
printf("\n p2 Address = %u",&p2); /* 65520 */
printf("\n p2 value = %u",p2); /* 65524 */

x = p2 - p1;
printf("\n x value = %d",x); /* 1 */

p1 = p1 + 2;
printf("\n p1 value = %u",p1); /* 65526 */

p2 = p2 - 1;
printf("\n p2 value = %u",p2); /* 65522 */
}

PBR VITS (Autonomous) Page 101


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 */

#include<stdio.h>
#include<conio.h>
main()
{
int x = 10;
double y = 3.45678;
void *ptr;
clrscr();
ptr=&x;
printf("\n Value 1 =%d",*(int *)ptr);
ptr=&y;
printf("\n Value 2 =%lf",*(double *)ptr);
}

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. 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 */

main()
{
int *p;
clrscr();
p = NULL;
printf("\n Value = %d",*p);
}

PBR VITS (Autonomous) Page 102


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 variable.

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 K[5] = {10,20,30,40,50};

0 1 2 3 4 Index Values

K 10 20 30 40 50 Element Values

1000 1002 1004 1006 1008 Addresses

Base Address

Here,
K = &K[0] = &K all are referred to the address location 1000. Hence, in C
language array name itself acts a pointer (Address constant).

Note: A slight difference between a pointer variable and array name is, pointer is a
variable that can appear on the left side of an assignment operator, whereas the array name
acts as an address constant and cannot be appear on the left side of the assignment operator.

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 K[3], i=0;

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


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

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

Similarly, for double dimensional arrays,

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

PBR VITS (Autonomous) Page 103


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

#include<stdio.h>
#include<conio.h>
main()
{
int x[10],i,n,*p;
clrscr();
p = x;
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n Enter %d Numbers = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Array Elements Are = ");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}
/* PROGRAM TO READ A DOUBLE DIMENSIONAL ARRAY AND PRINT IT USING POINTERS */

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

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

PBR VITS (Autonomous) Page 104


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

ARRAY OF POINTERS

Array of pointers are used to define more than one pointer variable that can points to
same data type variables. 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 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("\n Elements Are = ");
for(i=0;i<3;i++)
printf(" %d",*p[i]);
}

POINTER AND STRINGS

A string is an array of characters that terminated with a null character ‘\0’. String
means a character array itself; name of the string refers to base address of the array. Hence,
string address can be stored in pointer variable so that string contents can also be accessed
with the pointer variable.

/* EXAMPLE PROGRAM FOR PONTER TO STRING */

main()
{
char str[50]="KAVALI",*p;
int i;
clrscr();
p = str;
printf("\n Result string with STR = %s”,str);
printf(“\n Result string with P =%s”,p);
}

PBR VITS (Autonomous) Page 105


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Note: 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 can also be stored in the pointer variable.

/* EXAMPLE PROGRAM */

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

main()
{
char s[50]="KAVALI",*p="NELLORE";
int i;
clrscr();
printf("\nResult 1:");
puts(s);
printf("\nResult 2:");
puts(p);
}

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:

1. Passing individual element of the array 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("\n Enter How Many Values = ");
scanf("%d",&n);

PBR VITS (Autonomous) Page 106


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

printf("\n Enter %d Elements = ",n);


for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\n Before Passing To Function Array Values Are = \n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
change(x[3]);
printf("\n After 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);

main()
{
int x[10],i,n;
clrscr();
printf("\n Enter How Many Values = ");
scanf("%d",&n);
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\n Before Passing To Function Array Values Are = \n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
sort(x,n);
printf("\n After Passing To Function Array Values Are = \n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}

PBR VITS (Autonomous) Page 107


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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;
}
}
}
}

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("\n Before Sorting Elements Are = ");
for(i=0;i<5;i++)
printf(" %d",x[i]);
k = sort(x,5);
printf("\n After Sorting Elements Are = ");
for(i=0;i<5;i++)
printf(" %d",*(k+i));
}

PBR VITS (Autonomous) Page 108


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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++)
{
if(*(p+i)>*(p+j))
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
}
return 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, *p, **q;


x = 10;
p = &x;
q = &p;

Here,
x is an ordinary variable that holds an ordinary value.
p is a pointer variable that holds address of an ordinary variable.
q is a pointer-to-pointer variable that holds address of a pointer variable.

For this, the total representation should be:

x p q
10 65300 65302

65300 65302 65304

PBR VITS (Autonomous) Page 109


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM FOR POINTER TO POINTER VARIABLE */

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

main()
{
int x = 10,*p,**q;
clrscr();
p = &x;
q = &p;
printf(“\n Value with x is = %d”,x);
printf("\n Value with p is = %d",*p);
printf("\n Value with q is = %d",**q);
}

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.

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.

PBR VITS (Autonomous) Page 110


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

1. malloc() function: malloc() function is used to allocate memory for the variables
at run time. 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 *P;

P = (int*)malloc(10); (or) P = (int*)malloc(5*sizeof(int));

Here, 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 variable. By
default memory location is filled with garbage values. For this, memory allocation will be:

P Garbage Values

10 BYTES

/* EXAMPLE PROGRAM FOR MALLOC() FUCNTION */

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

main()
{
int *p,i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
p = (int*)malloc(n*sizeof(int));
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Array 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.,
The general form of calloc() function is:

Syntax: ptrvariable = (casttype*)calloc(n,elesize);

PBR VITS (Autonomous) Page 111


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Where,
ptrvariable is a pointer variable of type casttype.
n represents number of blocks.
elesize represents block size.

Example: int *P;


P = (int*)calloc(5,sizeof(int));

Here, calloc() function allocates multiple blocks of storage space with each of same
size and by default all locations are initialized with ‘0’s. If there is not enough space to
allocate, then it returns a NULL pointer.

For this, memory allocation will be:

P 0 0 0 0 0
10 BYTES

/* EXAMPLE PROGRAM FOR CALLOC() FUNCTION */

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

main()
{
int *p,i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
p = (int*)calloc(n,sizeof(int));
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Array Elements Are = ");
for(i=0;i<n;i++)
printf(" %d",*(p+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.

PBR VITS (Autonomous) Page 112


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

The general form of realloc() function is:


Syntax: ptrvariable = (casttype*)realloc(ptrvariable,newsize);

Where,
ptrvariable is a pointer variable of type casttype.

Here, realloc() 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.

/* EXAMPLE PROGRAM FOR REALLOC() FUNCTION */

#include<stdio.h>
#include<alloc.h>

main()
{
int *p,i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
p = (int*)malloc(n*sizeof(int));
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
p = (int*)realloc(p,(n+2)*sizeof(int));
printf("\n Enter %d Elements = ",n+2);
for(i=0;i<n+2;i++)
scanf("%d",p+i);
printf("\n Array 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);

PBR VITS (Autonomous) Page 113


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 */

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

main()
{
clrscr();
printf("\n Address of printf function is = %u",printf);
printf("\n Address of scanf function is = %u",scanf);
printf("\n Address 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("\n Address of the Function = %u",show);
}

void show()
{
printf("\n Function 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.

PBR VITS (Autonomous) Page 114


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* 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);
printf("\n Result = %d",z);
}

int show(int a,int b)


{
return a + b;
}

USES OF POINTERS

 Pointer variable holds address of another variable.


 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.

PBR VITS (Autonomous) Page 115


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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; Example: int *p;
char y; 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);
} }

PBR VITS (Autonomous) Page 116


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Differences between Arrays and Pointers

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]);
}
***
PBR VITS (Autonomous) Page 117
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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()

I: 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.

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.

PBR VITS (Autonomous) Page 118


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM FOR getchar() FUNCTION */

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

main()
{
char ch;
clrscr();
printf("\n Enter A Character = ");
ch = getchar();
printf("\n Result 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("\n Enter A Character = ");
ch = getch();
printf("\n Result Character = %c",ch);
}

PBR VITS (Autonomous) Page 119


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

c) 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 */

main()
{
char ch;
clrscr();
printf("\n Enter A Character = ");
ch = getche();
printf("\n Result Character = %c",ch);
}

II: 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.

PBR VITS (Autonomous) Page 120


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM FOR putchar() FUNCTION */

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

main()
{
char ch;
clrscr();
printf("\n Enter A Character = ");
ch = getchar();
printf("\n Result Character = ”);
putchar(ch);
}

b) 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("\n Enter A Character = ");
ch = getchar();
printf("\n Result Character = ”);
putch(ch);
}

PBR VITS (Autonomous) Page 121


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

III: 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.

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.

IV: 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:

PBR VITS (Autonomous) Page 122


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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:

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.
7 4 9 2
Example : printf(“%6d”,7492);

iv. It is possible to add zero’s at blank spaces by placing a ‘0’ before the field
width specifier.
0 0 7 4 9 2
Example : printf(“%06d”,7492);

PBR VITS (Autonomous) Page 123


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 used for displaying the
value.
P indicates the number of digits to be display 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


printf("%6.2f",7491.2579); 7491.26
printf("%6.2f",5678.3); 5678.30

ii. The format specification to print an exponential form of a floating point


number is:

Syntax : %W.Pe

Example: printf("%6.2e",7491245.2579); 7.49e+06

PBR VITS (Autonomous) Page 124


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

c) 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

e) 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);

L A B @ 2 0 1 5

***

PBR VITS (Autonomous) Page 125


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

STRUCTURE

Structure is a user defined data type and can be defined as “It 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 declaration is specified with the keyword “struct” 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:

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[10];
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;

PBR VITS (Autonomous) Page 126


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Now, the compiler allocates memory for the structure variable B1 as

BName :
B1 Pages :

Price :

16 Bytes

i.e., Memory is allocated individually for each member of the structure.

Accessing members of the structure

‘.’ 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>
struct Book
{
char BName[50];
int Pages;
float Price;
};
main()
{
struct Book B1;
clrscr();
printf("\n Enter Title of the Book = ");
gets(B1.BName);
printf("\n Enter Number of Pages = ");
scanf("%d",&B1.Pages);
printf("\n Enter Cost of the Book = ");
scanf("%f",&B1.Price);
printf("\n BOOK TITLE = %s",B1.BName);
printf("\n NUMBER OF PAGES = %d",B1.Pages);
printf("\n BOOK COST = %.2f RS",B1.Price);
}

PBR VITS (Autonomous) Page 127


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 */

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

struct Date
{
int Day,Month,Year;
}K;

main()
{
clrscr();
printf("\n Enter Current Day = ");
scanf("%d",&K.Day);
printf("\n Enter Current Month = ");
scanf("%d",&K.Month);
printf("\n Enter Current Year = ");
scanf("%d",&K.Year);
printf("\n TODAY DATE = %d / %d / %d",K.Day, K.Month ,K.Year);
}

INITIALIZATION OF 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 Book b = {“Let Us C”,350,125.75};

PBR VITS (Autonomous) Page 128


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

 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
{
int pid;
char pname[10];
float price;
};

main()
{
struct product s1 = {111,"soap",25.00};
clrscr();
printf("\n Product Code = %d\n”,s1.pid);
printf(“\n Product Name = %s\n”,s1.pname);
printf(“\n Product 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 s1 and s2 are two structure variables of the same structure type,
and then the details of s1 are copied into s2 as:

s2 = s1;
Here,
Each individual member of s1 is copied into individual member of s2.

PBR VITS (Autonomous) Page 129


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* 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("\n Original structure is = ");
printf("\n %d \t %s \t %.2f",s1.pid,s1.pname,s1.price);
s2 = s1;
printf("\n Copied structure is = ");
printf("\n %d \t %s \t %.2f",s2.pid,s2.pname,s2.price);
}

Comparison:

 Direct comparison of one structure variable with another structure variable using
relational operators is not possible.

i.e., Let s1 and s2 are two structure variables of the same structure type, and then the
comparisons like
s1>s2, s1<s2, s1<=s2, s1>=s2, s1==s2 and s1!=s2 are invalid operations.

However, for comparing structure variables individual member comparisons is


valid.

/* PROGRAM TO COMPARE THE GIVEN TWO STRUCTURES */

#include<stdio.h>
#include<string.h>

struct product
{
int pid;
char pname[10];
};

PBR VITS (Autonomous) Page 130


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

main()
{
struct product s1,s2;
clrscr();
printf("\n Enter Product 1 id = ");
scanf("%d",&s1.pid);
fflush(stdin);
printf("\n Enter Product 1 Name = ");
gets(s1.pname);
printf("\n Enter Product 2 id = ");
scanf("%d",&s2.pid);
fflush(stdin);
printf("\n Enter Product 2 Name = ");
gets(s2.pname);
if((s1.pid = = s2.pid)&&((strcmp(s1.pname,s2.pname)) = = 0))
printf("\n BOTH ARE SAME PRODUCTS ");
else
printf("\n DIFFERENT PRODUCTS ");
}

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;
}
VariableName[Size];

Where,

 struct is a keyword used to define the structure.


 Tag specifies name of the structure that follows same rules as a valid identifier.
 Member1, Member2, - - - - , Membern are the elements of the structure.
 VariableName specifies name of the structure variable that follows same rules as a
valid identifier.
 Size represents maximum number of structure variables.

PBR VITS (Autonomous) Page 131


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM TO READ A LIST OF STUDENTS INFORMATION AND PRINT


USING ARRAY OF STRUCTURES */

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

struct student
{
char name[50],branch[10];
int sub1,sub2;
}s[100];

main()
{
int i,j,n;
clrscr();
printf("\n Enter how many students = ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fflush(stdin);
printf("\n Enter student %d Name = ",i);
gets(s[i].name);
fflush(stdin);
printf("\n Enter student %d Branch = ",i);
gets(s[i].branch);
printf("\n Enter Marks in Two Subjects = ");
scanf("%d%d",&s[i].sub1,&s[i].sub2);
}

printf("\n Student Details Are = ");


for(i=1;i<=n;i++)
printf("\n %s \t %s \t %d \t %d",s[i].name,s[i].branch,s[i].sub1,s[i].sub2);
}

Initializing Array of Structures:

Array of structures can be initialized at the time of its declaration by a list of values
placed within pair of braces. The general format of initializing array of structures is:

Syntax: struct tag varname[size] = { {Record1 Details},


{Record2 Details},
---
---
};

PBR VITS (Autonomous) Page 132


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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”, “AI”,45,78,89} };

main()
{
int i;
clrscr();
printf(“\n Students Details Are = \n”);
for(i=0;i<2;i++)
printf(“\n %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;

PBR VITS (Autonomous) Page 133


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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("\n Enter Name of the Employee = ");
gets(st.name);
printf("\n Enter Date of Joining = ");
scanf("%d%d%d",&st.Join.d,&st.Join.m,&st.Join.y);
printf("\n Enter Salary of the Employee = ");
scanf(“%f”,&st.salary);
printf("\n EMPLOYEE NAME = %s",st.name);
printf("\n SALARY = %.2f RS",st.salary);
printf("\n JOIN DATE = %d / %d / %d",st.Join.d,st.Join.m,st.Join.y);
}

PBR VITS (Autonomous) Page 134


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM FOR INITIALIZING NESTED STRUCTURES */

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

struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st = {“Ravi Kumar”,10,6,2014,23456.25};

main()
{
clrscr();
printf("\n EMPLOYEE NAME = %s",st.name);
printf("\n SALARY = %.2f RS",st.salary);
printf("\n JOIN 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 a 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 the 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.

PBR VITS (Autonomous) Page 135


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 */

#include<stdio.h>
struct Account
{
int Acno;
float AcBalance;
}S = {111,35000.75}, *P;

main()
{
clrscr();
P = &S;
printf("\n ACCOUNT INFORMATION IS = ");
printf("\n %d \t %.2f Rs",P→Acno,P→AcBalance);
}

PBR VITS (Autonomous) Page 136


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

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("\n Before Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
change(s.matches);
printf("\n After Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
}

void change(int K)
{
K = 421;
}

PBR VITS (Autonomous) Page 137


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 variable.

/* PROGRAM TO PASS ENTIRE 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("\n Before Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);

change(s);

printf("\n After Passing = ");


printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
}

void change(struct cricket K)


{
K.matches = 421;
K.avg = 57.23;
}

Case 3: When address of the 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 pointer variable of the same structure type. With this the pointer variable indirectly
points to the original structure.

PBR VITS (Autonomous) Page 138


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Then if we made any changes inside the function on structure, those changes are
recognized by outside function. So that, all changes are effected on the original structure
variable.

/* 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("\n Before Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);

change(&s);

printf("\n After Passing = ");


printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
}

void change(struct cricket *K)


{
K → matches = 421;
K → avg = 57.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.
PBR VITS (Autonomous) Page 139
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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;

Note: typedef declaration does not create any new data types. It just adds a new name for
the existing data type.

 typedef keyword is very useful in the case of user-defined data types like structure.
While using typedef keyword with the structure creation, tag of the structure 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;
clrscr();
printf("\n Enter Real Part = ");
scanf("%f",&k.real);
printf("\n Enter Imaginary Part = ");
scanf("%f",&k.imag);
printf("\n Complex Number is = %.2f + i %.2f",k.real,k.imag);
}

PBR VITS (Autonomous) Page 140


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

SELF-REFERENTIAL STRUCTURE

A structure in which, at least one member that points to same structure type is referred
to as a self-referential structure. The general format of self-referential structure is:

Syntax: struct Tag


{
Datatype Member1;
- - -
struct Tag *Member;
};

Example: struct List


{
int info;
struct List *link;
};

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.

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;

PBR VITS (Autonomous) Page 141


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

Example : struct test


{
unsigned int x:5;
unsigned int y:4;
unsigned int z:5;
}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>

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);
}

Note: 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.

PBR VITS (Autonomous) Page 142


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM TO FORCE BIT GAP IN BETWEEN BIT FIELDS */

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

struct day
{
unsigned int d:5;
:1;
unsigned int m:4;
:1;
unsigned int y:5;
}val;

main()
{
val.d=16;
val.m=10;
val.y=15;
clrscr();
printf("\nCurrent Date =%u / %u / %u",val.d,val.m,val.y);
}

UNION

Union is also a user-defined data type that 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,

 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.

PBR VITS (Autonomous) Page 143


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Example : union Account


{
int acno;
float balance;
char actype[10];
};

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 K;

For this, the memory allocation will be:

10 Bytes

 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 : K . balance;

/* PROGRAM TO CREATE ACCOUNT DATABASE USING UNION */

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

union Account
{
int acno;
char actype[10];
float acbalance;
};

PBR VITS (Autonomous) Page 144


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

main()
{
union Account K;
clrscr();
printf("\n Enter Account Number = ");
scanf("%d",&K.acno);
printf("\n Account Number = %d",K.acno);
fflush(stdin);
printf("\n\n\n Enter Account Type = ");
gets(K.actype);
printf("\n Account Type = %s",K.actype);
printf("\n\n\n Enter Balance Amount = ");
scanf("%f",&K.acbalance);
printf("\n Balance Amount = %.2f RS",K.acbalance);
}

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.
3. A union may be a member of a structure and structure may by a member of union.
These concepts are referred as union of structures and structure of unions.

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 [ ] )


{
- - -
- - -
- - -
}

 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.
 main() function returns an integer value on successful completion.

PBR VITS (Autonomous) Page 145


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* 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("\n Number of arguments = %d",argc);
printf("\n Addition Result = %d",x+y);
return 1;
}

***

PBR VITS (Autonomous) Page 146


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

UNIT- V
Functions & File Handling
Introduction to Functions, Function Declaration and Definition, Function call Return Types
and Arguments, modifying parameters inside functions using pointers, arrays as parameters.
Scope and Lifetime of Variables, Basics of File Handling.

***

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.

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. Error detection and correction is an easy process in simple functions.
6. Large projects can be divided into small parts for easy processing with the help of
functions.

FUNCTION TYPES

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

a) Library functions: Functions those are predefined by the system compiler are
known as library functions.

Example: scanf(), printf(), getch(), getche(), etc.,

For all the library functions, definitions and necessary information is available in
header files.

PBR VITS (Autonomous) Page 147


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 etc,

ctype.h : Character type header file

ctype.h header file provides several library functions used for character testing and
conversion operations. Some of the important library functions are:
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)

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.
PBR VITS (Autonomous) Page 148
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

/* Program to check whether a given character is an alphabet or not */

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

main()
{
char ch;
clrscr();
printf(“\n Enter A Character = “);
scanf(“%c”,&ch)
if(isalpha(ch))
printf(“\n Given Character is An Alphabet”);
else
printf(“\n Given Character is not an Alphabet”);
}

math.h : Mathematical header file

math.h header file provides several library functions used for mathematical operations.
Some of the important library functions are:

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.
Example: printf(“ Result = %lf”, sin(45));

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

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

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

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

PBR VITS (Autonomous) Page 149


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

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

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

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

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

Function receives a double type argument and returns the square root value as double.

Example: printf(“Result = %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.

Example: printf(“Result = %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.
Example: printf(“Result = %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.

Example: printf(“Result = %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.

Example: printf(“Result = %lf”, floor(3.85));

PBR VITS (Autonomous) Page 150


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* Write a program to evaluate the expression 1 + X + X2 + X3 + - - - - - */

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int x,n,i;
double Sum,Term;
clrscr();
printf("\n Enter How Many Terms = ");
scanf("%d",&n);
printf("\n Enter X Value = ");
scanf("%d",&x);
Sum = 1.0;
for(i=1;i<n;i++)
{
Term = pow(x,i);
Sum = Sum + Term;
}
printf(" Expression Result = %lf",Sum);
}

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


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 statement 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.

PBR VITS (Autonomous) Page 151


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 statement is:

Syntax: VariableName = FunctionName(value1, value2, - - - , valuen);

Where, value1,value2, - - -, valuen 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);

3. Function body (or) definition: Function definition contains actual


implementation 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 / temporary 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.

Example: int Fact(int k)


{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}
Note: Function call is treated as the calling function and function definition is treated as the
called function.

PBR VITS (Autonomous) Page 152


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER USING FUNCTIONS */

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

int Fact(int);

main()
{
int P,K;
clrscr();
printf("\n Enter a Value = ");
scanf("%d",&K);
P = Fact(K);
printf("\n Factorial Value = %d",P);
}

int Fact(int N)
{
int i , f = 1;
for(i = 1 ; i < = N ; 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 such 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 4: Functions with arguments and with return value

Case 1: In this case, calling function does not send any data to the called function.
Similarly, after implementation of the function, called function does not return any value to
the calling function.
Note: i) If the function does not return any value, return type must be void.
iii) Default return type of a function is int.

PBR VITS (Autonomous) Page 153


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* Example program for functions without arguments and without return value */

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

void sum();

main()
{
clrscr();
sum();
}

void sum()
{
int x,y,z;
printf("\n Enter Two Values = ");
scanf("%d%d",&x,&y);
z=x+y;
printf("\n Result = %d",z);
}

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

/* Example program for functions with arguments and without return value */

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

void sum(int,int);

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

PBR VITS (Autonomous) Page 154


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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

/* Example program for functions without arguments and with return value */

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

int sum();

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

}
int sum()
{
int x,y,z;
printf("\n Enter 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 for functions with arguments and with return value */

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

int sum(int,int);
main()
{
int x,y,z;
clrscr();
printf("\n Enter Two Values:");
scanf("%d%d",&x,&y);
z = sum(x,y);
printf("\n Result = %d",z);
}

PBR VITS (Autonomous) Page 155


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

int sum(int p,int q)


{
int t;
t = p+q;
return t;
}

INTER FUNCTION COMMUNICATION

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

 Downward flow communication


 Upward flow communication
 Bi-directional flow communication

Downward flow communication

Calling Function In downward flow communication, the


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

Upward flow communication

Calling Function In upward flow 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 communication

Calling Function In bi-directional flow 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

PBR VITS (Autonomous) Page 156


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

NESTED FUNCTIONS

Functions can also be included within another function. Such a 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("\n MAIN FUNCTION STARTS");
fun1();
printf("\n MAIN FUNCTION ENDS");
}

void fun1()
{
printf("\n FUNCTION 1 STARTS");
fun2();
printf("\n FUNCTION 1 ENDS");
}

void fun2()
{
printf("\n FUNCTION 2 STARTS");
printf("\n FUNCTION 2 ENDS");
}

PBR VITS (Autonomous) Page 157


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

RECURSION

A function calls itself is known as recursion and the function is called as recursive
function.

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

Recursion can be classified into two types as:

1. Direct recursion
2. Indirect recursion

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

Example: void sum()


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

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

Example: void sum() void call()


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

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.

PBR VITS (Autonomous) Page 158


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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. Error detection and correction is an easy process in simple functions.
6. Large projects can be divided into small parts for easy processing with the help of
functions.
7. The main advantage of recursion is to reduce the length of the code.

Disadvantages:

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

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(“\n Enter a Value = ”);
scanf(“%d”,&K);
P = Fact(K);
printf(“\n Factorial Value = %d”,P);
}

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

PBR VITS (Autonomous) Page 159


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

LOCAL VARIABLE Vs GLOBAL VARIABLE

Variables declared inside the function definition or block are 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() void change()


{ {
int x = 10; int x;
clrscr(); x = 20;
printf(“\n Value 1 = %d”,x); printf(“\n Value 3 = %d”,x);
change(); }
printf(“\n Value 2 = %d”,x);
}

/* EXAMPLE PROGRAM FOR GLOBAL VARIABLE */

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

void change();

int x = 10;

main()
{
clrscr();
printf(“\n Value 1 = %d”,x);
change();
printf(“\n Value 2 = %d”,x);
}

void change()
{
x = x + 10;
printf(“\n Value 3 = %d”,x);
x = x + 10;
}

PBR VITS (Autonomous) Page 160


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

STORAGE CLASSES
Storage class deals with scope and lifetime 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. Lifetime 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 those
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

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 lifetime 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 */

main()
{
auto int x=100;
clrscr();
printf(“\n Result Value = %d”,x);
}
PBR VITS (Autonomous) Page 161
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.
 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 lifetime 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>

extern int x=100;

main()
{
clrscr();
printf(“\n Result Value = %d”,x);
}

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 static 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.

PBR VITS (Autonomous) Page 162


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

Depending on the place of declaration, static variables are classified into two types 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.

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 */

main()
{
static int x=10;
clrscr();
printf(“\n Result Value = %d”,x);
}

External static variables: Variables declared outside the function with ‘static’
access specifier are known as external static variables.

These variables are available to all functions. The scope of external static variable is
only in that file and the lifetime is global.

/* EXAMPLE PROGRAM FOR EXTERNAL STATIC VARIABLES */

#include<stdio.h>

static int x=10;

main()
{
clrscr();
printf(“\n Result Value = %d”,x);
}

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:

Syntax : register datatype identifier;

Example : register int x;

PBR VITS (Autonomous) Page 163


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

 Register variables are declared inside the function or block.


 For register variables memory is allocated in the register 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 lifetime is until end of the block or function.

/* EXAMPLE PROGRAM FOR REGISTER VARIABLES */

main()
{
register int x=10;
clrscr();
printf(“\n Result Value = %d”,x);
}

SYMBOLIC CONSTANTS

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

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>

#define PI 3.14159

main()
{
double R, Area;
clrscr();
printf(“\n Enter Radius of the Circle = ”);
scanf(“%lf”,&R);
Area = PI * R * R;
printf(“\n Area of the Circle = %lf”,Area);
}

PBR VITS (Autonomous) Page 164


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

TYPE QUALIFIERS

C provides three type qualifiers const, volatile and restrict that describes nature of
the identifiers to the compiler. Here, const and volatile qualifiers can be applied to any
variables, but restrict qualifier can be applied only on pointer variables.

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 K = 10;

/* EXAMPLE PROGRAM FOR CONSTANT VARIABLE */

main()
{
const int K = 10;
clrscr();
printf(“\n Result = %d”,K);
}

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 K;

/* EXAMPLE PROGRAM FOR VOLATILE VARIABLE */

main()
{
volatile int K = 10;
clrscr();
printf(“\n Result 1= %d”,K);
K = 20;
printf(“\n Result 2= %d”,K);
}

PBR VITS (Autonomous) Page 165


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

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

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


substitution. The general format of a macro substitution directive is:

Syntax: #define MacroName MacroValue

Example: #define PI 3.14159

Consider the following example.

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

#define PI 3.14159
main()
{
float R = 3.97,A;

PBR VITS (Autonomous) Page 166


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

clrscr();
A = PI * R * R;
printf(“\n AREA OF THE CIRCLE IS = %f”,A);
}

In this source program, pre-processor replaces the macro name PI with a single macro
value as 3.14159. Now, it works as:

main()
{
float R = 3.97,A;
clrscr();
A = 3.14159 * R * R;
printf(“\n AREA OF THE CIRCLE IS = %f”,A);
}

In this type of macro’s, the macroname is replaced with a single macrovalue. Hence,
such type of macro substitution is referred as simple macro substitution.

ii) Macro can also have arguments and is possible to replace for a single
statement. Such type of macro substitution is known as argument macro
substitution.

Consider the following example.

#include<stdio.h>

#define area(x) 3.14159*x*x

main()
{
float R = 3.97,A;
clrscr();
A = area (R);
printf(“\n AREA OF THE CIRCLE IS = %f”,A);
}

In this program, preprocessor replaces the macro area(x) with 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(“\n AREA OF THE CIRCLE IS = %f”,A);
}

PBR VITS (Autonomous) Page 167


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

iii) 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
except the last line while defining the macro.

/* EXAMPLE PROGRAM */

#include<stdio.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: #include <FileName>


(or)
#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”

PBR VITS (Autonomous) Page 168


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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
#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 */

#include<stdio.h>

#define vax 1
#define sun 0

main()
{
clrscr();
#if vax
printf(“\n TRUE ”);
#else
printf(“\n FALSE”);
#endif
}
***

PBR VITS (Autonomous) Page 169


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

STREAM

A stream is a sequence 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.

PBR VITS (Autonomous) Page 170


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

1. CONSOLE I/O FUNCTIONS

Console I/O functions always use the terminals keyboard and screen as the target
place.

Console I/O functions can further classified into two categories as formatted and un-
Formatted console I/O functions.

Console I/O Functions

Formatted I/O Functions Non-formatted I/O Functions

scanf() getch()
printf() getche()
getchar()
putch()
putchar()
gets()
puts()

These functions work on console effectively as long as the data is small. Console
representation is not suitable to manage large volume of data.

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 in terms 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.

Example: Input.dat (Data File)


Sum.c (C Language File)
Cpath.bat (Batch File)
Hello.exe (Executable File) etc.,

PBR VITS (Autonomous) Page 171


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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:

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.

PBR VITS (Autonomous) Page 172


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.

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/append 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.

PBR VITS (Autonomous) Page 173


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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("\n FILE 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.


 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.

PBR VITS (Autonomous) Page 174


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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 function 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.

PBR VITS (Autonomous) Page 175


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* EXAMPLE PROGRAM FOR ERROR HANDLING MECHANISM */

#include<stdio.h>
#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 Occurred:");
exit();
}
putchar(Ch);
}
fclose(f);
}

INPUT AND OUTPUT OPERATIONS ON FILES

1. fgetc() and fputc() functions:

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.

PBR VITS (Autonomous) Page 176


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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>
#include<conio.h>
main()
{
char ch;
FILE *fp1,*fp2;
clrscr();
fp1 = fopen("demo.txt","r");
if(fp1 = = NULL)
{
printf("\n FILE 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:

Syntax: fgets(char[], int, FilePointer);

PBR VITS (Autonomous) Page 177


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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("\n FILE OPENING ERROR");
exit();
}

fp2 = fopen("ptr.txt","w");
while((fgets(ch,sizeof(ch),fp1))!=NULL)
fputs(ch,fp2);

fclose(fp2);
fclose(fp1);
}

PBR VITS (Autonomous) Page 178


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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);

PBR VITS (Autonomous) Page 179


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

f1 = fopen("input.dat","r");
if(f1 = = NULL)
{
printf("\n FILE 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("\n EVEN NUMBERS ARE:");
f2 = fopen("even.dat","r");
while((item = getw(f2))!=EOF)
printf("%6d",item);
fclose(f2);
printf("\n ODD 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.

PBR VITS (Autonomous) Page 180


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.,

/* 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("\n Enter product id:");
scanf("%d",&p.id);
fflush(stdin);
printf("\n Enter product name:");
gets(p.name);
printf("\n Enter product cost:");
scanf("%f",&p.price);
fprintf(f,"%d\t%s\t%f\n",p.id,p.name,p.price);
printf("\n Do you want add another record(y/n):");
fflush(stdin);
flag = getchar();
}
fclose(f);
f = fopen("product.dat","r");

PBR VITS (Autonomous) Page 181


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

if(f = = NULL)
{
printf("\n FILE OPENING ERROR");
exit();
}
printf("\n PRODUCT 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)


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>
#include<conio.h>

main()
{
char ch;
clrscr( );
printf("\nEnter data:");
while((ch = fgetc(stdin))!=EOF)
fputc(ch,stdout);
}

PBR VITS (Autonomous) Page 182


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.
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);

PBR VITS (Autonomous) Page 183


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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>
#include<conio.h>
main()
{
int x;
float y;
char z='\n';
FILE *fp;
clrscr();
fp=fopen("Exam.txt","w");
printf("\n Enter 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>
#include<conio.h>

typedef struct
{
int rno;
char name[25],branch[5];
}student;

main()
{
int i,n;
student s[20];
FILE *f = fopen("st.txt","wb");
clrscr( );
PBR VITS (Autonomous) Page 184
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

printf("\n Enter how many students:");


scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n Enter 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()
c) rewind()

PBR VITS (Autonomous) Page 185


I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

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.


PBR VITS (Autonomous) Page 186
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER

/* 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;
char ch;
clrscr();
fp = fopen("win.dat","r");
if(fp = = NULL)
{
printf("\n File 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);
}

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();

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 zero if successful; otherwise, it returns EOF marker.

THE END
PBR VITS (Autonomous) Page 187

You might also like