0% found this document useful (0 votes)
12 views149 pages

Algorithmic Problem Solving Techniques

This document provides an overview of algorithmic problem solving, detailing the problem-solving process, techniques, and the construction of algorithms using various notations such as pseudocode and flowcharts. It discusses the qualities of good algorithms, control structures, and the differences between programming languages, including low-level, assembly, and high-level languages. Additionally, it highlights the advantages and disadvantages of using pseudocode and flowcharts in programming.
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)
12 views149 pages

Algorithmic Problem Solving Techniques

This document provides an overview of algorithmic problem solving, detailing the problem-solving process, techniques, and the construction of algorithms using various notations such as pseudocode and flowcharts. It discusses the qualities of good algorithms, control structures, and the differences between programming languages, including low-level, assembly, and high-level languages. Additionally, it highlights the advantages and disadvantages of using pseudocode and flowcharts in programming.
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

UNIT I ALGORITHMIC PROBLEM SOLVING

INTRODUCTION

PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of
solutions.
The problem solving process starts with the problem specifications and ends with a
correct program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing logic for solving a
problem.
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
[Link]
It is defined as a sequence of instructions that describe a method for solving a problem.
In other words it is a step by step procedure for solving a problem

• Should be written in simple English


• Each and every instruction should be precise and unambiguous.
• Instructions in an algorithm should not be repeated infinitely.
• Algorithm should conclude after a finite number of steps.
• Should have an end point
• Derived results should be obtained only after the algorithm terminates.

Qualities of a good algorithm

The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser
is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such algorithms may be
suitable

Building Blocks of Algorithm


As algorithm is a part of the blue-print or plan for the computer program. An algorithm is
constructed using following blocks.
• Statements
• States
• Control flow
• Function

2
Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may
consists of assignment statements, input/output statements, comment statements
Example:
• Read the value of ‘a’ //This is input statement
• Calculate c=a+b //This is assignment statement
• Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.

States
An algorithm is deterministic automation for accomplishing a goal which, given an initial
state, will terminate in a defined end-state.
An algorithm will definitely have start state and end state.

Control Flow
Control flow which is also stated as flow of control, determines what section of code is to
run in program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow

Sequential control flow:


The name suggests the sequential control structure is used to perform the action one after
another. Only one step is executed once. The logic is top to bottom approach.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop
Selection or Conditional control flow
Selection flow allows the program to make choice between two alternate paths based on
condition. It is also called as decision structure
Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of two
numbers.
Example
Description: finding the greater number
1. Start
2. Read a

3
3. Read b
4. If a>b then
4.1. Print a is greater
else
4.2. Print b is greater
5. Stop

Repetition control flow


Repetition control flow means that one or more steps are performed repeatedly until some
condition is reached. This logic is used for producing loops in program logic when one one more
instructions may need to be executed several times or depending on condition.
Basic Structure:
Repeat untilCONDITIONis true
Statements
Example
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n

4.1. Print i
5. Stop

Function
A function is a block of organized, reusable code that is used to perform a single, related
action. Function is also named as methods, sub-routines.
Elements of functions:
1. Name for declaration of function
2. Body consisting local declaration and statements
3. Formal parameter
4. Optional result type.
Basic Syntax
function_name(parameters)
function statements
end function

Algorithm for addition of two numbers using function


Main function()
Step 1: Start
Step 2:Call the function add()
Step 3: Stop
sub function add()
Step1:Functionstart

4
Step2:Geta,bValues
Step 3: add c=a+b
Step 4: Printc
Step 5: Return

[Link] OF AN ALGORITHM
Algorithm can be expressed in many different notations, including Natural Language,
Pseudo code, flowcharts and programming languages. Natural language tends to be verbose
and ambiguous. Pseudocode and flowcharts are represented through structured human language.
A notation is a system of characters, expressions, graphics or symbols designs used among
each others in problem solving to represent technical facts, created to facilitate the best result for a
program
Pseudocode
Pseudocode is an informal high-level description of the operating principle of a
computer program or algorithm. It uses the basic structure of a normal programming language,
but is intended for human reading rather than machine reading.
It is text based detail design tool. Pseudo means false and code refers to instructions
written in programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax
rules. The pseudocode is written in normal English language which cannot be understood by the
computer.

Example:
Pseudocode: To find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to read the
input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE,
ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:

5
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b is greater
ENDIF
5. Keep statements language independent.
Pesudocode must never written or use any syntax of any programming language.

Advantages of Pseudocode
• Can be done easily on a word processor
• Easily modified
• Implements structured concepts well
• It can be written easily
• It can be read and understood easily
• Converting pseudocode to programming language is easy as compared with
flowchart
Disadvantages of Pseudocode
• It is not visual
• There is no standardized style or format
Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes,
diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
[Link] Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.

2. Input/ Output Parallelogram Denotes either input or


symbol output operation.

3. Process symbol Rectangle Denotes the process to be


carried

4. Decision symbol Diamond Represents decision


making and branching

5. Flow lines Arrow lines Represents the sequence


of steps and direction of
flow. Used to connect
symbols.

6
6. Connector Circle A connector symbol is
represented by a circle
and a letter or digit is
placed in the circle to
specify the link. This
symbol is used to
connect flowcharts.

Rules for drawing flowchart


1. In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
2. The flow chart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or top to
bottom.
Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, cap leave the decision symbol.

5. Only one flow line is used in conjunction with terminal symbol.

6. If flowchart becomes complex, it is better to use connector symbols to reduce the


number of flow lines.
7. Ensure that flowchart has logical start and stop.

Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for various
purposes.
Efficient Coding

7
The flowcharts act as a guide or blue print during the system analysis and program
development phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart. It
helps the programmer to put efforts more efficiently on that part.

Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart
becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
Control Structures using flowcharts and Pseudocode
Sequence Structure
Pseudocode Flow Chart
General Structure
Process 1
…. Process 1
Process 2

Process 2
Process 3

Process 3

Example

READ a
Start
READ b
Result c=a+b
PRINT c a=10,b=20

c=a+b

print c

Stop

8
Conditional Structure
• Conditional structure is used to check the condition. It will be having two outputs only (True or False)
• IF and IF…ELSE are the conditional structures used in Python language.
• CASE is the structure used to select multi way selection control. It is not supported in Python.

Pseudocode Flow Chart


General Structure
IF condition THEN Yes
Process 1 if(condition)
ENDIF

Process 1 No

Process 2
Example
READ a
READ b Start

IF a>b THEN
PRINT a is greater a=10,b=20

Yes if (a>b)

Print a is greater No

Stop

IF… ELSE
IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1,
else, that is condition is false then execute Process2

Pseudocode Flow Chart


General Structure
IF condition THEN
Process 1 Yes if(condition)
ELSE
Process 2
ENDIF Process 1 No

Process 2

Example

9
READ a Start

READ b
IF a>b THEN
a=10,b=20
PRINT a is greater

Yes if (a>b)

Print a is greater
No

Print b is greater

Stop

Iteration or Looping Structure


• Looping is generally used with WHILE or DO...WHILE or FOR loop.
• WHILE and FOR is entry checked loop

Pseudocode Flow Chart


General Structure
WHILE condition
Body of the loop No
ENDWHILE if(condition)

Yes
Body of the loop

Example

• DO…WHILE is exit checked loop, so the loop will be executed at least once.

10
INITIALIZE a=1 Start

WHILE a<10 THEN


PRINT a
a=1
a=a+1
ENDWHILE
No
if (a<10)

Yes
Stop
Print a

a=a+1

o In python DO…WHILE is not supported.


o If the loop condition is true then the loop gets into infinite loop, which may lead to system
crash

Programming Language
• A programming language is a vocabulary and set of grammatical rules for instructing a computer
or computing device to perform specific tasks. In other word it is set of instructions for the
computer to solve the problem.
• Programming Language is a formal language with set of instruction, to the computer to solve a
problem. The program will accept the data to perform computation.
Program= Algorithm +Data
Need for Programming Languages
• Programming languages are also used to organize the computation
• Using Programming language we can solve different problems
• To improve the efficiency of the programs.
Types of Programming Language
In general Programming languages are classified into three types. They are
• Low – level or Machine Language
• Intermediate or Assembly Language
• High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers. It is also
called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions
and variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y

11
High – level Language:
A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that
enables a programmer to write programs that are more or less independent of a particular type of
computer. Such languages are considered high-level because they are closer to human languages and
further from machine languages. Ultimately, programs written in a high-level language must be translated
into machine language by a compiler or interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below.

Language Type Example


Interpreted Programming Language Python, BASIC, Lisp
Functional Programming Language Clean, Curry, F#
Compiled Programming Language C++,Java, Ada, ALGOL
Procedural Programming Language C,Matlab, CList
Scripting Programming Language PHP,Apple Script, Javascript
Markup Programming Language HTML,SGML,XML
Logical Programming Language Prolog, Fril
Concurrent Programming Language ABCL, Concurrent PASCAL
Object Oriented Programming Language C++,Ada, Java, Python
Interpreted Programming Language:
Interpreter is a program that executes instructions written in a high-level language.
An interpreter reads the source code one instruction or one line at a time, converts this line into
machine code and executes it.

Figure : Interpreter
Compiled Programming Languages
Compile is to transform a program written in a high-level programming language from source
code into object code. This can be done by using a tool called compiler.
A compiler reads the whole source code and translates it into a complete machine code program to
perform the required tasks which is output as a new file.

Figure: Compiler

12
Interpreted vs. Compiled Programming Language
Interpreted Programming Language Compile Programming Language
Translates one statement at a time Scans entire program and translates it as whole
into machine code
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower comparatively faster
No intermediate object code is generated, Generates intermediate object code which
hence are memory efficient further requires linking, hence requires more
memory
Continues translating the program until first It generates the error message only after
error is met, in which case it stops. Hence scanning the whole program. Hence debugging
debugging is easy. is comparatively hard.
Eg: Python, Ruby Eg: C,C++,Java

[Link] PROBLEM SOLVING:

Algorithmic problem solving is solving problem that require the formulation of an


algorithm for the solution.

Understanding the Problem


 It is the process of finding the input of the problem that the algorithm solves.
 It is very important to specify exactly the set of inputs the algorithm needs to handle.
 A correct algorithm is not one that works most of the time, but one that works
Correctly for all legitimate inputs.

13
Ascertaining the Capabilities of the Computational Device

If the instructions are executed one after another, it is called sequential algorithm

Choosing between Exact and Approximate Problem Solving


• The next principal decision is to choose between solving the problem exactly or solving it
approximately.
• Based on this, the algorithms are classified as exact algorithm and approximation
algorithm.
• Data structure plays a vital role in designing and analysis the algorithms.
• Some of the algorithm design techniques also depend on the structuring data specifying a
problem’s instance
• Algorithm+ Data structure=programs.

Algorithm Design Techniques


• An algorithm design technique (or “strategy” or “paradigm”) is a general approach to solving
problems algorithmically that is applicable to a variety of problems from different areas of
computing.
• Learning these techniques is of utmost importance for the following reasons.
• First, they provide guidance for designing algorithms for new problems,
Second, algorithms are the cornerstone of computer science.

Methods of Specifying an Algorithm


• Pseudocode is a mixture of a natural language and programming language-like constructs.
Pseudocode is usually more precise than natural language, and its usage often yields more succinct
algorithm [Link] the earlier days of computing, the dominant vehicle for specifying
algorithms was a flowchart, a method of expressing an algorithm by a collection of connected
geometric shapes containing descriptions of the algorithm’s steps.

• Programming language can be fed into an electronic computer directly. Instead, it needs to be
converted into a computer program written in a particular computer language. We can look at such
a program as yet another way of specifying the algorithm, although it is preferable to consider it as
the algorithm’s implementation.

• Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.

• A common technique for proving correctness is to use mathematical induction because an


algorithm’s iterations provide a natural sequence of steps needed for such proofs.

• It might be worth mentioning that although tracing the algorithm’s performance for a few specific
inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively.
But in order to show that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.

Analyzing an Algorithm

1. Efficiency.
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses

14
2. simplicity.
 An algorithm should be precisely defined and investigated with mathematical
expressions.
 Simpler algorithms are easier to understand and easier to program.
 Simple algorithms usually contain fewer bugs.

Coding an Algorithm
 Most algorithms are destined to be ultimately implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity.
 A working program provides an additional opportunity in allowing an empirical analysis
of the underlying algorithm. Such an analysis is based on timing the program on several
inputs and then analyzing the results obtained.

[Link] strategies for developing algorithm:


They are two commonly used strategies used in developing algorithm
1. Iteration
2. Recursion
Iteration
• The iteration is when a loop repeatedly executes till the controlling condition becomes false
• The iteration is applied to the set of instructions which we want to get repeatedly executed.
• Iteration includes initialization, condition, and execution of statement within loop and update
(increments and decrements) the control variable.
A sequence of statements is executed until a specified condition is true is called iterations.
1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
BEGIN
FOR( start-value to end-value) DO GET n
statement INITIALIZE i=1
... ENDFOR FOR (i<=n) DO
PRINT i
i=i+
1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
BEGIN
WHILE (condition) DO GET n
statement INITIALIZE i=1
... WHILE(i<=n) DO
ENDWHILE PRINT i
i=i+1
ENDWHILE
END

15
Recursions:
 A function that calls itself is known as recursion.
 Recursion is a process by which a function calls itself repeatedly until some specified condition has
beensatisfied.

Algorithm for factorial of n numbers using recursion:

Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop

Sub function factorial(n):


Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact

16
FLOW CHART

Pseudo code for factorial using recursion:

Main function:

BEGIN
GET n
CALL
factorial(n)
PRINT fact
BIN

Sub function factorial(n):

IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

17
5. ILLUSTRATIVE PROBLEMS
1. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare n, guess
Step 3: Compute guess=input
Step 4: Read guess
Step 5: If guess>n, then
Print your guess is too high
Else
Step6:If guess<n, then
Print your guess is too low
Else
Step 7:If guess==n,then
Print Good job
Else
Nope
Step 6: Stop

Pseudocode:
BEGIN
COMPUTE guess=input
READ guess,
IF guess>n
PRINT Guess is high
ELSE
IF guess<n
PRINT Guess is low
ELSE
IF guess=n
PRINT Good job
ELSE
Nope
END

18
Flowchart:

Start

Read n

Read
Guess number

Guess=input

If Guess>n

If Guess<n

Your guess is If Guess==n


too high
Your guess
is too low nope

Good job

Stop

19
[Link] minimum in a list
Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Compute min=a[0]
Step 6: Initialize i=1
Step 7: If i<n, then go to step 8 else goto step 10
Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8.2
Step 8.1: min=a[i]
Step 8.2: i=i+1 goto 7
Step 9: Print min
Step 10: Stop

Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END

20
Flowchart:

21
3. Insert a card in a list of sorted cards
Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Read item
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
Step 11: Stop

Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END

22
Flowchart:

23
[Link] of Hanoi
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
than one rings.
Tower of Hanoi is one of the best example for recursive problem solving.
Pre-condition:
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller
one sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.

Post-condition:
All the disk should be moved to the last pole and placed only in ascending order as shown
below.

Rules
The mission is to move all the disks to some another tower without violating the sequence
of arrangement. A few rules to be followed for Tower of Hanoi are
• Only one disk can be moved among the towers at any given time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation
shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with
lesser amount of disks, say → 1 or 2. We mark three towers with name, source, aux (only to help
moving the disks) and destination.
Input: one disk
If we have only one disk, then it can easily be moved from source to destination peg.
Input: two disks
If we have 2 disks −
• First, we move the smaller (top) disk to aux peg.
• Then, we move the larger (bottom) disk to destination peg.
• And finally, we move the smaller disk from aux to destination peg.
Input: more than two disks
• So now, we are in a position to design an algorithm for Tower of Hanoi with more than
two disks. We divide the stack of disks in two parts. The largest disk (n th disk) is in one
part and all other (n-1) disks are in the second part.

24
• Our ultimate aim is to move disk n from source to destination and then put all other (n1)
disks onto it. We can imagine to apply the same in a recursive way for all given set of
disks.
• The steps to follow are –
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest

A recursive algorithm for Tower of Hanoi can be driven as follows –


START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP

25
FLOW CHART Start

Enter disk i.e number


of disks

Call the function


Hanoi(n,A,C,B)

Stop

If disk==1?

Print move disk from


A to C

Call function Hanoi with


disk-1,A,B,C

Print move disk


from A to C

Call function Hanoi


with disk-1,C,A,B

Return

26
5. Draw a flow chart to find greatest among three numbers.(AU 2018)

6. Draw a flow chart to find sum of n numbers(AU 2018)

27
2 MARKS

1. What is an algorithm?
An algorithm is a finite number of clearly described, unambiguous do able steps that
can be systematically followed to produce a desired results for given input in the given amount
of time. In other word, an algorithm is a step by step procedure to solve a problem with finite
number of steps.

2. What is Pseudo code?


Pseudocode is an informal high-level description of the operating principle of a
computer program or algorithm. Pseudo means false and code refers to instructions
written in programming language.

3. What is Problem Solving?


Problem solving is the systematic approach to define the problem and creating
number of solutions. The problem solving process starts with the problem specifications
and ends with a correct program.

4. Distinguish between algorithm and program.

Algorithm Program
1. Systematic logical approach which is a It is exact code written for
well-defined, step-by-step procedure that problem following all the rules of the
allows a computer to solve a problem. programming language.

2. An algorithm is a finite number of clearly The program will accept the data to
described, unambiguous do able steps that perform computation.
can be systematically followed to produce
a desired results for given input in the Program=Algorithm + Data
given amount of time.

5. Define Flow chart.


A graphical representation of an algorithm. Flow charts is a diagram made up of
boxes, diamonds, and other shapes, connected by arrows.

6. Write an algorithm to accept two numbers, compute the sum and print the result.
Step 1: Start
Step 2: Declare variables num1,num2 and sum,
Step 3: Read values num 1 and num2.
Step 4: Add and assign the result to sum.
Sum←num1+num2
Step 5: Display sum

28
7. Differentiate between iteration and recursion.

[Link] Iteration Recursion


1. Iteration is a process of executing Iteration is a process of
certain set of instructions repeatedly,
executing certain set of
without calling the self function. instructions repeatedly, by
calling the self function
repeatedly.
2. Iterative methods are more efficient Recursive methods are less
because of better execution speed. efficient.
3. It is simple to implement. Recursive methods are complex
to implement.

8. What is Programming language? With example.


Programming Language is a formal language with set of instruction, to the
computer to solve a problem. Java, C, C++, Python, PHP.

9. What are the steps for developing algorithms.


• Problem definition
• Development of a model
• Specification of Algorithm
• Designing an Algorithm
• Checking the correctness of Algorithm
• Analysis of Algorithm
• Implementation of Algorithm
• Program testing
• Documentation Preparation

10. What are the Guidelines for writing pseudo code?


• Write one statement per line
• Capitalize initial keyword
• Indent to hierarchy
• End multiline structure
• Keep statements language independent.

29
[Link] a flow chart to find whether the given number is leap year or not.

Start

Read year

If
(year%4==0)

Print ‘Leap year’ Print ‘Not Leap year’

Stop

30
CS3251 PROGRAMMING IN C L

COURSE OBJECTIVES:
• To understand the constructs of C Language.
• To develop C Programs using basic programming constructs
• To develop C programs using arrays and strings
• To develop modular applications in C using functions
• To develop applications in C using pointers and structures
• To do input/output and file handling in C

UNIT I BASICS OF C PROGRAMMING


Introduction to programming paradigms – Applications of C Language - Structure of C program
- C programming: Data Types - Constants – Enumeration Constants - Keywords – Operators:
Precedence and Associativity - Expressions - Input/Output statements, Assignment statements –
Decision making statements - Switch statement - Looping statements – Preprocessor directives -
Compilation process

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array – Two dimensional
arrays - String operations: length, compare, concatenate, copy – Selection sort, linear and binary
search.
UNIT III FUNCTIONS AND POINTERS
Modular programming - Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion, Binary Search using recursive functions – Pointers
– Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Parameter
passing: Pass by value, Pass by reference.

UNIT IV STRUCTURES AND UNION


Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes
and Visibility.

UNIT V FILE PROCESSING


Files – Types of file processing: Sequential access, Random access – Sequential access file -
Random access file - Command line arguments.
COURSE OUTCOMES: Upon completion of the course, the students will be able to
CO1: Demonstrate knowledge on C Programming constructs
CO2: Develop simple applications in C using basic constructs
CO3: Design and implement applications using arrays and strings
CO4: Develop and implement modular applications in C using functions.
CO5: Develop applications in C using structures and pointers.
CO6: Design applications using sequential and random access file processing.

TOTAL : 45 PERIODS

TEXT BOOKS:
1. ReemaThareja, “Programming in C”, Oxford University Press, Second Edition, 2016.
2. Kernighan, B.W and Ritchie,D.M, “The C Programming language”, Second Edition, Pearson
Education, 2015.

REFERENCES:
1. Paul Deitel and Harvey Deitel, “C How to Program with an Introduction to C++”, Eighth edition,
Pearson Education, 2018.
2. Yashwant Kanetkar, Let us C, 17th Edition, BPB Publications, 2020.

3. Byron S. Gottfried, “Schaum’s Outline of Theory and Problems of Programming with C”,
McGraw-Hill Education, 1996.
4. Pradip Dey, Manas Ghosh, “Computer Fundamentals and Programming in C”, Second Edition,
Oxford University Press, 2013.
5. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, 1st Edition,
Pearson Education, 2013.
UNIT 1
BASICS OF C PROGRAMMING
Introduction to programming paradigms – Applications of C Language - Structure of C program - C
programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Preprocessor directives - Compilation process .

1. INTRODUCTION TO PROGRAMMING PARADIGMS:


C INTRODUCTION:
The programming language “C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has become such a
popular language that a variety of software programs are written using this language.
The greatest advantage of using C for programming is that it can be easily used on different types
of computers. Many other programming languages such as C++ and Java are also based on C which means
that you will be able to learn them easily in the future. Today, C is widely used with the UNIX operating
system.

PROGRAMMING PARADIGMS:
In computing, a program is a specific set of ordered operation for a computer to [Link] process
of developing and implementing various sets of instruction to enable a computer to perform a certain task
is called PROGRAMMING.
PROGRAMMING PARADIGMS INCLUDE:
1. IMPERATIVE PROGRAMMING PARADIGMS:
Command show how the computation takes place, step by step. Each step affects the global
state of the computation.
2. STRUCTURED PROGRAMMING PARADIGMS:
It is a kind of imperative programming where the control flow is defined by nested loops,
conditionals, and subroutines, rather than via gotos. Variables generally local to blocks.
3. OBJECT ORIENTED PROGRAMMING(OOP) PARADIGMS:
It is a programming paradigms based on the concepts of objects, which may contain data, in the
form of fields, often known as attributes, and code, in the form of procedures, often known as
methods.
4. DECLARATIVE PROGRAMMING PARADIGMS:
The programmer states only what the results should look like , not how to obtain it. No loops,
no assignments, etc. Whatever engines that interprets this code is just supposed go gets the
desired information and can use whatever approach its wants.
5. FUNCTIONAL PROGRAMMING PARADIGMS:
In functional programming, control flow is expressed by combining functional calls, rather than
by assigning values to variables.
6. PROCEDURAL PROGRAMMING PARADIGMS:
This paradigms includes imperative programming with procedure calls.
7. EVENT DRIVEN PROGRAMMING PARADIGMS:
In which the flow of the program is determined by events such as user action(mouse clicks, key
presses), sensor output, or message from other program/threads. It is the dominant paradigms
used in GUI and other applications that are centred on performing certain action in response to
user input.
8. FLOW DRIVEN PROGRAMMING PARADIGMS:
Programming processes communicating with each other over predefined channels.
9. LOGIC PROGRAMMING PARADIGMS:
Here programming is done by specifying a set of facts and rules. An engine infers the answer
to question.
10. CONSTRAINTS PROGRAMMING PARADIGMS:
An engine finds the value that meet the constraints.
One of the characteristics of a language is its support for particular programming
paradigms. For example: small talks has direct support for programming in the object oriented
way, so it might called an object oriented language.
Very few language implement a paradigms 100%, when they do, they are “PURE”. It is
incredibly rare to have a “pure OOP language” or a “pure functional language”.
A lot of language will facilitate programming in one or more paradigms. If a language is
purposely designed to allow programming in many paradigms is called a “multi paradigms
language”.
APPLICATION OF C:
1. OPERATING SYSTEM
2. EMBEDDED SYSTEM
3. GUI(GRAPHICAL USER INTERFACE)
4. NEW PROGRAMMING PLATFORMS
5. GOOGLE
6. MOZILLA FIREBOX AND THUNDERBIRD
7. MYSQL
8. COMPILER DESIGN
9. ASSEMBLERS
10. TEXT EDITORS
11. DRIVERS
12. NETWORK DEVICES
13. GAMING AND ANIMATION
FEATURES OF C PROGRAMMING/ADVANTAGES:
• C is a robust language with rich set of built in function.
• Programs written in c are efficient and fast.
• C is highly portable, programs once written in c can be run on another machine with minor or no
modification.
• C is basically a collection of c library functions, we can also create our own function and add it to
the c library.
• C is easily extensible.
DISADVANTAGE OF C:
• C doesnot provide OOP.
• There is no concepts of namespace in c.
• C doesnot provides binding or wrapping up of a single unit.
• C doesnot provide constructor and destructor.
STRUCTURE OF C:

Documentation section:
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to use later.

Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.

Definition section: The definition section defines all symbolic constants such using the
#define directive.
Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that
is outside of all the functions. This section also declares all the user-defined functions.
Main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part.
Declaration part:
The declaration part declares all the variables used in the executable part.
Executable part:
There is at least one statement in the executable part. These two parts must appear between
the opening and closing braces. The program execution begins at the opening brace and ends at
the closing brace. The closing brace of the main function is the logical end of the program. All
statements in the declaration and executable part end with a semicolon.

Subprogram section:
If the program is a multi-function program then the subprogram section contains all the
user-defined functions that are called in the main () function. User-defined functions are
generally placed immediately after the main () function, although they may appear in any order.
All section, except the main () function section may be absent when they are not required.

C PROGRAMMING: DATA-TYPES
A data-type in C programming is a set of values and is determined to act on those
values. C provides various types of data-types which allow the programmer to select the
appropriate typefor the variable to set its value.
The data-type in a programming language is the collection of data with values having
fixed meaning as well as characteristics. Some of them are integer, floating point, character etc.
Usually, programming languages specify the range values for given data-type.
C Data Types are used to:

• Identify the type of a variable when it declared.


• Identify the type of the return value of a function.
• Identify the type of a parameter expected by a function.
ANSI C provides three types of data types:

1. Primary(Built-in) Data Types:void, int, char, double and float.

2. Derived Data Types:Array, References, and Pointers.

3. User Defined Data Types:Structure, Union, and Enumeration.

Primary Data Types:

Every C compiler supports five primary data types:


void -As the name suggests it holds no value and is generally used for specifyingthe type of
function or what it returns. If the function has a void type, it means that the function will not
return any value.
int-Used to denote an integer type.
Char-Used to denote a character type.
float, double-Used to denote a floating point
type.
int*,float*,char*- used to denote a pointer type.
Declaration of Primary Data Types with variable name:
After taking suitable variable names, they need to be assigned with a data type. This is how the
data types are used along with variables:
Example:
int age;
char letter;
float height, width;

Derived Data Types


C supports three derived data types:
DATATYPES DESCRIPTION
Arrays Arrays are sequences of data items having homogeneous
values. They have adjacent memory locations to store
values.
References Function pointers allow referencing functions with a
particular signature.

Pointers These are powerful C features which are used to access the
memory and deal with their addresses.

User Defined Data Types

C allows the feature called type definition which allows programmers to define their own

identifier that would represent an existing data type. There are three such types:

Data Types Description

Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. “struct” keyword is used to define a structure.
Union These allow storing various data types in the same memory location. Programmers
can define a union with different members but only a single member can contain
a value at given time.
Enum Enumeration is a special data type that consists of integral constants and each of them
is assigned with a specific name. “enum” keyword is used to define the enumerated data
type.

Example for Data Types and Variable Declarations in C


#include <stdio.h> int main()
{

int a = 4000; // positive integer data type float b = 5.2324; // float data type
char c = 'Z'; // char data type
long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type
int f = -185; // -ve integer data type
short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type
double i = 4.1234567890; // double float data type float j = -3.55; // float data type
}
Let's see the basic data types. Its size is given according to 32 bit architecture.
Data Types Memory Size Range

Char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

Short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

Int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to


2,147,483,647
signed long int 4 byte -2,147,483,648 to
2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte
double 8 byte
long double 10 byte

The storage representation and machine instructions differ from machine to Machine.
sizeof operator can use to get the exact size of a type or a variable on a particular platform.
Example: #include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int is: %d \n", sizeof(int));
printf("Storage size for char is: %d \n", sizeof(char)); return 0
}
CONSTANTS
A constant is a value or variable that can't be changed in the program, for example: 10,
20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc

2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor
C const keyword:
The const keyword is used to define constant in C programming.
Example:
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}

Output:
The value of PI is: 3.140000
If you try to change the value of PI, it will render compile time error.
#include<stdio.h>
int main(){
const float PI=3.14; PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object.
C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax: #define token value
Let's see an example of #define to define a constant.
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output:
3.140000
Backslash character constant:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as “Escape
Sequence”.
Example:
\t is used to give a tab
\n is used to give new line
Constants Meaning Constants Meaning
\a beep sound \n newline
\v vertical tab \\ backslash
\b backspace \r carriage return
\’ single quote \0 null
\f form feed \t horizontal tab
\” double quote

ENUMERATION CONSTANTS:
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte . It work like
the Integer. It is used for creating an user defined data type of integer. Using enum we can
create sequence of integer constant value.

Syntax: enum tagname{value1,value2,value3,….};

• In above syntax enum is a keyword. It is a user defined data type.

• In above syntax tagname is our own variable. tagname is any variable name.

• value1, value2, value3,are create set of enum values.

It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be start
from zero and next to generated value should be previous constant value one.

Example:

enum week{sun,mon,tue,wed,thu,fri,sat}; enum week today;

• In above code first line is create user defined data type called week.

• week variable have 7 value which is inside { } braces.


• today variable is declare as week type which can be initialize any data or value
among 7 (sun, mon,).

Example:

#include<stdio.h>
#include<conio.h>
enum abc{x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf(“sum: %d”,a);
getch();
}
Output:
Sum: 3
KEYWORDS:
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are
only 32 reserved words (keywords) in C language.
A list of 32 keywords in c language is given below:

auto break case Char Const Continue default do Double else


enum extern float For Goto If int long register return
short signed sizeof Static Struct Switch typedef union unsigned void
volatile while

OPERATORS :
Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Ternary or Conditional Operators
Arithmetic Operators:
Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A
hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0

Relational Operators:
Which can be used to check the Condition, it always return true or false. Lets suppose variable
hold 8 and B hold 3.

Logical Operator:

Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.

Operator Example (int A=8, B=3, C=-10) Result


&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True

Truth table of Logical Operator

C1 C2 C1&&C2 C1||C2 !C1 !C2


T T T T F F
T F F T F T
F T F T T F
F F F F T T

Assignment operators:
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.

Operator Example (int A=8, B=3) Result


+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
a=b Value of b will be assigned to a
Increment and Decrement Operator:
Increment Operators are used to increased the value of the variable by one and Decrement Operators
are used to decrease the value of the variable by one in C programs.
Both increment and decrement operator are used on a single operand or variable, so it is called as a
unary operator. Unary operators are having higher priority than the other operators it means unary operators
are executed before other operators.
Increment and decrement operators are cannot apply on constant.
The operators are ++, -- Type of Increment Operator
• pre-increment
• post-increment
pre-increment (++ variable):
In pre-increment first increment the value of variable and then used inside the expression (initialize
into another variable).
Syntax:
++variable;
post-increment (variable ++):
In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.
Syntax:
variable++;
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i; i=10;
x=++i;
printf(“Pre-increment\n”); Output:
printf(“x::%d”,x); Pre-increment x::10
printf(“i::%d”,i); i::10
i=10; Post-increment x::10
x=i++; i::11
printf(“Post-increment\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}
Type of Decrement Operator:
• pre-decrement
• post-decrement
Pre-decrement (-- variable):
In pre-decrement first decrement the value of variable and then used inside the expression (initialize
into another variable).
Syntax:
--variable;

Post-decrement (variable --):


In Post-decrement first value of variable is used in the expression (initialize into another variable)
and then decrement the value of variable.
Syntax:
variable--;
Example:
#include<stdio.h>
#include<conio.h> Output:
void main() Pre-decrement x::9
{ i::9
int x,i; i=10; Post-decrement x::10
x=--i; i::9
printf(“Pre-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i--;
printf(“Post-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}

Ternary Operator:
If any operator is used on three operands or variable is known as Ternary Operator. It can be
represented with ? : . It is also called as conditional operator
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
Syntax:

Expression 1? Expression 2: Expression 3;

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value Or variable or statement or any mathematical expression. If condition will be true expression-2 will
be execute otherwise expression-3 will be executed.
Conditional Operator flow diagram

Example:

find largest number among 3 numbers using ternary operator


#include<stdio.h>
void main()
{
int a,b,c,large; Output:
printf(“Enter any three numbers:”); Enter any three numbers: 12 67 98
scanf(“%d%d%d”,&a,&b,&c); The largest number is 98
large=a>b?(a>c?a:c):(b>c?b:c);
printf(“The largest number is:%d”,large);
}

Special Operators:
C supports some special operators

Operator Description

sizeof() Returns the size of an memory location.

& Returns the address of an memory location.

* Pointer to a variable.
Expression evaluation
In C language expression evaluation is mainly depends on priority and associativity.
Priority
This represents the evaluation of expression starts from "what" operator.
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Precedence of operators :
The precedence rule is used to determine the order of application of operators in evaluating sub
expressions. Each operator in C has a precedence associated with it. The operator with the highest
precedence is operated first.
Associativity of operators :
The associativity rule is applied when two or more operators are having same precedence in the sub
expression. An operator can be left-to-right associative or right-to-left associative.
Rules for evaluation of expression:
•First parenthesized sub expressions are evaluated first.
•If parentheses are nested, the evaluation begins with the innermost sub expression.
•The precedence rule is applied to determine the order of application of operators in evaluating
sub expressions.
•The associability rule is applied when two or more operators are having same precedence in the sub
expression.
EXPRESSION:

An expression is a sequence of operators and operands that specifies computation of a value.

For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +

Simple Expressions & Compound Expressions:

An expression that has only one operator is known as a simple expression. E.g: a+2

An expression that involves more than one operator is called a compound expression.

E.g: b=2+3*5.

IO STATEMENT:

The I/O functions are classified into two types:

• Formatted Functions

• Unformatted functions
FORMATTED INPUT FUNCTION:
SCANF():
It is used to get data in a specified format. It can accept different data types.
Syntax:
scanf(“Control String”, var1address, var2address, …);

EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
scanf(“%d %d”,&a,&b);
sum= a+b;
}

FORMATTED OUTPUT FUNCTION:


PRINTF():
The printf( ) function is used to print data of different data types on the console in a specified
format.
Syntax:
printf(“Control String”, var1, var2, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
printf(“enter two numbers:”); Enter two numbers: 5 4
scanf(“%d %d”,&a,&b); Sum is 9

sum= a+b;
printf(“sum is:%d”,sum);
}

UNFORMATTED INPUT FUNCTION:


• getchar()
• getch()
• getche()
• gets()
getchar():
This function reads a single character data from the standard input.
Syntax:
variable_name=getchar();

Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> j
void main()
{
Char ch;
ch=getchar();
Printf(“%c”,ch);
}
getch():
getch() accepts only a single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
Syntax:
variable_name = getch();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ Ch=a

Char ch;
ch=getch();
Printf(“ch=%c”,ch);
}
getche():
getche() also accepts only single character, but getche() displays the entered character in the
screen.
Syntax:
variable_name = getche();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ a
Ch=a
Char ch;
ch=getche();
Printf(“ch=%c”,ch);
}
gets():
This function is used for accepting any string through stdin (keyboard) until enter key
is pressed.
Syntax:
gets(variable_name);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Char ch[10]; OUTPUT:
cprogram
gets(ch); Ch=cprogram
Printf(“ch=%s”,ch);
getch();
}
UNFORMATTED OUTPUT FUNCTION:
• putchar()
• putch()
• puts()
putchar():
This function prints one character on the screen at a time.
Syntax :
putchar(variable name);
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> enter a character: j
j
void main()
{
Char ch;
printf(“enter a character:”);
ch=getchar();
putchar(ch);
getch();
}
putch():
putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Syntax:
putch(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Press any character:
char ch; Pressed character is: e
clrscr();
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is:”);
putch(ch);
getch();
}
puts():
This function prints the string or character array.
Syntax:
puts(variable_name);

Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Enter a string: cprogramming
char ch[20]; cprogramming
clrscr();
puts(“enter a string”);
gets(ch);
puts(ch);
}
ASSIGNMENT STATEMENT:
The assignment statement has the following form:
Syntax:
variable = expression/constant/variable;
Its purpose is saving the result of the expression to the right of the assignment operator to the
variable on the left. Here are some rules:
• If the type of the expression is identical to that of the variable, the result is saved in the variable.
• Otherwise, the result is converted to the type of the variable and saved there.
❖ If the type of the variable is integer while the type of the result is real, the fractional
part, including the decimal point, is removed making it an integer result.
❖ If the type of the variable is real while the type of the result is integer, then a decimal
point is appended to the integer making it a real number.
• Once the variable receives a new value, the original one disappears and is no more available.
Examples of assignment statements,
b = c ; /* b is assigned the value of c */
a = 9 ; /* a is assigned the value 9*/
b = c+5; /* b is assigned the value of expr c+5 */

• The expression on the right hand side of the assignment statement can be: An arithmetic
expression;
❖ A relational expression;
❖ A logical expression;
❖ A mixed expression.
For example,
int a;
float b,c ,avg, t;
avg = (b+c) / 2; /*arithmetic expression */
a = b && c; /*logical expression*/
a = (b+c) && (b<c); /* mixed expression*/
DECISION MAKING STATEMENTS:
Decision making statement is depending on the condition block need to be executed or not which
is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then statement
block will not be executed.
In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In C
language there are three types of decision making statement.
• if
• if-else
• switch
if Statement:
if-then is most basic statement of Decision making statement. It tells to program to execute a
certain part of code only if particular condition is true.
Syntax:

if(condition)
{
Statements executed if the condition is true
}
FLOWCHART:

Constructing the body of "if" statement is always optional, Create the body when we are having multiple
statements.
For a single statement, it is not required to specify the body.
If the body is not specified, then automatically condition part will be terminated with next semicolon ( ; ).
Example:
#include<stdio.h>
int main()
{
int num=0;
printf(“enter a number:”); OUTPUT:
scanf(“%d”,&num); Enter a number: 4
4 is even number
if(num%2==0)
{
printf(“%d is even number”,num);
}
return 0;
}
if-else statement:
In general it can be used to execute one block of statement among two blocks, in C language if
and else are the keyword in C.
Syntax:
if(expression)
{

else

Flowchar
t:
In the above syntax whenever condition is true all the if block statement are executed remaining
statement of the program by neglecting else block statement. If the condition is false else block statement
remaining statement of the program are executed by neglecting if block statements.
Example:
#include<stdio.h>
void main()
{
int age;
printf(“enter age:”)
scanf(“%d”,&age);
Output:
if(age>=18) Enter age: 18
Eligible to vote
{ Enter age: 17
Not eligible to vote
printf(“age:%d”,age);
printf(“eligible to vote” );
}
else
{
printf(“age:%d”,age);
printf(“not eligible to vote” );
}
Nested if:
When an if else statement is present inside the body of another “if” or “else” then this is called
nested if else.
Syntax of Nested if else statement:

if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Flowchart:

EXAMPLE:
#include<stdio.h>
void main() Output:
Enter age and salary: 55 55000
{ 65000
int age, salary;
printf(“enter age and salary”);
scanf(%d %d”, &age,&salary);
if(age>50)
{
if(salary<60000)
{
salary=salary+10000
;printf(“%d”,salary);
}
else
{
salary=
salary+5000;
printf(“%d”,salary);
}
}
else
{
salary=salary+1000;
printf(“%d”,salary);
}
printf(“end of program”);
getch();
}
Switch:
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax:
switch(expression/variable)
{
case value1:
statements;
break;//optional
case value2:
statements;
break;//optional
default:
statements;
break;//optional
}
Rules for apply switch:
1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch
Flowchart:

Example:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
// declaration of local variable op;
int op, n1, n2;
printf (" enter 2 number: ");
scanf(%d %d”,&n1,&n2);
printf (" \n 1 Addition \t \t 2 Subtraction \n 3 Multiplication \t 4 Division \n 5 Exit \n \n Please,
Make a choice ");
scanf ("%d", &op); // accepts a numeric input to choose the operation
switch (op)
{
case 1:
printf ("sum is :%d ",n1+n2);
break;
case 2:
printf ("difference is :%d ",n1-n2);
break;
case 3:
printf ("multiplication :%d ",n1*n2);
break;
case 4:
printf ("division :%d ",n1/n2);
break;
case 5:
printf ("exit”);
break;
default:
printf(“enter the number between 1 to 5:”);
}
}
LOOPING STATEMENTS
Sometimes it is necessary for the program to execute the statement several times, and C loops
execute a block of commands a specified number of times until a condition is met.
What is Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a task
tens of thousands of times. Every programming language has the feature to instruct to do such repetitive
tasks with the help of certain form of statements. The process of repeatedly executing a collection of
statement is called looping . The statements get executed many numbers of times based on the condition.
But if the condition is given in such a logic that the repetition continues any number of times with no
fixed condition to stop looping those statements, then this type of looping is called infinite looping.
C supports following types of loops:
• while loops
• do while loops
• for loops
while loops:
C while loops statement allows to repeatedly run the same block of code until a condition is met.
while loop is a most basic loop in C programming. while loop has one control condition, and executes as
long the condition is true.
The condition of the loop is tested before the body of the loop is executed, hence it is called an
entry-controlled loop.
Syntax:
while (condition)
{
statement(s); Increment statement;
}
Flowchart:
Flowchart:

Example: #include<stdio.h>void main ()


{
int i=1;
clrscr();
while(i<=10)
{
printf(“%d”,i);
i++;
} getch();
}

Output:
1 2 3 4 5 6 7 8 9 10

Do..while loops:
C do while loops are very similar to the while loops, but it always executes the code block at least
once and furthermore as long as the condition remains true. This is an exit- controlled loop.
Syntax:
do{
statement(s);
}while( condition );
Flowchart:
EXAMPLE:
#include<stdio.h>
void main ()
{ Output:
int i=1; 1 2 3 4 5 6 7 8 9 10

clrscr();
do
{
printf(“%d”,i);
i++;
} while(i<=10);
getch();
}
For loop:
C for loops is very similar to a while loops in that it continues to process a block of code until a
statement becomes false, and everything is defined in a single line. The for loop is also entry-controlled
loop.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Flowchart:
Example:
#include<stdio.h>
void main ()
{ Output:
int i; 1 2 3 4 5 6 7 8 9 10

clrscr();
for(i=1;i<=10;i++)
{
printf(“%d”,i);
getch();
}
PRE-PROCESSOR DIRECTIVES
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros. Preprocessor directives are
executed before compilation.

All preprocessor directives starts with hash #symbol.


Let's see a list of preprocessor directives.
• #include
• #define
• #undef
• #ifdef
• #ifndef
• #if
• #else
• #elif
• #endif
• #error
• #pragma
[Link] Preprocessor purposes syntax
directive
1 #include Used to paste code of given file into #include <filename>
current file. It is used include system- #include “filename”
defined and user-defined header files.
If included file is not found, compiler
renders error.
2 #define Used to define constant or #define PI 3.14
microsubstitution. It can use any
basic data type.
3 #undef Used to undefine the constant or #undef PI
macro defined by #define.
4 #ifdef Checks if macro is defined by #ifdef MACRO
#define. If yes, it executes the code //code
otherwise #else code is executed, if #endif
present.
5 #ifndef Checks if macro is defined by #ifndef MACRO
#define. If yes, it executes the code //code
otherwise #else code is executed, if #endif
present.
6 #if Evaluates the expression or #if expression
condition. If condition is true, it //code
executes the code otherwise #elseif #endif
or #else or #endif code is executed
7 #else Evaluates the expression or condition #if expression
if condition of #if is false. It can be //if code
used with #if, #elif, #ifdef and #else
#ifndef directives. //else code
#endif
8 #error Indicates error. The compiler gives #error First include
fatal error if #error directive is found then compile
and skips further compilation
process.
9 #pragma Used to provide additional #pragma token
information to the compiler. The
#pragma directive is used
by the compiler to offer machine or
operating-system feature.
COMPILATION PROCESS:
C is a high level language and it needs a compiler to convert it into an executable code so that the
program can be run on our machine.
How do we compile and run a C program?
Below are the steps we use on an Ubuntu machine with gcc compiler.

• We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
compile it using below command.
$ gcc –Wall filename.c –o filename
The option -Wall enables all compiler’s warning messages. This option is recommended to generate
bettercode. The option -o is used to specify output file name. If we do not use this option, then an output
file with name [Link] is generated.
After compilation executable is generated and we run the generated executable using below
command.
$ ./filename
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C program to
become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along with the
executable.
$gcc –Wall –save-temps filename.c –o filename
The following screenshot shows all generated intermediate files.
Let us one by one see what these intermediate files contain
Pre-processing:
This is the first phase through which source code is passed. This phase include:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside
filename.i:using $vi filename.i
In the above output, source file is filled with lots and lots of info, but at the end our code is
preserved.
Analysis:
• printf contains now a + b rather than add(a, b) that’s because macros have expanded.
• Comments are stripped off.

• #include<stdio.h> is missing instead we see lots of code. So header files has been
expanded andincluded in our source file.
Compiling:
The next step is to compile filename.i and produce an; intermediate compiled output file
filename.s.
This file is in assembly level instructions. Let’s see through this file using $vi filename.s
Assembly:
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing code is converted into
machine language, the function calls like printf() are not resolved. Let’s view this file using $vi
filename.o
Linking:
This is the final phase in which all the linking of function calls with their definitions are
done. Linkerknows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program which is
required whenthe program starts and ends.
For example, there is a code which is required for setting up the environment like passing
commandline arguments. This task can be easily verified by using $size filename.o and $size
filename.
Through these commands, we know that how output file increases from an object file to
an executable file. This is because of the extra code that linker adds with our program.
UNIT II
ARRAYS AND STRINGS
Introduction to Arrays: Declaration, Initialization – One dimensional array –
Two dimensional arrays - String operations: length, compare, concatenate, copy –
Selection sort, linear and binary search.

INTRODUCTION TO ARRAYS: DECLARATION,INITIALIZATION:ONE

DIMENSIONAL ARRAYS:
Array in C language is a collection or group of elements (data). All the elements of c
array are homogeneous (similar). It has contiguous memory location.
C array is beneficial if you have to store similar elements. Suppose you have to store
marks of 50 students, one way to do this is allotting 50 variables.
So it will be typical and hard to manage.
For example we cannot access the value of these variables with only 1 or 2 lines of
code.
Another way to do this is array. By using array, we can access the elements easily. Only
few lines of code is required to access the elements of array.

Advantage of C Array:
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array:
1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't
exceed the limit. So, it doesn't grow the size dynamically like Linked List.

Declaration of C Array:
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[array_size];

Now, let us see the example to declare array.


int marks[5];
Here, int is the datatype, marks is the array_name and 5 is the array_size.

How to access element of an array in C:


You can use array subscript (or index) to access any element stored in array. Subscript
starts with 0, which means arr[0] represents the first element in the array arr.
In general arr[n-1] can be used to access nth element of an array. where n is any integer
number.

Initialization of C Array:
A simple way to initialize array is by index. Notice that array index starts from 0 and
ends with [SIZE - 1].
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Example:
#include<stdio.h>
int main()
{ Output:
int i=0; 80
int marks[5];//declaration of array 60
marks[0]=80;//initialization of array 70
marks[1]=60; 85
marks[2]=70; 75
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop return 0;
}
C Array: Declaration with Initialization:
We can initialize the c array at the time of declaration. Let's see the code. int
marks[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as the
following code
.
Example: int marks[]={20,30,40,50,60};
Programs:
#include<stdio.h> Output:
int main() 20
{ 30
int i=0; 40
int marks[5]={20,30,40,50,60};//declaration and initialization of array 50
//traversal of array 60
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
return 0;
}
TWO DIMENSIONAL ARRAYS (2 D arrays):
The two dimensional array in C language is represented in the form of rows and
columns, also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
Declaration of two dimensional Array in C:
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[size1][size2];

A simple example to declare two dimensional array is given below.


Example: int twodimen[4][3];

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C:
A way to initialize the two dimensional array at the time of declaration is given
below.
Example: int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Programs:

#include<stdio.h> Output:
int main() arr[0][0] = 1
{ arr[0][1] = 2
int i=0,j=0; arr[0][2] = 3
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[1][0] = 2
//traversing 2D array arr[1][1] = 3
for(i=0;i<4;i++) arr[1][2] = 4
{ arr[2][0] = 3
for(j=0;j<3;j++) arr[2][1] = 4
{ arr[2][2] = 5
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[3][0] = 4
}//end of j arr[3][1] = 5
}//end of i return 0; arr[3][2] = 6
}

STRING OPERATION:
What is meant by String?
String in C language is an array of characters that is terminated by \0 (null character).
There are two ways to declare string in c language.

1. By char array
2. By string literal

Let's see the example of declaring string by char array in C language.


char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As you know well, array index starts from 0, so it will be represented as in the figure
given below.
While declaring string, size is not mandatory. So you can write the above code as
given below:

char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
You can also define string by string literal in C language.
For example: char ch[]="javatpoint";
In such case, '\0' will be appended at the end of string by the compiler.

Difference between char array and string literal:


The only difference is that string literal cannot be changed whereas string declared by
char array can be changed.
Programs:
Let's see a simple example to declare and print string. The '%s' is used to print string
in c language.
#include<stdio.h> Output:
#include <string.h> Char Array Value is: javatpoint
int main() String Literal Value is: javatpoint
{
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[11]="javatpoint";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}

1. String operations: length-strlen()


The strlen() function returns the length of the given string. It doesn't count null
character '\0'.
Example:
#include<stdio.h>
#include <string.h> Output:
int main() Length of string is: 10
{
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}

2. String operations: compare-strcmp():


The strcmp(first_string, second_string) function compares two string and returns 0 if
both strings are equal.
Here, we are using gets() function which reads string from the console.
Programs:
#include<stdio.h>
#include <string.h> Output:
int main() Enter 1st string: hello
{ Enter 2nd string: hello
char str1[20],str2[20]; Strings are equal
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if( (strcmp(str1,str2)==0) printf("Strings
are equal");
else
printf("Strings are not equal");
return 0;
}

3. String operations: concatenate-strcat():


The strcat(first_string, second_string) function concatenates two strings and result is
returned to first_string.
Programs:
#include<stdio.h> Output:
#include <string.h> Value of first string is: helloc
int main()
{
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);return
0;
}

4. String operations: copy-strcpy():


The strcpy(destination, source) function copies the source string in destination
Programs:
#include<stdio.h>
#include <string.h> Output:
int main() Value of second string is: javatpoint
{
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
5. String operations:Reverse - strrev():

The strrev(string) function returns reverse of the given string. Let's see a simple example
of strrev() function.
Programs:
#include<stdio.h>
#include <string.h>int
main() Output:
{ Enter string: javatpoint
char str[20]; String is: javatpoint
printf("Enter string: "); Reverse String is: tnioptavaj
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}

6. String operation: lower- strlwr():


The strlwr(string) function returns string characters in lowercase. Let's see asimple
example of strlwr() function.
Programs:
#include<stdio.h> Output:
#include <string.h>int Enter string: JAVATpoint
main() String is: JAVATpoint
{ Lower String is: javatpoint
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
7. String operation:upper-strupr():
The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.
Programs:
#include<stdio.h> Output:
#include <string.h> Enter string: javatpoint
int main() String is: javatpoint
{ Upper String is: JAVATPOINT
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Sample Programs:
1. Program to calculate the average marks of the class
#include<stdio.h>void
main()
{ int m[5],i,sum=0,n;float Output:
avg; Enter number of students
printf(“enter number of students \n”); 5
scanf(“%d”,&n); Enter marks of students
printf(“enter marks of students \n”); 55
for(i=0;i <n;i++) 60
sum=sum+m[i]; avg=float(sum)/n; 78
printf(“average of:%f”,avg); 85
} 90
Average of: 73.6
2. Addition of two numbers in array:
#include <stdio.h>
void main()
{
int a[10], b[10], c[10], n, i;
printf("Enter the number of elements:\t");
scanf("%d", &n);
printf("Enter %d elements for array 1:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter %d elements for array 2:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &b[i]);
for (i = 0; i < n; i++)
c[i] = a[i] + b[i];
printf("Sum of two array elements are:\n");
for (i = 0; i < n; i++)
printf("%d\n", c[i]);
}
Output:
Enter the number of elements: 5Enter 5
elements for array 1:
93
37
71
03
17
Enter 5 elements for array 2:
29
84
28
75
63
Sum of two array elements are:122
121
99
78
80

3. Subtraction of two number:


#include < stdio.h >
int main()
{
int m, n, c, d, first[10][10], second[10][10], difference[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", & m, & n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++) scanf("%d", & first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++) scanf("%d", & second[c][d]);
printf("Difference of entered matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
difference[c][d] = first[c][d] - second[c][d];
printf("%d\t", difference[c][d]);
}
printf("\n");
}
return 0;
}
4. Multiplication of two numbers in array:
#include<stdio.h>
#include<stdlib.h> int
main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++) Output:
{ enter the number of row=3
printf("%d\t",mul[i][j]); enter the number of column=3
} enter the first matrix element=
printf("\n"); 111
} 222
return 0; 333
} enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18
UNIT III FUNCTIONS AND POINTERS

Introduction to functions: Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion – Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using recursive functions – Pointers – Pointer
operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting
of names – Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two
numbers and changing the value of a variable using pass by reference.

FUNCTIONS

Definition

C enables its programmers to break up a program into segments commonly known as functions

Every function in the program is supposed to perform a well-defined task. Therefore, the programcode of
one function is completely insulated from the other functions.

main() calls a function named func1(). Therefore, main() is known as the calling function
andfunc1() is known as the called function.
Need For Functions:
Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in any program rather than
writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by function calls.

Terminologies In Functions
• A function f that uses another function g is known as the calling function, and g is known as the
called function.
• The inputs that a function takes are known as arguments.
• When a called function returns some result back to the calling function, it is said to
returnthat result.
• The calling function may or may not pass parameters to the called function. If the
called function accepts arguments, the calling function will pass parameters, else not.
➢ Function declaration is a declaration statement that identifies a function’s name, a
list ofarguments that it accepts, and the type of data it returns.
➢ Function definition consists of a function header that identifies the function, followed
by the bodyof the function containing the executable code for that function.
Function Declaration
The general format for declaring a function that accepts arguments and returns a value as result
can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..);

o function_name - is a valid name for the function. Naming a function follows the
same rules that are followed while naming variables. A function should have a
meaningful name that must specify the task that the function will perform.
o return_data_type - the data type of the value that will be returned to the calling
function asa result of the processing performed by the called function.
o (data_type variable1, data_type variable2, ...) - is a list of variables of specified
data types. These variables are passed from the calling function to the called
function. They are also known as arguments or parameters that the called
function accepts to perform its task.
Function Definition
When a function is defined, space is allocated for that function in the memory. A functiondefinition
comprises of two parts:
• Function header
• Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);
}

return_data_type function_name(data_type variable1, data_type variable2,...) is known as the


function header, the rest of the portion comprising of program statements within the curly brackets
{ } is thefunction body which contains the code to perform the specific task.
➢ The number of arguments and the order of arguments in the function header must
be the same as thatgiven in the function declaration statement.
➢ The function header is same as the function declaration. The only difference
between the two is thata function header is not followed by a semi-colon.

Function Call
The function call statement invokes the function. When a function is invoked, the compiler jumps to the
called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function. A function call statement has the
following syntax:
function_name(variable1, variable2, ...);

If the return type of the function is not void, then the value returned by the
called functionmay be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Eg:// program to find whether a number is even or odd using functions.
#include <stdio.h>
int evenodd(int); //FUNCTION DECLARATION
int main()
{
int num, flag;
printf("\n Enter the number : ");
scanf("%d",&num);
flag = evenodd(num); //FUNCTION CALL
if (flag == 1)
printf("\n %d is EVEN", num);
else
printf("\n %d is ODD", num);
return 0;
}
int evenodd(int a) // FUNCTION HEADER
{

if(a%2 == 0)
return 1;
else
return 0;
}
Output:
Enter the number : 7878 is EVEN
PASSING PARAMETERS TO FUNCTIONS

There are two ways in which arguments or parameters can be passed to the called function.
1. Call by value - The values of the variables are passed by the calling function to
the calledfunction.
2. Call by reference - The addresses of the variables are passed by the calling
function to thecalled function.
1. Call by Value
• In call by value method, the value of the actual parameters is copied into the formal
parameters.

• In call by value method, we cannot modify the value of the actual parameter by
the formalparameter.
• In call by value, different memory is allocated for actual and formal parameters.

• The actual parameter is the argument which is used in the function call whereas formal
parameter isthe argument which is used in the function definition.
Eg://Program for call by value
#include<stdio.h>
int main()
{
int x,y;
void swap(int,int); printf("Enter two
numbers:");scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping: x = %d\ty =
%d",x,y);
swap(x,y);
printf("\n\nAfter Swapping: x = %d\ty = %d",x,y);
}

void swap(int a, int b)


{
a=a+b;
b=a-b;
a=a-b;
printf("\n\nIn swap function: x = %d\ty = %d\n\n",a,b);
}

Output:

Enter two numbers: 2 3


Before Swapping: x=2 y=3
In Swap function: x=3 y=2
After Swapping : x=2 y=3

Pros and cons


• The biggest advantage of using the call-by-value technique is that arguments can be passed as
variables, literals, or expressions.

1. Its main drawback is that copying data consumes additional storage space. In addition, it can take
alot of time to copy, thereby resulting in performance penalty, especially if the function is called
many times.
Call By Reference:
• The method of passing arguments by address or reference is also known as call by address or call
by reference. Here, the addresses of the actual arguments are passed to the formal parameters of
the function.
• If the arguments are passed by reference, changes in the formal parameters also make changes on
actual parameters.

Eg//Program for Call by reference

#include<stdio.h>
int main()
{
int x ,y;
void swap (int*,int*);
printf(“enter the two numbers”);
scanf(“%d%d”,&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\ty = %d",x,y);
swap(&x,&y);
printf("\n\nAfter Swapping:\n\nx = %d\ty = %d\n\n",x,y);
}
void swap(int *a, int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
printf("\n\nIn swap function: x = %d\ty = %d\n\n",a,b);
}

Output:

Enter two numbers: 2 3


Before Swapping: x=2 y=3
In Swap function: x=3 y=2
After Swapping : x=3 y=2
Advantages
1. Since arguments are not copied into the new variables, it provides greater time andspace
efficiency.
2. The function can change the value of the argument and the change is reflected in the calling
function.

3.A function can return only one value. In case we need to return multiple values, we can pass those
arguments by reference, so that the modified values are visible in the calling function.

Disadvantage:
1. if inadvertent changes are caused to variables in called function then these changes would
bereflected in calling function as original values would have been overwritten.

RECURSIVE FUNCTION

Function calls itself again and again is called recursion.


➢ A recursive function is defined as a function that calls itself to solve a smaller version of its taskuntil a final
call is made which does not require a call to itself.
Every recursive solution has two major cases. They are,
➢ Base case - in which the problem is simple enough to be solved directly without making any further
calls to the same function.
➢ Recursive case - in which first the problem at hand is divided into simpler sub-parts. Second, the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.

Eg:Write a program to calculate the factorial of a given number.


#include <stdio.h>
int Fact(int); // FUNCTION DECLARATION
int main()
{
int num, val;
printf("\n Enter the number: ");
scanf("%d", &num);
val = Fact(num);
printf("\n Factorial of %d = %d", num, val);
}
int Fact(int n)
{
if(n==1)
return;
else
return (n * Fact(n–1));

Output:

Enter the number : 5


Factorial of 5 = 120

Types of Recursion
1. Direct Recursion
A function is said to be directly recursive if it explicitly calls itself.

2. Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it

3. Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be performed when
the recursive function returns to its caller.
4. Non Tail Recursion:
A recursive function is said to be non tail recursive if operations are pending to be performed when
the recursive function returns to its caller.

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

Advantages
➢ Recursive solutions often tend to be shorter and simpler than non-recursive ones.
➢ Code is clearer and easier to use.
➢ Recursion works similar to the original formula to solve a problem.
➢ Recursion follows a divide and conquer technique to solve problems.
disadvantages
➢ Recursion is implemented using system stack. If the stack space on the system is limited,
recursion to a deeper level will be difficult to implement.

➢ Aborting a recursive program in midstream can be a very slow process.


➢ Using a recursive function takes more memory and time to execute as compared to itsnon
recursive counter part.
➢ It is difficult to find bugs, particularly while using global variables.
PROGRAM TO DO BINARY SEARCH USING RECURSION

#include<stdio.h>
#define size 10
int binsearch(int[], int, int, int);
int main()
{
int num, i, key, position;
int low, high, list[size];
printf("\nEnter the total number of elements");
scanf("%d", &num);
printf("\nEnter the elements of list :");
for (i = 0; i < num; i++)
{
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("\nEnter element to be searched : ");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1)
{
printf("\nNumber present at %d", (position + 1));
}
else
printf("\n The number is not present in the list");
return (0);
}

// Binary Search function


int binsearch(int a[], int x, int low, int high)
{
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid])

{
return (mid);
}
else if (x < a[mid])

{
binsearch(a, x, low, mid - 1);
}
else
{

binsearch(a, x, mid + 1, high);

}
Output:
Enter the total number of elements : 5
Enter the elements of list : 11 22 33 44 55

Enter element to be searched : 33


Number present at 3

POINTERS
A pointer is a variable that contains the memory location of another variable.

Declaring Pointer Variables

The general syntax of declaring pointer variables can be given as below

data type *ptr name;


Here, data type is the data type of the value that the pointer will point to. For example,
Ex:
int x =10
int *ptr;
ptr=&x

ex: program using pointer

#include<stdio.h>
int main()
{
int num,*pnum;
pnum=&num;
printf(“enter the number”);
scanf(“%d”,&num);
printf(“the no that was entered is %d”,*pnum);
return 0;
}
Output
Enter the number : 10
The number that was entered is : 10

The Pointer Operators:


There are two pointer operators :
1. value at address operator ( * )
2. address of operator ( & )
Value at address operator ( * )
The * is a unary operator. It gives the value stored at a particular address. The ‘value at address’
operator is also called ‘indirection’ operator.
q = *m;
if m contains the memory address of the variable count, then preceding assignment statement
canplaces the value of count into q.
Address of operator ( & )
The & is a unary operator that returns the memory address of its operand
.m = & count;
The preceding assignment statement can be “The memory address of the variable count is places into m”.

Output of the program :


Address of a = 12345
Address of a = 12345
Address of b = 12345
Value of b = 12345
Value of a = 5
Value of a = 5
Value of a = 5

Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, and –
Valid Pointer Arithmetic Invalid Pointer Arithmetic
Operations Operations
✓ Adding a number to pointer. ➢ Addition of two pointers.
✓ Subtracting a number form a ➢ Division of two pointers.
pointer.
✓ Incrementing a pointer.
✓ Decrementing a pointer.
✓ Subtracting two pointers.
#include <stdio.h>int main()
{
int m = 5, n = 10, q = 0;
int *p1;
int *p2;
int *p3;
OUTPUT: p1
p1 = &m; //printing the address of m
= 2680016
p2 = &n; //printing the address of n
p2 = 2680012
printf("p1 = %d\n", p1);
*p1+*p2 = 15
printf("p2 = %d\n", p2);
p1-p2 = 1
q = *p1+*p2;
p1++ = 2680020
printf("*p1+*p2 = %d\n", q);//point 1
p2-- = 2680008
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
printf("p2-- = %d\n", p2); //point 4
//Below line will give ERROR
printf("p1+p2 = %d\n", p1+p2); //point 5return 0;
}

NULL POINTER
null pointer which is a special pointer value and does not point to any value. This means that a
nullpointer does not point to any valid memory address.
int *ptr = NULL;
The null pointer is used in three ways,
[Link] stop indirection in a recursive data structure.
[Link] an error value
[Link] a sentinel value

#include <stdio.h>
int main()
{
int *ptr = NULL;
printf("The value of ptr is %u",ptr);

return 0;
}

Output :
The value of ptr is 0

POINTERS AND ARRAYS :

Syntax: int *ptr;


ptr = &arr[0];

Here, ptr is made to point to the first element of the array.

Eg:// program to display an array of given numbers.

#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int *ptr1, *ptr2;
ptr1 = arr;
ptr2 = &arr[8];
Output
while(ptr1<=ptr2) 1234567
{
printf("%d", *ptr1);
ptr1++;
}
return 0;
}

ARRAY OF POINTERS:

An array of pointers can be declared


as.
datatype *array_name[size];

Eg:int *ptr[10];

The above statement declares an array of 10 pointers where each of the pointer points to aninteger variable.
Example 2://Program on Array of Pointers
int main()
{
int *ptr[10];
int p = 1, q = 2, r = 3, s = 4, t = 5;
ptr[0] = &p;
ptr[1] = &q; OUTPUT:4

ptr[2] = &r;
ptr[3] = &s;
ptr[4] = &t;
printf("\n %d", *ptr[3]);
return 0;
}

Example 2://Program on Array of Pointers


int main()
{
int arr1[]={1,2,3,4,5};
int arr2[]={0,2,4,6,8};
Output
int arr3[]={1,3,5,7,9};
101
int *parr[3] = {arr1, arr2, arr3};
int i;
for(i = 0;i<3;i++)
printf(«%d», *parr[i]);
return 0;
}
Applications of Pointers
➢ Pointers are used to pass information back and forth between functions.
➢ Pointers enable the programmers to return multiple data items from a function via function
arguments.
➢ Pointers provide an alternate way to access the individual elements of an array.
➢ Pointers are used to pass arrays and strings as function arguments.
➢ Pointers are used to create complex data structures, such as trees, linked lists, linked
stacks,linkedqueues, and graphs.

PROGRAM TO SORT NAMES


#include<stdio.h>
#include<string.h>
int main()
{
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);
puts("Enter Strings one by one: ");
for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++)
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted Strings:");
for(i=0;i<=count;i++)
puts(str[i]);
return 0;
}

1. Write a program to calculate the GCD of two numbers using recursive functions.#include
<stdio.h>
int GCD(int, int);
int main()
{
int num1, num2, res;
printf("\n Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
res = GCD(num1, num2);
printf("\n GCD of %d and %d = %d", num1, num2, res);
return 0;
}
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}
Output
Enter the two numbers : 8 12
GCD of 8 and 12 = 4

2. Write a program to print the Fibonacci series using recursion.


#include <stdio.h>int
Fibonacci(int); int
main()
{
int n, i = 0, res;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("Fibonacci series\n");
for(i = 0; i < n; i++ )
{
res = Fibonacci(i);Stacks 247 printf("%d\t",res);
}
return 0;
}

int Fibonacci(int n)
{ output:
if ( n == 0 ) enter the terms of Fibonacci series 01123
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n–1) + Fibonacci(n–2) ))

}
3. Write a program to add two integers using pointers and functions.
#include <stdio.h>
void sum (int*, int*, int*);int
main()
{
int num1, num2, total;
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
sum(&num1, &num2, &total);
printf("\n Total = %d", total);
return 0;
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}
Output
Enter the first number : 23
Enter the second number : 34
Total = 57
UNIT 4 STRUCTURES AND UNION

Structure - Nested structures – Pointer and Structures – Array of structures – Example


Program using structures and pointers – Self referential structures – Dynamic memory
allocation - Singly linked list – typedef-union storage classes and visibility

STRUCTURES:
• A structure is a user-defined data type that can store related information together. A
structure is acollection of variables under a single name.
• the major difference between a structure and an array is that, an array contains
related informationof the same data type.
• The variables within a structure are of different data types and each has a name that is
used to selectit from the structure.
Features of structures
• Structures can store more than one different data type data under a
single variable.
• Structure elements are stored in successive memory locations.
• Nesting of structure is possible.
• Structure elements can be passed as argument to the function.
Syntax:
//Structure creation
struct structurename
{
Datatype1
variablename;Datatype2
variablename;
.
.
};

//Object Creation

struct structname objname;


• It is possible to create structure pointers.
Example ://Program to display a point

#include<stdio.h>struct point

int x,y;

};

void main()
Output:
{ (2,3)

struct point p1={2,3};

printf(“(%d,%d)”,p1.x,p1.y);

Initialization of structures:

Syntax:
struct struct_name

datatype membername1;

datatype membername2;

datatype membername3;

}sturct_var={constant1,constant2,constant3,….};

Example:
struct student
{

int rno;

char name[20];

char course[20];

float fees;

}stud1={01,”Rahul”,”BCA”,45000};

or

struct student stud2={02,”Rajiv”};

Fig. illustrates how the values will be assigned to individual fields of the structure

Accessing the members of a structure:


A structure member variable is generally accessed using a ‘.’(dot) operator.
Syntax:
struct_var.membername;

Example:

[Link]=01; [Link]=”Rahul”;[Link]=”BCA”;[Link]=45000;

Receiving user input:

scanf(“%d”,&[Link]);

scanf(“%s”,[Link]);

Displaying output:

printf(“Roll No:%d”,[Link]);printf(“Name:%s”,[Link]);

TYPEDEF DECLARATION:
The typedef keyword enables the programmer to create a new data type name
from an existing data
type.
Syntax:
typedef existingdatatype newdatatype;
Example 1:

typedef int INTEGER;INTEGER number=5;

Example 2:

typedef struct student

int rno;
char name[20]; char course[20];float fees;

};

student s1; //instead of struct student s1;

COPYING AND COMPARING STRUCTURES:

Values of structure variables

Copy

We can assign a structure to another structure of the


same [Link] student
stud1={01,”Rahul”,”BCA”,45000};
struct student stud2=stud1;

Compare:

if([Link]==[Link])
printf(“Fees of s2 and s1 are equal”);
STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES) :
• Structures can be placed within another structures ie., a structure may contain another
structure as itsmember. A structure that contains another structure as its member is
called as nested structures.

Example:write a c program to read and display information of students using


nested structure
#include<stdio.h>
int main()
{
int day;
int month;
int year;
};struct student
{
int rollno;
char no[100];
float fees;
struct DOB date;
};
struct student stud1;
clrscr();
printf(“enter the roll no”);
scanf(“%d”,&stud1.roll_no);
printf(“enter the name”);
scanf(“%s”,[Link]);
printf(“enter the fees”);
scanf(“%f “,&[Link]);
printf(“enter the DOB”);
printf(“%d%d%d”,&[Link],&[Link],&[Link]);
Printf(“\n ******students details******”);
Printf(“\n ROLL No=%d”,stud1.roll_no);
Printf(“\n NAME=%s”,[Link]);
Printf(“\n FEES = %f”,[Link]);
Printf(“\n DOB =%d-%d-%d”,[Link],[Link],[Link]);
getch();
return 0;
}
Output:
Enter the roll no 01
Enter the name arun
Enter the fees 45000
Enter the DOB 25-09-1991

ARRAYS OF STRUCTURES.
In the above examples, we have seen how to declare a structure and assign
values to its datamembers.
PASSING STRUCTURES THROUGH POINTERS:
• Passing large structures to functions using the call by value method is very inefficient.
Therefore, it is preferred to pass structures through pointers. It is possible to create a
pointer to almost any type in C, including the user-defined types.

• It is extremely common to create pointers to structures. A pointer to a structure is a


variable that holds the address of a structure. The syntax to declare a pointer to a structure
can be given as,

struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}*ptr;

Or

struct struct_name *ptr;


• For our student structure, we can declare a pointer variable by writing
• struct student *ptr_stud, stud;

• The next thing to do is to assign the address of stud to the pointer using the address
operator(&), as we would do in case of any other pointer. So to assign the address,
we will write
• ptr_stud = &stud;
• To access the members of a structure, we can write
(*ptr_stud).roll_no;
Write a program to initialize the members of a structure by using a pointer to thestructure.
#include<stdio.h>

#include <conio.h>

struct student
{
int r_no; Output
char name[20]; Enter the details of the student:

char course[20]; Enter the RollNumber = 02

Enter the Name = Aditya


int fees;
Enter the Course = MCA
};
Enter the Fees = 60000
int main()
DETAILS OF THE STUDENT
{
struct student stud1, *ptr_stud1;
clrscr();
ptr_stud1 = &stud1;
printf("\n Enter the details of the student : "
)
printf("\n Enter the Roll Number ="); ;
scanf("%d", &ptr_stud1 -> r_no);
printf("\n Enter the Name = );
gets(ptr_stud1 -> name);

printf("\n Enter the Course = ");


gets(ptr_stud1 -> course);
printf("\n Enter the Fees = ");
scanf("%d", &ptr_stud1 -> fees);
printf("\n DETAILS OF THE STUDENT");
printf("\n ROLL NUMBER = %d", ptr_stud1 –> r_no);
printf("\n NAME = %s", ptr_stud1 –> name);
printf("\n COURSE = %s", ptr_stud1 –> course);
printf("\n FEES = %d", ptr_stud1 –> fees);
return 0;
}

SELF-REFERENTIAL STRUCTURES
Self-referential structures are those structures that contain a reference to the data
of its same type. That is, a self-referential structure, in addition to other data, contains a pointer to
a data that is of the sametype as that of the structure. For example, consider the structure node given
below.
struct node
{
int val;
struct node *next;
};
Here, the structure node will contain two types of data: an integer val and a pointer
next. You must be wondering why we need such a structure. Actually, self-referential
structure is the foundation of other data structures. We will be using them throughout this
book and their purpose will be clearer to you when we discuss linked lists, trees, and graphs.

LINKED LISTS
Array is a linear collection of data elements in which the elements are stored in
consecutive memorylocations. Its size is fixed.
A linked list does not store its elements in consecutive memory locations and the user can
add anynumber of elements to it.
However, unlike an array, a linked list does not allow random access of data. Elements in a
linked listcan be accessed only in a sequential manner. But like an array, insertions and deletions
can be done at any point in the list in a constant time.
A linked list can be perceived as a train or a sequence of nodes in which each node contains one
ormore data fields and a pointer to the next node

Start

Simply linked list

Since in a linked list, every node contains a pointer to another node which is of the same type, it is
also called a self-referential data type.

START - stores the address of the first node in the list


.next - stores the address of its succeeding node.

Declaration of node:
struct node
{
int data;
struct node *next;
}

Memory Allocation and De-allocation for a Linked List


The Function malloc is most commonly used to attempt to ``grab'' a continuous portion of
memory. It is defined by:
void *malloc(size_t
number_of_bytes);
it is usual to use the sizeof() function to specify the number of bytes:

Struct node *new_node;


new_node = (struct node*)malloc(sizeof(struct node));
SINGLY LINKED Lists
A singly linked list is the simplest type of linked list in which every node contains some data
and a pointer to the next node of the same data type. By saying that the node contains a pointer to
the next node,we mean that the node stores the address of the next node in sequence.
A singly linked list allows traversal of data only in one way. Figure 6.7 shows a singly linked
list.

START

Singly linked list

Inserting a New Node in a Linked List


In this section, we will see how a new node is added into an already
existing linked list. We willtake four cases and then see how insertion is done in
each case.
Case 1: The new node is
inserted at the beginning.
Case 2: The new node is
inserted at the end.
Case 3: The new node is inserted after a given node

Case 1: Inserting a Node at the Beginning of a Linked List

.
struct node *insert_beg(struct node *start)
{
struct node *new_node;int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = start;
start = new_node;
return start;
}

Case 2: Inserting a Node at the End of a Linked List

struct node *insert_end(struct node *start)


{
struct node *ptr, *new_node;
int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = NULL;
ptr = start;
while(ptr -> next != NULL)ptr = ptr -> next;
ptr -> next = new_node;
return start;
}

case 3: Inserting a Node After a Given Node in a Linked List


struct node *insert_after(struct node *start)
{
struct node *new_node, *ptr, *preptr;
int num, val;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
printf(“\n Enter the value after which the data has to be inserted : “);
scanf(“%d”, &val);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
ptr = start;
preptr = ptr;
while(preptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next=new_node;
new_node -> next = ptr;
return start;
}
Deleting a Node from a Linked List:
Case 1: The first node is deleted.
Case 2: The last node is deleted.
Case 3: The node equal to a given value is deleted.

Case 1: Deleting the First Node from a Linked List

struct node *delete_beg(struct node *start)


{
struct node *ptr;ptr = start;
start = start -> next;free(ptr);
return start;
}

Case 2: Deleting the Last Node from a Linked List

struct node *delete_end(struct node *start)


{
struct node *ptr, *preptr;ptr = start;
while(ptr -> next != NULL)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = NULL;free(ptr);
return start;
}
Case 3: Deleting the Node equal to a Given Value in a Linked List

struct node *delete_node(struct node *start)


{
struct node *ptr, *preptr;
int val;
printf(“\n Enter the value of the node which has to be deleted : “);
scanf(“%d”, &val);
ptr = start;
if(ptr -> data == val)
{
start = delete_beg(start);
return start;
}
else
{

while(ptr -> data != val)


{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = ptr -> next;
free(ptr);
return start;
}

Programming Example
Declare a structure to store information of a particular date.
struct date
{
int day;
int month;
int year;
};

Declare a structure to create an inventory record.


struct inventory
{
char prod_name[20];
float price;
int stock;
};

Write a program, using an array of pointers to a structure, to read and display the data of
students.
#include <stdio.h>
#include <conio.h>

#include <alloc.h>

struct student

int r_no;

char name[20];

char course[20];

int fees;

};

struct student *ptr_stud[10];

int main()

int i, n;

printf("\n Enter the number of students : ");

scanf("%d", &n);
for(i=0;i<n;i++)
{
ptr_stud[i] = (struct student *)malloc(sizeof(struct student));
printf("\nEnter the data for student %d ", i+1);
printf("\n ROLL NO.: ");
scanf("%d", &ptr_stud[i]–>r_no);
printf("\n NAME: ");
gets(ptr_stud[i]->name);
printf(“\ncourse”);
gets(ptr->stud[i]->course);
printf(“/n FEES”);
scanf(“%d”,&ptr_stud[i]->fees);
}
printf(“\n DETAILS OF STUDENT”);
for(i=0;i<n;i++)
{
printf((“\n ROLL NO=%d”,[Link][i]->[Link]);
printf(“\n NAME=%s,ptr->stud[i]->name);
printf(“\n COURSE=%s,ptr->stud[i]->course);
printf(“n FEES=%d”,ptr->stud[i]->fees);
}
return 0;
}

Output
Enter the number ofstudents : 1
Enter the data forstudent 1
ROLL NO.: 01
NAME: Rahul
COURSE:BCA
FEES: 45000
DETAILS OF STUDENT
SROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000

Write a program that passes a pointer to a structure to a function.


#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct student
{
int r_no;
char name[20];
char course[20];
int fees;
};
void display (struct student *);
int main()
{
struct student *ptr;
ptr = (struct student *)malloc(sizeof(struct student));
printf("\n Enter the data for the student ");
printf("\n ROLL NO.: ");
scanf("%d", &ptr–>r_no);
printf("\n NAME: ");
gets(ptr–>name);
printf("\n COURSE: ");
gets(ptr–>course);
}
printf(“/n FEES”);

scanf("%d", &ptr–>fees);
display(ptr);
getch();
return
}

void display(struct student *ptr)


{
printf("\n DETAILS OF STUDENT");
printf("\n ROLL NO. = %d", ptr–>r_no);
printf("\n NAME = %s", ptr–>name);
printf("\n COURSE = %s ", ptr–>course);
printf("\n FEES = %d", ptr–>fees);
}
Output
Enter the data for the student

ROLL NO.: 01
NAME: Rahul
COURSE: BCA
FEES: 45000
DETAILS OF STUDENT
ROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000
[Link]
CS3251 Programming in C - UNIT V

UNIT V FILE PROCESSING


Files – Types of file processing: Sequential access, Random access – Sequential
access file - Example Program: Finding average of numbers stored in sequential
access file - Random access file -Example Program: Transaction processing using
random access files – Command line arguments

5.1 Introduction

A file is a semi-permanent, named collection of data. A File is usually stored


on magnetic media, such as a hard disk or magnetic tape. Semi-permanent means that
data saved in files stays safe until it is deleted or modified.

Named means that a particular collection of data on a disk has a name, like
[Link] and access to the collection is done by using its name.

A file represents a sequence of bytes on the disk where a group of related data
is stored. File is created for permanent storage of data. It is a readymade structure.

5.1.1 Types of Files

1. Text files
2. Binary files
1. Text Files [Link]
A text file consists of consecutive characters, which are interpreted by the
library functions used to access them and by format specifiers used in functions.

Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors.

They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.

2. Binary files
A binary file consists of bytes of data arranged in continuous block. A separate
set of library functions is there to process such data files.

Binary files are mostly the .bin files in your computer. Instead of storing data in
plain text, they store it in the binary form (0's and 1's). They can hold higher amount
of data, are not readable easily and provides a better security than text files.

5.1.2 File Operations

In C, you can perform four major operations on the file, either text or binary:

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

1. Creating a new file

2. Opening an existing file

3. Closing a file

4. Reading from and writing information to a file

Function description

fopen() - create a new file or open a existing file

fclose() - closes a file

getc() - reads a character from a file

putc() - writes a character to a file

fscanf() - reads a set of data from a file

fprintf() - writes a set of data to a file

getw() - reads a integer from a file

putw() - writes a integer to a file

[Link]
fseek() - set the position to desire point

ftell() - gives current position in the file

rewind() - sets the position to the beginning point

1. Opening a File or Creating a File

Opening a file means creating a new file with specified file name and with accessing
mode.

The fopen() function is used to create a new file or to open an existing file.

Syntax:

*fp = FILE *fopen(const char *filename, const char *mode);

Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the
opened(or created) file.

filename is the name of the file to be opened and mode specifies the purpose of
opening the file.

Mode can be of following types:

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

Mode Description

Mode Purpose

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ [Link]
opens a binary file in both reading and writing mode

2. Closing a File

A file must be closed after all the operation of the file have been completed. The
fclose() function is used to close an already opened file.

Syntax:

int fclose( FILE *fp);

Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.

3. Reading and writing to a text file

i. Read a character from a file: fgetc function

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

The ‘fgetc’ function is used to read a character from a file which is opened in read
mode.

Syntax:

c=fgetc(p1);

where p1 is the file pointer.

ii. Read a data from a file: fscanf function

The fscanf function is used to read data from a file. It is similar to the scanf function
except that fscanf() is used to read data from the disk.

Syntax:

fscanf(fb “format string”, &v1, &v2…&vn);

where fb refers to the file pointer. v1, v2, … vn refers variables whose values are read
from the disk “format string” refers the control string which represents the conversion
specification.

iii. Write a character to a file:fputc function

The function ‘fputc’ is used to write a character variable x to the file opened in write
mode. [Link]
Syntax:

fputc(x,fp1);

where fp1 is the file pointer.

iv. Writing data to a file : fprintf()

fprintf() function is used to write data to a file. It is similar to the printf() function
except that fprintf() is used to write data to the disk.

Syntax:

fprintf(fp, “format string”, v1,v2… vn);

where fp refers to the file pointer.

5.2 Types of file processing

There are two main ways a file can be organized:

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

1. Sequential Access — In this type of file, the data are kept sequentially. To read last
record of the file, it is expected to read all the records before that particular record. It
takes more time for accessing the records.

2. Random Access — In this type of file, the data can be read and modified
randomly. If it is desired to read the last record of a file, directly the same record can
be read. Due to random access of data, it takes less access time as compared to the
sequential file.

Sequential Access File

A Sequential file is characterized by the fact that individual data items are
arranged serially in a sequence, one after another. They can only be processed in serial
order from the beginning. In other words, the records can be accessed in the same
manner in which they have been stored. It is not possible to start reading or writing a
sequential file from anywhere except at the beginning.

Random Access File

The second and better method of arranging records of a file is called direct
access or random access. In this arrangement one can have access to any record which
is situated at the middle of the file without reading or passing through other records in
the file.
[Link]
5.3 Reading Sequential Access file

Data is stored in files so that the data can be retrieved for processing when needed

Example:

[Link] file contents

100 Jones 9023.00

200 Frank 234.00

300 Mano 29023.00

400 Bala 2344.00

Program:

// Reading and printing a sequential file

#include <stdio.h>

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

#include <stdlib.h>

int main(void) {

unsigned int account; // account number

char name[30]; // account name

double balance; // account balance

FILE *cfPtr; // cfPtr = [Link] file pointer

// fopen opens file; exits program if file cannot be opened

if ((cfPtr = fopen("[Link]", "r")) == NULL) {

puts("File could not be opened");

exit(0);

printf("%-10s%-13s%s\n", "Account", "Name", "Balance");

fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);

// while not end of file [Link]


while (!feof(cfPtr)) {

printf("%-10d%-13s%7.2f\n", account, name, balance);

fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);

} // end while

fclose(cfPtr); // fclose closes the file

} // end main

Output:

Account Name Balance

100 Jones 9023.00

200 Frank 234.00

300 Mano 29023.00

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

400 Bala 2344.00

5.4 Read numbers from file and calculate Average

/* Program to read from the [Link] file and find the average of the numbers */

#include <stdio.h>

#include <stdlib.h>

#define DATAFILE "[Link]"

int main() {

FILE* fp;

int n[50], i = 0;

float sum = 0;

if ((fp = fopen(DATAFILE, "r")) == NULL) {

printf("Unable to open %s...\n", DATAFILE);

exit(0); [Link]
}

puts("Reading numbers from [Link]");

while (!feof(fp)) {

fscanf(fp, "%d ", &n[i]);

printf("%d %d\n", i, n[i]);

sum += n[i];

i++;

fclose(fp);

// if no data is available in the file

if (i == 0)

printf("No data available in %s", DATAFILE);

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

float average = sum / i;

printf("The average is %.3f for %d numbers\n", average, i);

return 0;

Output:

5.5 Random access file


[Link]
 Access individual records without searching through other records

 Instant access to records in a file

 Data can be inserted without destroying other data

 Data previously stored can be updated or deleted without overwriting.

⚫ Implemented using fixed length records

 Sequential files do not have fixed length records

0 100 200 300 400 500

} byte offsets
}
}
}
}
}
}

100 100 100 100 100 100


bytes bytes bytes bytes bytes bytes

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

5.5.1 Functions For Selecting A Record Randomly

The functions used to randomly access a record stored in a file are fseek(), ftell(),
rewind(), fgetpos(), and fsetpos().

1. fseek()

• fseek() is used to reposition a binary stream. The prototype of fseek() can be


given as,

• int fseek( FILE *stream, long offset, int origin);

• fseek() is used to set the file position pointer for the given stream. Offset is an
integer value that gives the number of bytes to move forward or backward in
the file. Offset may be positive or negative, provided it makes sense. For
example, you cannot specify a negative offset if you are starting at the
beginning of the file. The origin value should have one of the following values
(defined in stdio.h):

• SEEK_SET: to perform input or output on offset bytes from start of the file

• SEEK_CUR: to perform input or output on offset bytes from the current


position in the file

• [Link]
SEEK_END: to perform input or output on offset bytes from the end of the file

• SEEK_SET, SEEK_CUR and SEEK_END are defined constants with value 0,


1 and 2 respectively.

• On successful operation, fseek() returns zero and in case of failure, it returns a


non-zero value. For example, if you try to perform a seek operation on a file
that is not opened in binary mode then a non-zero value will be returned.

• fseek() can be used to move the file pointer beyond a file, but not before the
beginning.

Example: Write a program to print the records in reverse order. The file must be
opened in binary mode. Use fseek()

#include<stdio.h>

#include<conio.h>

main()

{ typedef struct employee

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

{ int emp_code;

char name[20];

int hra;

int da;

int ta;

};

FILE *fp;

struct employee e;

int result, i;

fp = fopen("[Link]", "rb");

if(fp==NULL)

{ printf("\n Error opening file");

exit(1);

} [Link]
for(i=5;i>=0;i--)

{ fseek(fp, i*sizeof(e), SEEK_SET);

fread(&e, sizeof(e), 1, fp);

printf("\n EMPLOYEE CODE : %d", e.emp_code);

printf("\n Name : %s", [Link]);

printf("\n HRA, TA and DA : %d %d %d", [Link], [Link], [Link]);

fclose(fp);

getch();

return 0;

2. rewind()

10

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

• rewind() is used to adjust the position of file pointer so that the next I/O
operation will take place at the beginning of the file. It’s prototype can be given
as

• void rewind( FILE *f );

• rewind() is equivalent to calling fseek() with following parameters:


fseek(f,0L,SEEK_SET);

3. fgetpos()

• The fgetpos() is used to determine the current position of the stream. It’s
prototype can be given as

int fgetpos(FILE *stream, fpos_t *pos);

• Here, stream is the file whose current file pointer position has to be determined.
pos is used to point to the location where fgetpos() can store the position
information. The pos variable is of type fops_t which is defined in stdio.h and
is basically an object that can hold every possible position in a FILE.

• On success, fgetpos() returns zero and in case of error a non-zero value is


returned. Note that the value of pos obtained through fgetpos() can be used by

[Link]
the fsetpos() to return to this same position.

4. fsetpos()

• The fsetpos() is used to move the file position indicator of a stream to the
location indicated by the information obtained in "pos" by making a call to the
fgetpos(). Its prototype is

• int fsetpos( FILE *stream, const fops_t pos);

• Here, stream points to the file whose file pointer indicator has to be re-
positioned. pos points to positioning information as returned by "fgetpos".

• On success, fsetpos() returns a zero and clears the end-of-file indicator. In case
of failure it returns a non-zero value

The program opens a file and reads bytes at several different locations.

#include <stdio.h>

main()

11

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

FILE *fp;

fpos_t pos;

char feedback[20];

fp = fopen(“[Link]”, “rb”);

if(fp == NULL)

printf(“\n Error opening file”);

exit(1);

// Read some data and then check the position.

fread( feedback, sizeof(char), 20, fp);

if( fgetpos(fp, &pos) != 0 )

[Link]
printf(“\n Error in fgetpos()");

exit(1);

fread(feeback, sizeof(char), 20, fp);

printf("\n 20 bytes at byte %ld: %s", pos, feedback);

// Set a new position and read more data

pos = 90;

if( fsetpos(fp, &pos ) != 0 )

printf(“\n Error in fsetpos()");

exit(1);

fread( feedback, sizeof(char), 20, fp);

12

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

printf( "\n 20 bytes at byte %ld: %s", pos, feedback);

fclose(fp);

5. ftell()

The ftell function is used to know the current position of file pointer. It is at this
position at which the next I/O will be performed. The syntax of the ftell() defined in
stdio.h can be given as:

long ftell (FILE *stream);

On successful, ftell() function returns the current file position (in bytes) for stream.
However, in case of error, ftell() returns -1.

When using ftell(), error can occur either because of two reasons:

First, using ftell() with a device that cannot store data (for example, keyboard)

Second, when the position is larger than that can be represented in a long integer. This
will usually happen when dealing with very large files

FILE *fp;

char c;
[Link]
int n;

fp=fopen("abc","w");

if(fp==NULL)

{ printf("\n Error Opening The File");

exit(1);

while((c=getchar())!=EOF)

putc(c,fp);

n = ftell(fp);

fclose(fp);

fp=fopen("abc","r");

13

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

if(fp==NULL)

{ printf("\n Error Opening The File");

exit(1);

while(ftell(fp)<n)

{ c= fgetc(fp);

printf('%c", c);

fclose(fp);

5.6 Example Program: Transaction processing using random access files

The program maintains a bank’s account information—updating existing accounts,


adding new accounts, deleting accounts and storing a listing of all the current accounts
in a text file for printing.
[Link]
The program has five options.

Option 1

calls function textFile to store a formatted list of all the accounts (typically called a
report) in a text file called [Link] that may be printed later. The function
uses fread and the sequential file access techniques used in the program of Section
below.

After option 1 is chosen, the file [Link] contains:

Acct Last Name First Name Balance

29 Brown Nancy -24.54

33 Dunn Stacey 314.33

37 Barker Doug 0.00

88 Smith Dave 258.34

96 Stone Sam 34.98

14

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

Option 2

calls the function updateRecord to update an account. The function will update only
a record that already exists, so the function first checks whether the record specified
by the user is empty. The record is read into structure client with fread, then member
acctNum is compared to 0. If it’s 0, the record contains no information, and a message
is printed stating that the record is empty. Then the menu choices are displayed. If the
record contains information, function updateRecord inputs the transaction amount,
calculates the new balance and rewrites the record to the file.

Enter account to update ( 1 - 100 ): 37

37 Barker Doug 0.00

Enter charge ( + ) or payment ( - ): +87.99

37 Barker Doug 87.99

Option 3

calls the function newRecord to add a new account to the file. If the user enters an
account number for an existing account, newRecord displays an error message
indicating that the record already contains information, and the menu choices are

[Link]
printed again

Enter new account number ( 1 - 100 ): 22

Enter lastname, firstname, balance

? Johnston Sarah 247.45

Option 4

calls function deleteRecord to delete a record from the file. Deletion is accomplished
by asking the user for the account number and re-initialising the record. If the account
contains no information, deleteRecord displays an error message indicating that the
account does not exist.

Option 5

terminates program execution.

Example Program:

15

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

// Bank-account program reads a random-access file sequentially, updates data already


written to the file, creates new data to be placed in the file, and deletes data previously
in the file. //

#include <stdio.h>

#include <stdlib.h>

// clientData structure definition

struct clientData {

unsigned int acctNum; // account number

char lastName[15]; // account last name

char firstName[10]; // account first name

double balance; // account balance

}; // end structure clientData

// prototypes

unsigned int enterChoice(void);


[Link]
void textFile(FILE *readPtr);

void updateRecord(FILE *fPtr);

void newRecord(FILE *fPtr);

void deleteRecord(FILE *fPtr);

int main(int argc, char *argv[]) {

FILE *cfPtr; // [Link] file pointer

unsigned int choice; // user's choice

// fopen opens the file; exits if file cannot be opened

// Do not change the mode "rb+" - it will not work!

if ((cfPtr = fopen("[Link]", "rb+")) == NULL) {

printf("%s: File could not be opened.\n", argv[0]);

exit(-1);

16

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

// enable user to specify action

while ((choice = enterChoice()) != 5) {

switch (choice) {

// create text file from record file

case 1:

textFile(cfPtr); break;

// update record

case 2:

updateRecord(cfPtr); break;

// create record

case 3:

newRecord(cfPtr); break;

[Link]
// delete existing record

case 4:

deleteRecord(cfPtr); break;

// display if user does not select valid choice

default:

puts("Incorrect choice"); break;

} // end switch

} // end while

fclose(cfPtr); // fclose closes the file

} // end main

// create formatted text file for printing

void textFile(FILE *readPtr) {

FILE *writePtr; // [Link] file pointer

17

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

int result; // used to test whether fread read any bytes

// create clientData with default information

struct clientData client = {0, "", "", 0.0};

// fopen opens the file; exits if file cannot be opened

if ((writePtr = fopen("[Link]", "w")) == NULL) {

puts("File could not be opened.");

} // end if

else {

rewind(readPtr); // sets pointer to beginning of file

fprintf(writePtr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name","First Name",


"Balance");

// copy all records from random-access file into text file

while (!feof(readPtr)) {

result = fread(&client, sizeof(struct clientData), 1, readPtr);


[Link]
// write single record to text file

if (result != 0 && [Link] != 0) {

fprintf(writePtr, "%-6d%-16s%-11s%10.2f\n", [Link],

[Link], [Link], [Link]);

} // end if

} // end while

fclose(writePtr); // fclose closes the file

} // end else

} // end function textFile

// update balance in record

void updateRecord(FILE *fPtr) {

18

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

unsigned int account; // account number

double transaction; // transaction amount

// create clientData with no information

struct clientData client = {0, "", "", 0.0};

// obtain number of account to update

printf("%s", "Enter account to update ( 1 - 100 ): ");

scanf("%d", &account);

// move file pointer to correct record in file

fseek(fPtr, (account - 1) * sizeof(struct clientData), SEEK_SET);

// read record from file

fread(&client, sizeof(struct clientData), 1, fPtr);

// display error if account does not exist

if ([Link] == 0) {

[Link]
printf("Account #%d has no information.\n", account);

} else { // update record

printf("%-6d%-16s%-11s%10.2f\n\n", [Link], [Link],

[Link], [Link]);

// request transaction amount from user

printf("%s", "Enter charge ( + ) or payment ( - ): ");

scanf("%lf", &transaction);

[Link] += transaction; // update record balance

printf("%-6d%-16s%-11s%10.2f\n", [Link], [Link],


[Link], [Link]);

// move file pointer to correct record in file

// move back by 1 record length

fseek(fPtr, -sizeof(struct clientData), SEEK_CUR);

19

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

// write updated record over old record in file

fwrite(&client, sizeof(struct clientData), 1, fPtr);

} // end else

} // end function updateRecord

// delete an existing record

void deleteRecord(FILE *fPtr) {

struct clientData client; // stores record read from file

struct clientData blankClient = {0, "", "", 0}; // blank client

unsigned int accountNum; // account number

// obtain number of account to delete

printf("%s", "Enter account number to delete ( 1 - 100 ): ");

scanf("%d", &accountNum); [Link]

// move file pointer to correct record in file

fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET);

// read record from file

fread(&client, sizeof(struct clientData), 1, fPtr);

// display error if record does not exist

if ([Link] == 0) {

printf("Account %d does not exist.\n", accountNum);

} // end if

else { // delete record

// move file pointer to correct record in file

fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET);

20

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

// replace existing record with blank record

fwrite(&blankClient, sizeof(struct clientData), 1, fPtr);

} // end else

} // end function deleteRecord

// create and insert record

void newRecord(FILE *fPtr) {

// create clientData with default information

struct clientData client = {0, "", "", 0.0};

unsigned int accountNum; // account number

// obtain number of account to create

printf("%s", "Enter new account number ( 1 - 100 ): ");

scanf("%d", &accountNum);

[Link]
// move file pointer to correct record in file

fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET);

// read record from file

fread(&client, sizeof(struct clientData), 1, fPtr);

// display error if account already exists

if ([Link] != 0) {

printf("Account #%d already contains information.\n", [Link]);

} // end if

else { // create record user enters last name, first name and balance

printf("%s", "Enter lastname, firstname, balance\n? ");

scanf("%14s%9s%lf", [Link], [Link], &[Link]);

[Link] = accountNum;

21

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

// move file pointer to correct record in file

fseek(fPtr, ([Link] - 1) * sizeof(struct clientData), SEEK_SET);

// insert record in file

fwrite(&client, sizeof(struct clientData), 1, fPtr);

} // end else

} // end function newRecord

// enable user to input menu choice

unsigned int enterChoice(void) {

unsigned int menuChoice; // variable to store user's choice

// display available options

printf("%s", "\nEnter your choice\n"

"1 - store a formatted text file of accounts called\n"

[Link]
" \"[Link]\" for printing\n"

"2 - update an account\n"

"3 - add a new account\n"

"4 - delete an account\n"

"5 - end program\n? ");

scanf("%u", &menuChoice); // receive choice from user

return menuChoice;

} // end function enterChoice

Output

22

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

[Link]

5.7 Command line arguments

Command line argument is a parameter supplied to the program when it is invoked.


Command line argument is an important concept in C programming. It is mostly used
when you need to control your program from outside. Command line arguments are
passed to the main() method.

Syntax:

int main(int argc, char *argv[])

23

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

Here argc counts the number of arguments on the command line and argv[ ] is a
pointer array which holds pointers of type char which points to the arguments passed
to the program

Example:

#include <stdio.h>

#include <conio.h>

int main(int argc, char *argv[])

int i;

if( argc >= 2 )

printf("The arguments supplied are:\n");

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

printf("%s\t", argv[i]); [Link]


}

else

printf("argument list is empty.\n");

return 0;

Remember that argv[0] holds the name of the program and argv[1] points to the first

command line argument and argv[n] gives the last argument. If no argument is

supplied, argc will be 1.

24

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

Multiple Choice Questions

1. _______ is a collection of data.

A. Buffer

B. Stream

C. File

Answer: File

2. If the mode includes b after the initial letter, what does it indicates?
a) text file
b) big text file
c) binary file
Answer: binary file

[Link]
3. What is the function of the mode ‘ w+’?
a) create text file for writing, discard previous contents if any
b) create text file for update, discard previous contents if any
c) create text file for writing, do not discard previous contents if any
d) create text file for update, do not discard previous contents if any
Answer: create text file for update, discard previous contents if any

4. fflush(NULL) flushes all ____________


a) input streams
b) output streams
c) previous contents
d) appended text
Answer: output streams
5. What is the keyword used to declare a C file pointer.?
A) file

25

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

B) FILE
C) FILEFP
D) filefp
Answer: FILE

6. What is a C FILE data type.?


A) FILE is like a Structure only
B) FILE is like a Union only
C) FILE is like a user define int data type
D) None of the above
Answer: FILE is like a Structure only

7. Where is a file temporarily stored before read or write operation in C


language.?
A) Notepad
B) RAM
C) Hard disk [Link]
D) Buffer
Answer: Buffer

8. Which function gives the current position of the file.


A. fseek()
B. fsetpos()
C. ftell()
D. Rewind()
Answer: ftell()

9. Which function is used to perform block output in binary files?


A. fwrite()

B. fprintf()

26

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

C. fputc()

D. fputs()

Answer: fwrite()

10. Select the standard stream in C

A. stdin

B. stdout

C. stderr

D. all of these

Answer: all of these

11. From which standard stream does a C program read data?

A. Stdin

B. stdout [Link]
C. stderr

D. all of these

Answer: stderr

12. Which acts as an interface between stream and hardware?

A. file pointer

B. buffer

C. stdout

D. stdin

Answer: buffer

13. Which function is used to associate a file with a stream?

A. fread()

27

Downloaded from [Link]


[Link]
CS3251 Programming in C - UNIT V

B. fopen()

C. floes()

D. fflush()

Answer: fopen()

14. Which function returns the next character from stream, EOF if the end of file
is reached, or if there is an error?

A. fgetc()

B. fgets()

C. fputs()

D. fwrite()

Answer: fgetc()

[Link]

28

Downloaded from [Link]

You might also like