S.PRINCY SUGANTHI BAI - Vidyarthiplus

159
MC7102-PROBLEM M SOLVING AND PROGRAMM S.PRINCY SUGANT Asso.Prof/ MCA d MING THI BAI dept., www.Vidyarthiplus.com www.Vidyarthiplus.com

Transcript of S.PRINCY SUGANTHI BAI - Vidyarthiplus

Page 1: S.PRINCY SUGANTHI BAI - Vidyarthiplus

MC7102-PROBLEM SOLVING AND PROGRAMMING PROBLEM SOLVING AND PROGRAMMING

S.PRINCY SUGANTHI BAI

Asso.Prof/ MCA dept.,

PROBLEM SOLVING AND PROGRAMMING

S.PRINCY SUGANTHI BAI

Asso.Prof/ MCA dept.,

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 2: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

UNIT 1

INTRODUCTION TO COMPUTER PROBLEM SOLVING

I. Programs and requirements for problem solving

Problem solving can be stated as intricate process requiring much thought, careful

planning, logical precision, persistence and attention to detail. It can be challenging, exciting and

satisfying experience with considerable room for personal creativity and expression.

i. Programs and Algorithms

v Computer solution to a problem is a set of explicit and unambiguous instructions

expressed in a programming language.

v Set of instructions is called a program.

v A Program can thought as algorithm expressed in a programming language.

v An algorithm corresponds to a solution to a problem that is independent of any

programming language.

v Program should supply with input data.

v Input data manipulate according to the instructions and produce the output.

v Output represents computer solution to the problem.

Algorithm:

Algorithm consists of a set of explicit and unambiguous final steps which, when carried

out for a given set of initial conditions, produce the corresponding output and terminate in a

finite time.

ii. Requirements for solving problems by Computer

v One can employ algorithms to solve problems.

Problem

Algorithm

I/P Computer O/P

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 3: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v Depth understanding is needed to design algorithm which solve any complex

problem.

Example : Telephone Directory Look up Problem:

· A Telephone directory has thousands of names and numbers.

· Searching by name or number from page 1 is lengthy and time consuming

process.

· Probably the directory is sorted by number than name.

· Data structure is linked with algorithm for high performance.

II. Problem Solving Aspect

v Problem Solving is a creative process which largely defines systemation and

mechanization.

v Problem solving has number of steps to achieve the goal.

1) Problem definition phase:

v Defining the problem fully is done in the problem definition phase.

v This phase decides “What must be done” rather “How to do it”.

v Problem statement gives a set of precisely defined tasks.

2) Getting started on a problem:

v Many ways to solve most problems.

v Many solutions to most problems.

v Difficult to identify which path is fruitful and fruitless while solving a problem.

v After getting complete idea it is better to start implementation. It means “What

can we do”.

v Proverb states that “Sooner your start coding your program the longer it is going

to take”.

3) Use of specific examples:

v Many strategies, while using, we may stuck in some point.

v It is usually much easier to work out the details of a solution to a specific

problem.

v Geometrical or schematic diagrams representing certain aspects of the problem

can be usefully employed in many instances.

v Example: The Greatest common divisor of 2 numbers.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 4: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Problem: Given 2 positive non zero integers n and m. find GCD of n and m.

Algorithm development:

1. Ordinary Procedure

v Find the common divisors of both n and m. v Then find the GCD of both in common.

Step 1: Find the prime factors of m

Step 2: Find the prime factors of n

Step 3: Find the common factors in prime expansion

Step 4: Compute the product of common factors. It gives the output.

Example : input m and n

Say m=60 and n=24

2×2×3=12

· GCD of 60, 24 is 12.

Here step 3 is tedious.

2. Euclid’s Algorithm:

gcd(m, n) = gcd(n, m mod n)

i.e Remainder of division m by n

Step 1: If n=0 return value of m and stop

Else goto step 2

Step 2: Divide m by n and assign remainder to r

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 5: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Step 3: Assign m=n and n=r

Goto step 1 i.e making r=0.

Pseudo code:

While n≠0

r←m mod n

m←n

n←r

return m

Thus, largest integer that divides both numbers evenly is called GCD.

3. Another Method:

Ø The GCD of 2 numbers may be the least of the 2 numbers (or) less than the small

number of the given 2 numbers

Ø Take min of 2 numbers t = min {m,n}

Ø Check whether t divides m and n

if (t)

Then t is the answer

Else

T=t-1

Decrease by 1

Algorithm:

Step 1: t=min {m,n}

Step 2: Divide m by t

M mod t = 0

Goto step 3

Other

Goto step 4

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 6: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Step 3: Divide n by t

If (n mod t = 0)

Return t

Else

Goto step 4

Step 4: t = t-1

Goto step 2

Algorithm work fine when one i/p is zero. Otherwise it is time consuming.

4) Similarities among problems:

v Get the past experience for any current problem

v Start any solving process with specific example.

v Have aware about the similarities of various problems.

v More experience in more tools and techniques helps to solve the problem easily.

v Sometimes previous experience blocks new creativity or better solution.

v Place only cautious reliance on past experience.

v Independently solving the problem sometimes gives better solution.

v Analyzing past problems and experience sometimes leads to dead end.

v Solve a problem after viewing the problem from different angles.

v Analyze the problem by turning a problem upside down, inside out, sideways,

backwards, forwards and so on…..

5) Working backwards from the solution

v Try to work backwards to the starting conditions. This is significantly better.

v Important thing in developing problem solving skills is practice.

v Piaget says that “We learn more when we have to intent”.

6) General problem solving strategies:

v There are many general and powerful computational strategies that are used in

many guises in computer science.

v Mostly used principle is “Divide and Conquer Strategy”.

v Divide and Conquer:

Ø It divide the original problem in to sub problems

Ø It is possible to split the problem into smaller and smaller sub problems.

Ø Applied for sorting, selecting and searching algorithms.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 7: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Example : Binary search algorithm

Step 1: Arrange the elements in order (sequential order)

Step 2: Split the list and find the middle value and compare with the

element to be searched.

Step 3: If middle value > element to be searched

Perform step 2 for second half

Else

Perform step 2 for first half

Perform step 2 and 3 until goal achieved.

A[0]………A[m-1] A[m] A[m+1] …A[n-1]. Find k l = 0, r = n-1

Step 1: Split the sorted array (l+r)/2

Step 2: if k = A[m] m-> middle index

Stop

Elseif

Divide and conquer for k < A[m]

Else

Divide and conquer applied k > A[m] (second half of the list).

3 14 27 31 39 42 m

70 74 81 85 93 98

r

Ø Need log2n comparison rather than n comparison.

Ø It is good for searching problems.

Example: Dynamic Programming

v Build up a solution to a problem through a sequence of intermediate steps.

v Idea that a good solution to a large problems by finding good solution to smaller

problems

v It is technique for solving problems with overlapping sub problems

Example: Fibonacci series.

0 1 1 2 3 5 8 13 21 34

By Recurrence:

55

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 8: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

F(n) = f(n-1) + f(n-2) for n≥2

Initial condition f(0)=0 f(1)=1

n=5

Dynamic Programming algorithm:

v Refined to avoid using extra space.

v Avoid solving unnecessary sub problems.

v It is an algorithm design technique for optimization problems.

v Solves problems by combing solutions to sub problems.

v Sub problems dependent.

v Solutions of sub problem not affect another sub problem.

III. Top Down Design

v An algorithm is able to implement a correct and efficient computer program.

v To solve a problem powerful techniques are used to design an algorithm.

v The problem can be solved effectively if the algorithm manages the inherent complexity.

v A technique for algorithm design that tries to accommodate some human limitations is

known as Top down design or stepwise refinement.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 9: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v Solve the problem in stepwise fashion.

[1] Breaking a problem into sub problems

v First the ground work should be done that gives the outline of a solution.

v Problem description itself sometimes gives starting point for top

v Outline may have set of statement or a single statement.

v One statement or task can be splitted into sub tasks.

v These well-defined sub tasks are useful to reach the final goal.

v Sub tasks need to interact with each other should well defined. This preserve over all

structure of the solution to the problem.

v Preservation of overall structure needed to prove the correctness of the solution.

v Large task is divided into sub tasks. Sub tasks are again

sub tasks form the program statement.

v Schematic breakdown of a problem into sub tasks as employed in top down design.

[2] Choice of a suitable data structure

Solve the problem in stepwise fashion.

problems

First the ground work should be done that gives the outline of a solution.

iption itself sometimes gives starting point for top down design.

Outline may have set of statement or a single statement.

One statement or task can be splitted into sub tasks.

defined sub tasks are useful to reach the final goal.

to interact with each other should well defined. This preserve over all

structure of the solution to the problem.

Preservation of overall structure needed to prove the correctness of the solution.

Large task is divided into sub tasks. Sub tasks are again sub divided into sub tasks. End

sub tasks form the program statement.

Schematic breakdown of a problem into sub tasks as employed in top down design.

[2] Choice of a suitable data structure

down design.

to interact with each other should well defined. This preserve over all

Preservation of overall structure needed to prove the correctness of the solution.

sub divided into sub tasks. End

Schematic breakdown of a problem into sub tasks as employed in top down design.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 10: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v Important decision in formulating computer solutions to problems is the choice of

appropriate data structures.

v Organized data has the effect on final solution.

v Inappropriate choice leads to a simple, transparent and efficient implementation.

v Data structure can be defined at any stage of the algorithm development.

v It is desirable when considered DS at very outset of our problem solving explorations

before the top down design.

v It can also be refined as the algorithm is developed.

v Data structures and algorithms are linked to each other.

v A small change in data organization can have a significant influence on an algorithm.

v There is no formula that is problem must use this choice of data structure.

v Things to be asked or aware when DS chosen are

§ How can the intermediate results are arranged that reduce computation in the later

stage?

§ Can the data structure be easily searched?

§ Can the data structure be easily updated?

§ Can earlier state can be recovered?

§ Whether need excess storage?

§ It is possible to impose some data structures on a problem that is not initially

apparent?

§ Can be problem be formulated in terms of one of the common data structures.

Example: array, set, queue, stack, tree, graph, list?

[3] Construction of loops:

v Sub tasks are leads to series of iterative constructs, loops or structures that work under

condition.

v These, work with i/p or o/p statements, computable expressions and assignments form the

heart of the program implementation.

v Loop has three important parts

· Initial condition – loop begins

· Invariant relation – apply for each iteration

· Terminate (condition) – Under which iterative process work or terminate.

v Some problems use straight forward process instead of loops.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 11: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Summation problem

[4] Establishing initial conditions for loops

v Set loop variable to a value

v The range may be 0≤i≤n for n

v A smallest problem has i=0 or i=1

v n=0 means i=0 and s=0

[5] Finding the iterative construct

v To solve a problem of i=1 then we must solve i=0

The solution for n=1 is

The solution for n>1 is

The solution to summation problem is n

i=1

s=a[1]

i=i+1

s=s+a[i]

i=0; s=0;

while i<n do

begin

i=i+1;

s=s+a[i];

end

Summation problem

[4] Establishing initial conditions for loops

n for n iterations.

problem has i=0 or i=1

[5] Finding the iterative construct

To solve a problem of i=1 then we must solve i=0

The solution to summation problem is n≥0

i=1

s=a[1]

i=i+1

s=s+a[i]

i=0; s=0;

while i<n do

begin

i=i+1;

s=s+a[i];

end

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 12: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Example 3 with sample data

[6] Termination of loops

v Loops terminated by

Ø Known number of iterations.

Ø Direct termination facility in program code.

Example 1: Pascal for loop

Unconditionally loop terminates after n

Example 2: Pascal while loop

No guarantee of termination of loop

For i=1 to n do

Begin

.

.

.

end

While(x>0) and (x<10) do

begin

.

end

Example 3 with sample data

Known number of iterations.

Direct termination facility in program code.

Pascal for loop

terminates after n

Pascal while loop

termination of loop

For i=1 to n do

Begin

While(x>0) and (x<10) do

begin

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 13: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Example 3: Termination possible with simplifying test.

Establish an array of n elements

a[1]<a[2]<……<a[n]

a[n+1]=a[n]

i=1

while a[0]<a[i+1]

do

i=i+1;

IV. Implementation of Algorithms

v Properly designed in a top down fashion

v Top down rule easy to understand and debug

v Also easy to modify because the program are much more apparent.

[1] Use of procedure to emphasize modularity:

v Top down design are easy to understand and more readable, thus it can be modularize.

v Modularize means splitting the large or lengthy program into set of independent

procedures.

v This set of procedures will perform well defined tasks.

[2] Choice of variable names:

v Proper variable names are chosen so that easy to understand and remember in future

work.

v Example : To name a variable to store a day means, variable name is day instead of just

d or a.

v A clean definition of all variables and constants at the start of each procedure can makes

the program more meaningful. This is a process of self documenting.

[3] Documentation of programs:

v A program should be more effective and useful if it understood and used by other people.

v It must give the extract requirement i.e input with format for the user.

Example: Enter a number between 0 to 10 as a whole number.

Procedure sort

Begin

Writeln(‘sort called’)

end

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 14: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v The program should properly handle the wrong

given.

[4] Debugging programs:

v Various test should be done even for a small program to have a error free program.

v Additional information given with output that it can work normal or abnormal situation

respect to the input given.

v A simple debugging tool is Boolean variable.

if debug then

Begin

Writeln(…..)

End

v Error should be handled more effectively which results in a good program.

v Work the program by hand before put in to the system.

v No method for debugging but some

v Example : Binary search procedure

Problem

1. Search value x

2. Array a[1….n]

3. x=44; n=15

he program should properly handle the wrong request i.e proper response should be

Various test should be done even for a small program to have a error free program.

Additional information given with output that it can work normal or abnormal situation

A simple debugging tool is Boolean variable.

f debug then

Writeln(…..)

Error should be handled more effectively which results in a good program.

Work the program by hand before put in to the system.

method for debugging but some steps makes the task easy.

Example : Binary search procedure

request i.e proper response should be

Various test should be done even for a small program to have a error free program.

Additional information given with output that it can work normal or abnormal situation

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 15: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v To get proper result do the task by hand written stepwise procedure.

v Do not assume anything. Make it clear and then proceed.

[5] Program Testing

v A program must be designed to solve a problem which can accommodate with limiting

and unusual cases.

v Unusual cases make the program critical.

v Necessary to handle all types of inputs.

v A program should properly respond to the user inputs.

v Writing a program to a specific case generally need a lot of time and effort.

v Program must solve wide area of problems.

v Instead of fixed constants, variables are used.

Example 1: while i<100 do // Fixed constatnt

Example 2: while i<n do // Variable

v Fixed constant are useful for specific cases.

V. Program Verification

v Software development and debugging need more time and effort.

v Large program need more time and more effort.

v Top down design are useful to make the program readable and understandable.

get proper result do the task by hand written stepwise procedure.

Do not assume anything. Make it clear and then proceed.

A program must be designed to solve a problem which can accommodate with limiting

the program critical.

Necessary to handle all types of inputs.

should properly respond to the user inputs.

Writing a program to a specific case generally need a lot of time and effort.

Program must solve wide area of problems.

of fixed constants, variables are used.

while i<100 do // Fixed constatnt

while i<n do // Variable

Fixed constant are useful for specific cases. Example Tmonths=12;

development and debugging need more time and effort.

Large program need more time and more effort.

Top down design are useful to make the program readable and understandable.

A program must be designed to solve a problem which can accommodate with limiting

Writing a program to a specific case generally need a lot of time and effort.

Top down design are useful to make the program readable and understandable.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 16: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v Program correctness can be a matter of life or death in the case of military, space and

medical applications.

v Demonstrating program correctness is more needed that working different input to a

particular problem.

Program Verification:

It refers to a application of mathematical proof techniques to establish that the results

obtained by the execution of a program with arbitrary inputs are in accord with formally defined

output specifications.

Prove the algorithm at the basic level itself or abstract or superficial level.

[1] Computer model for program execution

v A program may have variety of path for termination.

v According to the input path has chosen for execution and terminate.

v A program may transit from one state to another.

v A state transition changes the value of the variable in a current execution path.

v As well as instructions that change the computation state there also other instructions that

simply makes tests on the current state.

v These tests make change in the sequential flow of execution.

v This model for program execution provides us with a foundation on which to construct

correctness proofs of algorithms.

[2] Input and Output assertions:

v Program correctness depends on formal statement

v Formal statement has 2 parts:

è Input assertion

è Output assertion

v Input assertion: Specify any condition placed on the values of the input

variable

v Output assertion: Produce for input data that satisfies the input assertion.

(x=q * y+r) ^ (r<y)

v The output assertion can written as logical notation

(x=q * y + r) ^ r<y

^ - Logical connectivity “and”

Q - Quotient

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 17: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

R - remainder

x divided y

[3] Implication and Symbolic execution

v Problem can be verified by a set of implication.

v General form of implication.

P Q

P à assumption

Q à conclusion

P Q P Q

True True True True False False False True True False False true

v If assumption and conclusion are same then true else if conclusion is true then true.

v Symbolic execution replaces all input data values into symbolic value and all arithmetic

operations into algebraic manipulation of symbolic expressions.

Normal execution

x=3 y=1

x=x-y ===> x=3-1

=2

Symbolic execution

x=α y=β

x=x-y ===> x=α-β

if x=α-β and y=β

then find y=x+y

y= α-β+ β

y= α

v Symbolic execution enables us to transform the verification procedure into proving that

the input assertion with symbolic values substituted for all input variables implies the

output assertion with final symbolic values substituted for all variables. This is called as

Verification condition.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 18: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v A number of intermediate verification conditions between the inpu

are needed.

v Verification conditions are straight line segment, branching segments and loop segment.

[4] Verification of straight line program segments:

A number of intermediate verification conditions between the input and output assertions

Verification conditions are straight line segment, branching segments and loop segment.

[4] Verification of straight line program segments:

t and output assertions

Verification conditions are straight line segment, branching segments and loop segment.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 19: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

[5] Verification of program segments with branches:

[5] Verification of program segments with branches:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 20: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

[6] Verification of program segments with loops:

Verification of program segments with loops:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 21: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 22: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

[7]Verification of program segments that employ arrays

]Verification of program segments that employ arrays

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 23: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 24: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 25: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

VI. The efficiency of algorithms

v Efficiency lies on design, implementation and analysis of algorithms

v CPU and internal memory efficiency helps to improve algorithm efficiency.

v Computer resources are needed to complete the task of a algorithm.

v Always aware to design a algorithm which was more economical.

v This is possible by only by giving specific response regarding to the

problem.

Efficiency lies on design, implementation and analysis of algorithms

memory efficiency helps to improve algorithm efficiency.

Computer resources are needed to complete the task of a algorithm.

Always aware to design a algorithm which was more economical.

This is possible by only by giving specific response regarding to the characteristics of a

memory efficiency helps to improve algorithm efficiency.

characteristics of a

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 26: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

[1] Redundant Computations:

v Redundant computation leads to inefficiency.

v When it occurs inside for loop or any other loops, it will be executed many times.

That leads more serious.

v Repeatly recalculating same set

v Unnecessary multiplications and additions should be removed.

Redundancy inside the inner loops should be eliminated.

[2] Referring array elements:

v Redundancy easily creeps

v Version 1 is not more efficient

Redundant computation leads to inefficiency.

When it occurs inside for loop or any other loops, it will be executed many times.

That leads more serious.

Repeatly recalculating same set of statements remains constant.

Unnecessary multiplications and additions should be removed.

Redundancy inside the inner loops should be eliminated.

Redundancy easily creeps into array processing.

Version 1 is not more efficient because of condition a[i]>a[p].

When it occurs inside for loop or any other loops, it will be executed many times.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 27: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v The condition a[i]>a[p] need only one memory reference.

[3] Inefficiency due to late termination

v The inefficiency will occur if the algorithm terminates late.

v Late in-sense, suppose after achieving the goal the other data

v Example: Alphabetical (linear) search

In linear search each data is visited and if target achieved the program terminates.

If it does not terminate then occur inefficiency.

Version 1 terminates after visiting complete list of items.

Version 2 terminates once the target is obtained.

The condition a[i]>a[p] need only one memory reference.

[3] Inefficiency due to late termination

The inefficiency will occur if the algorithm terminates late.

sense, suppose after achieving the goal the other data also visited.

Example: Alphabetical (linear) search

In linear search each data is visited and if target achieved the program terminates.

then occur inefficiency.

Version 1 terminates after visiting complete list of items.

2 terminates once the target is obtained.

In linear search each data is visited and if target achieved the program terminates.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 28: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

[4] Early detection of desired output conditions

v Inefficiency sometimes involved due to early detection of desired output conditions.

v This early detection of desired output condition leads to termination problem

Eg Bubble sort

v Due to the nature of input the output condition met early before termination condition

met.

v This will happen when i/p list is in sorted order.

[5] Trading storage for efficiency gains

v To speed up an algorithm, always include least number of loops.

v One loop to do one job is better. This is like one variable hold one value.

v Trade between storage and efficiency improve performance.

v Save some intermediate results to avoid unnecessary testing.

v Always use less memory space algorithm to improve efficiency.

VII. The Analysis of algorithms

v Every one follow algorithm which gives good solution.

v Good solution to a problem is always appreciable.

v Good solution should be quantitative or qualitative.

v The solution should be more economical.

v Economical in terms of human as well as system.

Good algorithm qualities and capabilities

· They are simple but powerful and general solution.

· Easy to understood and clear in implementation without tricky.

· Easily modified if needed.

· Correct for clearly defined situations.

· Able to understand on number of levels.

· Economical in terms of time, storage and peripherals.

· Documented clearly that anyone can understand.

· Must machine independent.

· Used as sub procedure for other problems.

· The solution must please, satisfy and made to feel proud to its designer.

Quantitative measures give the way to predict the performance of an algorithm and can be

comparing with other algorithm of same problem.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 29: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· A algorithm is efficient if its saves computing resources which saves times and money.

[1]Computational complexity:

Computational model that gives the algorithm performance foe specified input

conditions.

· It is a quantitative measurement.

· Performance measured in terms of problem size (n).

· n increases then cost increases.

· Lower end of the scale, also have logarithmic dependence of n.

· Higher end of the scale, also have exponential dependence on n.

Computational cost as a function of problem size for a range of computational

complexities.

Log 2n N Nlog2n N2 N3 2n

1 2 2 4 8 4 3.322 10 33.22 102 103 >103

6.644 102 664.4 104 106 >>1025

9.966 103 9966.0 106 109 >>10250

13.287 104 132,877 108 1012 >>102500

v One can solve only very small problem with an algorithm that exhibits exponential

behavior.

v Logarithmic dependence on n

If problem n=104, 13 steps needed 13 micro seconds needed.

v Exponential algorithm on n if n=100, Time taken : Earth terminate

v N grows due to comparison or number of times some arithmetic expressions repeated.

[2] The Order notation

v A standard notation developed to represent functions which bound the computing time

for algorithms.

v It is three types.

v Usually O notation is used. O notation can be called “Big O” notation.

v An algorithm in which the dominant mechanism is executed cn2 times for c, a constant

and nà problem size is said to be order n2 complexity. It can be written as O(n2).

v A function g(n) is Of(n) provided there is a constant c, the relation is g(n) ≤ c f(n) holds

for all value of n that are finite and positive.

v G(n) and f(n) can be expressed as lim:→铺 苹纵:邹坪纵屁邹= 规

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 30: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

C is not equal to zero.

Example:

An algorithm that requires 3n2+6n+3 comparisons to complete its task.

G(n)= 3n2+6n+3

p 辜矫→酵 舰(矫)交纵僵邹= 礁 3n2+6n+3 =3

N2

v The particular algorithm has an asymptotic complexity of O(N2).

v An algorithm with a higher asymptotic complexity has a very small constant of

proportionality and hence for some particular range of n it will give better performance

than an algorithm with lower complexity and a higher proportionality constant.

[3] Worst and average case behavior

v Worst and average case applied to both the time and space complexity of an algorithm.

v Worst complexity:

Given problem size n corresponds to the maximum complexity encountered

among all problem of size n.

v In many practical applications it is much more important to have a measure of the

expected complexity of a given algorithm rather than the worst case behavior.

v The expected complexity gives a measure of the behavior of the algorithm averaged over

all possible problems of size n.

v In comparing 2 algorithms to solve a given problem, generally opt in preference for the

algorithm that has the lower expected complexity.

[4] Probabilistic average case analysis

v Characteristic the behavior of an algorithm that linearly searches an ordered list of

elements for some value x.

1 2 ………… N

Worst case:

Necessary for the algorithm to examine all n values in the list before terminating.

Average case:

A probabilistic average case analysis it is generally assumed that all possible points are

equally likely, i.e the probability that x will be found at position 1 is 1/n and at position 2 is 1/n

and so on.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 31: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v The average search cost is therefore the sum of all possible search costs each multiplied

by their associated probability.

Example: If n=5

Average search cost=1/5(1+2+3+4+5) = 3

General case

Average search cost=1/n(n/2(n+1))

=n+1/2

v Average number of iterations of the search loop that are required before the algorithm

terminates in a successful search.

v The associated binary search for an array of size 15.

v One element can found with 1 comparison

v Two elements with 2 comparisons.

v Four elements with 3 comparisons

v So on…… The sum of over all possible elements =

v 2i elements require i+1 comparison

v Average search cost is again just the sum over all possible search costs, each multiplied by

their associated probability.

The average search cost is therefore the sum of all possible search costs each multiplied

by their associated probability.

Average search cost=1/5(1+2+3+4+5) = 3

st=1/n(n/2(n+1))

Average number of iterations of the search loop that are required before the algorithm

terminates in a successful search.

The associated binary search for an array of size 15.

One element can found with 1 comparison

Two elements with 2 comparisons.

Four elements with 3 comparisons

So on…… The sum of over all possible elements = 1+2+2+3+3+3+3+4+…..

comparison.

Average search cost is again just the sum over all possible search costs, each multiplied by

The average search cost is therefore the sum of all possible search costs each multiplied

Average number of iterations of the search loop that are required before the algorithm

1+2+2+3+3+3+3+4+…..

Average search cost is again just the sum over all possible search costs, each multiplied by

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 32: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v It is exact only when n is one less than a power of two.

the sum

v Sum is a geometric progression

v To compute the sum take the derivation of (x

v After substituting the sum in average search cost expression, average search cost is got

PROGRAMMING, ALGORITHMS & F

1) Program and programming

· A computer can neither think nor judge on its own.

· A computer independently analyzes

· A program is a set of logically related instructions that is arranged in

guides the computer in solving a problem.

· A program is a set of instructions to perform a task.

· Process of writing a program is called Programming.

It is exact only when n is one less than a power of two. Some calculus is needed to evaluate

Sum is a geometric progression

To compute the sum take the derivation of (xk+1)/(x-1) multiplied by 2

After substituting the sum in average search cost expression, average search cost is got

UNIT II

PROGRAMMING, ALGORITHMS & FLOW CHARTS

Program and programming

A computer can neither think nor judge on its own.

A computer independently analyzes a given data and find a solution on its own.

A program is a set of logically related instructions that is arranged in a sequence and

guides the computer in solving a problem.

A program is a set of instructions to perform a task.

a program is called Programming.

Some calculus is needed to evaluate

After substituting the sum in average search cost expression, average search cost is got

LOW CHARTS

a given data and find a solution on its own.

a sequence and

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 33: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· If the system is not correctly programmed, it delivers information

be used.

· Program acquired by

1. Purchase an existing program

2. Prepare a new program from scratch

[1] System software

· Language Translator: Transforms a computer program

that can be understood by the machine.

· Examples of Language translators:

· COBOL 3

· Turbo C

· Borland C etc….

· Operating system: It manages the computer resources effectively, take care of

scheduling multiple jobs for execution, a

between the input/output units and the main memory.

· OS have been developed and gone several revisions and modifications to achieve

better utilization of computer

· Advances in computer hardware have hel

· Utilizes: utility programs are those that may be requested by application programs

many times during the execution phase.

· Example(utilizes):

· Sort/merge for sorting large volumes of data and merging

· Transfer programs for transforming data content from one medium to another disk to

tape, tape to disk etc……

Special purpose software:

If the system is not correctly programmed, it delivers information results that

1. Purchase an existing program – Packaged software

2. Prepare a new program from scratch – Customized software.

Language Translator: Transforms a computer program written by the user into a form

that can be understood by the machine.

Examples of Language translators:

: It manages the computer resources effectively, take care of

scheduling multiple jobs for execution, and manages the flow of data and instructions

between the input/output units and the main memory.

OS have been developed and gone several revisions and modifications to achieve

better utilization of computer resources.

Advances in computer hardware have helped in the development of more efficient os.

Utilizes: utility programs are those that may be requested by application programs

many times during the execution phase.

Sort/merge for sorting large volumes of data and merging them into a sorted list.

Transfer programs for transforming data content from one medium to another disk to

tape, tape to disk etc……

results that cannot

written by the user into a form

: It manages the computer resources effectively, take care of

nd manages the flow of data and instructions

OS have been developed and gone several revisions and modifications to achieve

ped in the development of more efficient os.

Utilizes: utility programs are those that may be requested by application programs

orted list.

Transfer programs for transforming data content from one medium to another disk to

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 34: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Extend the capability of operating systems to provide specialized services to

application programs.

[2] Application Software:

v Enable the computer to solve a specific data processing task.

v 2 categories of application software

1. Pre written software packages

2. User application programs.

v Application programs are written to meet the exact requirement.

v User application program may be written using one of these packages or

programming languages

Important categories of software packages available are

· Database management

· Spreadsheet software

· Word processing, Desktop publishing and Presentation software.

· Multimedia software

· Data communication software

· Statistical and operational research software

· Categories of a Application software

Extend the capability of operating systems to provide specialized services to

Enable the computer to solve a specific data processing task.

2 categories of application software

written software packages

application programs.

Application programs are written to meet the exact requirement.

User application program may be written using one of these packages or

programming languages.

Important categories of software packages available are

Database management software

Spreadsheet software

Word processing, Desktop publishing and Presentation software.

Multimedia software

Data communication software

Statistical and operational research software

Categories of a Application software

Extend the capability of operating systems to provide specialized services to

User application program may be written using one of these packages or

Word processing, Desktop publishing and Presentation software.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 35: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

2) Building blocks for simple programs

v Building blocks for programs are

· Sequential control

· Selection control

· Repetition

These are easy to construct any algorithm.

1. Sequential Control

· Steps of an algorithm are carried out in a sequential manner where each step is executed

exactly once.

· Example: Convertion of farenheit into celcius

· Algorithm

a. Read the temperature in Fahrenheit

b. Apply conversion formula

c. Display result in degree Celsius.

Description of an algorithm done using pseudo code.

Pseudo code: It is a mixture of English(human language), symbols and selected features

commonly used in programming languages.

Read degree- farenheit

Degree-celsius=(5/9)*(degree=farenheit-32)

Display degree-celcius

· Describing an algorithm can also be done by graphical representation.

· Graphical representation of an algorithm is a flowchart.

2. Selection control:

v Only one of a number of alternative steps is executed

v Eg Student result generation

Read grade

If(grade>=95)

Then destination

Else

Try to get it

v With if only used one condition checked.

v If else 2 condition checked.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 36: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

v If else if else then more than 2 conditions are checked.

v For checking more than 2 conditions we can use switch case.

v Example: Read result

Case(result>=90)

Print ‘a’

Case(result>=80)

Print ‘b’

Case(result>=70)

Print ‘c’

Case(result>=60)

Print ‘d’

Case (result<60)

Print ‘f’

· This has more alternatives. According to the alternatives the structures are chosen.

3. Repitition:

· One or more steps are performed repeatedly under a condition.

· Example: Compute the average of 10 numbers.

Ex 1:

Total=0

Average=0

For 1 to 10

Read number

Total=total+number

End for

Average=total/10

Ex 2:

For 1 to 10

Print “hai”

Ex 3:

Read 10 numbers

While (total<s)do

Read number

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 37: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Total=total+number

End do

3) Programming life cycle phase

· Programming is a problem solving activity.

· Good problem solver has potential to become a good performance.

· Business students solve problems with systems approach.

· Engineering and science students use engineering and scientific method.

· Programmers use the software development method.

Software development method:

· Specify the problem requirement

· Analyze the problem.

· Design the algorithm to solve the problem.

· Implement the algorithm

· Test and verify the completed program.

· Maintain and update the program.

[1] Specify the problem requirement:

· Forces to state the problem clearly and unambiguously.

· This gain a clear understanding and requirement for the solution.

· Objective is to eliminate unimportant aspects.

· More information to be calculated.

[2] Analysis:

· Involves identifying the problem

a. inputs

b. Outputs

c. Constraints on the solution

· Determine the required format in which output is displayed.

· Develop a list of problem variables and their relationship.

· It can be expressed as formulas.

· Problem statement-read very carefully

· Underline the phrases in the problem statement that identify input and output.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 38: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Compute and display the total cost of apples given the number of pounds of apples purchased

and the cost per pound of apples.

Problem Input: Quantity of apples purchased (in pounds)

Cost per pound of apples (in dollars per pound)

Problem output: Total cost of apples (in dollars)

Formula designed: General formula

Total cost=Unit cost ×Number of units.

· The processing of modeling a problem by extracting the essential variables and their

relationships is called abstraction.

[3]Design:-

· To solve a problem, list of steps called algorithm are designed.

· No need for every detail of problem in the beginning.

· Top-down design is used.

· List the major steps or sub-problems that are needed to solve the problem.

· Problem can be broken to sub problems called divide and conquer method.

· Generally any problem has the following sub-problems.

o Get the data.

o Perform the computation.

o Display the result.

· Attack the each problem individually.

· Algorithm refinement is used to perform breaking of large steps in to more detailed list of

steps.

· To desk check algorithm, carefully perform each algorithm step and verify the task of

algorithm like a computer.

· To save the time and effort to locate algorithm errors early in the problem solving

process.

[4]Implementation:-

· Involving in writing the program.

· It converts each algorithm step into one or more statements in a programming language.

Example:-

int x,y;

scanf(“%d”,&x);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 39: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

scanf(“%d”,&y);

X=x+y;

printf(“The Result is %d”,X);

[5]Testing:-

· To test the completed program to verify that it works as desired.

· Don’t rely on one test case.

· Test the program using different set of data for every situation.

[6]Maintenance:-

· Maintaining and updating the program involves modifying the program to resolve

previously undetected errors and to keep it up to date.

· Creating a program that is to read, understand and maintain is a discipline approach.

· Follow accepted program style guidelines.

4) Discuss pseudo code and flow charts in detail.

· Pseudocode is a simple way of writing programming code in English. Pseudocode is not

an actual programming language. It uses short phrases to write code for programs before

one actually create it in a specific language.

· An outline of a program, written in a form that can easily be converted into real

programming statements. For example, the pseudocode for finding given number odd or

even.

pseudo code for finding whether a given number is even or odd.

1) Input number 'X' from user

2) Divide the X by 2 and store its remainder As 'R'

3) if R is 0 then print 'X' is an even number

4) if R is not 0 then print 'X' is an odd number.

5) Exit

C Program for finding whether a given number is even or odd.

void main()

{

int x,r;

clrscr();

printf("Enter a number ");

scanf("%d", x);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 40: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

r = x/2;

if (r = 0)

printf("Given number is Even")

else

printf("Given number is Odd.")

getch();

}

Flowchart

Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing

program and explaining program to others.

Symbols Used In Flowchart Different symbols are used for different states in flowchart, For example: Input/

decision making has different symbols. The table below describes all the symbols that are used in

making flowchart

Symbol Purpose Flow line

Terminal(Stop/Start)

Input/Output

Processing

Desicion

On-page Connector

Off-page Connector

Predefined Process/Function

Examples of flowcharts in programming Flowchart to add two numbers

Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing

program and explaining program to others.

Different symbols are used for different states in flowchart, For example: Input/

decision making has different symbols. The table below describes all the symbols that are used in

Description Used to indicate the flow of logic by connecting symbols.

Used to represent start and end of flowchart.

Used for input and output operation.

Used for arithmetic operations and data-manipulations.

Used to represent the operation in which there are two alternatives, true and false.

Used to join different flow line

Used to connect flowchart portion on different page.

Used to represent a group of statements performing one processing task.

in programming

Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing

Different symbols are used for different states in flowchart, For example: Input/Output and

decision making has different symbols. The table below describes all the symbols that are used in

the flow of logic by connecting

represent start and end of flowchart.

manipulations.

Used to represent the operation in which there are two

Used to connect flowchart portion on different page.

Used to represent a group of statements performing one

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 41: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Though, flowchart are useful in efficient coding,

in very complicated in case of complex programs and often ignored.

Though, flowchart are useful in efficient coding, debugging and analysis of a program, drawing flowchart

in very complicated in case of complex programs and often ignored.

debugging and analysis of a program, drawing flowchart

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 42: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

5) Algorithm

In programming, algorithm is the set of well defined instruction in sequence to solve a

program. An algorithm should always have a clear stopping point.

Qualities of a good algorithm

· Inputs and outputs should be defined precisely.

· Each steps in algorithm should be clear and unambiguous.

· Algorithm should be most effective among many different ways to solve a problem.

· An algorithm shouldn't have computer code. Instead, the algorithm should be written in

such a way that, it can be used in similar programming languages.

Examples Of Algorithms In Programming

Algorithm to add two numbers entered by user.

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 5: Display sum

Step 6: Stop

Algorithm to find the largest among three different numbers entered by user.

Step 1: Start

Step 2: Declare variables a,b and c.

Step 3: Read variables a,b and c.

Step 4: If a>b

If a>c

Display a is the largest number.

Else

Display c is the largest number.

Else

If b>c

Display b is the largest number.

Else

Display c is the greatest number.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 43: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Step 5: Stop

Algorithm to find all roots of a quadratic equation ax2+bx+c=0.

Step 1: Start

Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;

Step 3: Calculate discriminant

D←b2-4ac

Step 4: If D≥0

r1←(-b+√D)/2a

r2←(-b-√D)/2a

Display r1 and r2 as roots.

Else

Calculate real part and imaginary part

rp←b/2a

ip←√(-D)/2a

Display rp+j(ip) and rp-j(ip) as roots

Step 5: Stop

An algorithm to find the factorial of a number entered by user.

Step 1: Start

Step 2: Declare variables n,factorial and i.

Step 3: Initialize variables

factorial←1

i←1

Step 4: Read value of n

Step 5: Repeats the steps until i=n

5.1: factorial←factorial*i

5.2: i←i+1

Step 6: Display factorial

Step 7: Stop

An algorithm to check whether a number entered by user is prime or not.

Step 1: Start

Step 2: Declare variables n,i,flag.

Step 3: Initialize variables

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 44: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

flag←1

i←2

Step 4: Read n from user.

Step 5: Repeats the steps until i<(n/2)

5.1 If remainder of n÷i equals 0

flag←0

Go to step 6

5.2 i←i+1

Step 6: If flag=0

Display n is not prime

else

Display n is prime

Step 7: Stop

Algorithm to find the Fibonacci series till term≤1000.

Step 1: Start

Step 2: Declare variables first_term,second_term and temp.

Step 3: Initialize variables first_term←0 second_term←1

Step 4: Display first_term and second_term

Step 5: Repeats the steps until second_term≤1000

5.1: temp←second_term

5.2: second_term←second_term+first term

5.3: first_term←temp

5.4: Display second_term

Step 6: Stop

Algorithm is not the computer code. Algorithm is just the instructions which give clear idea to

you idea to write the computer code.

6) Programming Languages

The different generations of languages

There are currently five generations of computer programming languages. In each generation, the

languages syntax has become easier to understand and more human-readable.

First generation languages (abbreviated as 1GL)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 45: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Represent the very early, primitive computer languages that consisted entirely of 1's and 0's - the

actual language that the computer understands (machine language).

Second generation languages (2GL)

· Represent a step up from the first generation languages.

· Allow for the use of symbolic names instead of just numbers.

· Second generation languages are known as assembly languages.

· Code written in an assembly language is converted into machine language (1GL).

Third generation languages (3GL)

· With the languages introduced by the third generation of computer programming, words

and commands (instead of just symbols and numbers) were being used.

· These languages therefore, had syntax that was much easier to understand.

· Third generation languages are known as "high level languages" and include C, C++,

Java, and Javascript, among others.

Fourth generation languages (4GL)

· The syntax used in 4GL is very close to human language, an improvement from the

previous generation of languages.

· 4GL languages are typically used to access databases and include SQL and ColdFusion,

among others.

Fifth generation languages (5GL)

· Fifth generation languages are currently being used for neural networks.

· A nueral network is a form of artifical intelligence that attempts to imitate how the

human mind works.

· Human makes the computer to think.

Classification of Programming languages

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 46: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Imperative Programming

· Control flow in imperative programming is

compuation takes place, step by step.

· Each step affects the global

result = []

i = 0

start:

numPeople = length(people)

if i >= numPeople goto end

p = people[i]

nameLength = length(p.name)

if nameLength <= 5 goto next

upperName = toUpper(p.name)

addToList(result, upperName)

next:

i = i + 1

goto start

end:

return sort(result)

Structured Programming

· Structured programming is a kind of imperative programming where

defined by nested loops, conditionals, and subroutines, rather than via gotos. Variables

are generally local to blocks (have lexical scope).

Control flow in imperative programming is explicit: commands show

compuation takes place, step by step.

Each step affects the global state of the computation.

Structured programming is a kind of imperative programming where the control flow is

defined by nested loops, conditionals, and subroutines, rather than via gotos. Variables

are generally local to blocks (have lexical scope).

: commands show how the

the control flow is

defined by nested loops, conditionals, and subroutines, rather than via gotos. Variables

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 47: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

result = [];

for i = 0; i < length(people); i++ {

p = people[i];

if length(p.name)) > 5 {

addToList(result, toUpper(p.name));

}

}

return sort(result);

· Early languages emphasizing structured programming: Algol 60, PL/I, Algol 68, Pascal,

C, Ada 83, Modula, Modula-2. Structured programming as a discipline is sometimes

though to have been started by a famous letter by Edsger Dijkstra entitled Go to

Statement Considered Harmful.

Object Oriented Programming

· OOP is based on the sending of messages to objects. Objects respond to messages by

performing operations. Messages can have arguments, so "sending messages" looks a lot

like calling subroutines.

· A society of objects, each with their own "local memory" and own set of operations has a

different feel than the "monolithic processor and single shared memory" feel of non

object oriented languages.

result = []

for p in people {

if p.name.length > 5 {

result.add(p.name.toUpper);

}

}

return result.sort;

· The first object oriented language was Simula-67; Smalltalk followed soon after as the

first "pure" object-oriented language. Many languages designed from the 1980s to the

present have been object-oriented, notably C++, CLOS (object system of Common Lisp),

Eiffel, Modula-3, Ada 95, Java, C#, Ruby.

· Declarative Programming

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 48: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Control flow in declarative programming is implicit: the programmer states only what the

result should look like, not how to obtain it.

select upper(name)

from people

where length(name) > 5

order by name

· No loops, no assignments, etc. Whatever engine that interprets this code is just supposed

go get the desired information, and can use whatever approach it wants. (The logic and

relational paradigms are generally declarative as well.)

Functional Programming

In functional programming control flow is expressed by combining function calls, rather than by assigning values to variables.

let( f, fun( people, if(equals(people, emptylist), emptylist, if(greater(length(name(head(people))), 5), append(to_upper(name(head(people))), f(tail(people))), f(tail(people))))), sort(f(people)))

Of course, there's usually syntactic sugar

let fun f [] = [] | f (p :: ps) = if p.name.length() > 5 then p.name.to_upper()::(f ps) else (f ps) in sort(f(people))

The real power of this paradigm comes from passing functions to functions (and returning functions from functions).

sort( filter((λs. s.length() > 5), map((λp. p.name.to_upper()), people)

Logic and Constraint Programming Logic and constraint programming are two paradigms in which programs are built by setting up relations that specify facts and inference rules, and asking whether or not

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 49: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

something is true (i.e. specifying a goal.) Unification and backtracking to find solutions (i.e. satisfy goals) takes place automatically. Languages that emphasize this paradigm: Prolog, GHC, Parlog, Vulcan, Polka, Mercury, Fnil.

7) Compiler-Interpreter, Loader and Linker - Program execution

Compiler · "A compiler translates the high-level source programs into target programs in machine

languages for the specific hardware. Once the target program is generated, the user can

execute the program.

· A compiler reads analyses and translates code into either an object file or a list of error

messages.

A compiler for a language generally has several different stages as it processes the

input.

1. Preprocessing

· During the preprocessing stage, comments, macros, and directives are processed.

Comments are removed from the source file. This greatly simplifies the later stages.

· If the language supports macros, the macros are replaced with the equivalent text.

· For example, C and C++ support macros using the #define directive. So if a macro were

defined for pi as: #define PI 3.1415927

· Any time the preprocessor encountered the word PI, it would replace PI with 3.1415927

and process the resulting text.

· The preprocessor may also replace special strings with other characters. In C and C++,

the preprocessor recognizes the \ character as an escape code, and will replace the escape

sequence with a special character. For example \t is the escape code for a tab, so \t would

be replaced at this stage with a tab character.

2. Lexical analysis

· It is the process of breaking down the source files into key words, constants, identifiers,

operators and other simple tokens. A token is the smallest piece of text that the language

defines.

C tokens:

· C tokens are the basic buildings blocks in C language which are constructed together to

write a C program.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 50: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Each and every smallest individual units in a C program are known as C tokens.

· C tokens are of six types. They are,

§ Keywords (eg: int, while),

§ Identifiers (eg: main, total),

§ Constants (eg: 10, 20),

§ Strings (eg: “total”, “hello”),

§ Special symbols (eg: (), {}),

§ Operators (eg: +, /,-,*)

3. Syntactical analysis

· It is the process of combining the tokens into well-formed expressions, statements, and

programs.

· Each language has specific rules about the structure of a program--called the grammar or

syntax. Just like English grammar, it specifies how things may be put together. In

English, a simple sentence is: subject, verb, predicate.

· In C or C++ an if statement is: if ( expression ) statement

· The syntactical analysis checks that the syntax is correct, but doesn't enforce that it

makes sense. In English, a subject could be: Pants, the verb: are, the predicate: a kind of

car. This would yield: Pants are a kind of car. Which is a sentence, but doesn't make

much sense.

· In C or C++, a constant can be used in an expression: so the expression:

float x = "This is red"++

· Is syntactically valid, but doesn't make sense because a float number cannot have

string assigned to it, and a string cannot be incremented.

4. Semantic analysis

· It is the process of examining the types and values of the statements used to make sure

they make sense.

· During the semantic analysis, the types, values, and other required information about

statements are recorded, checked, and transformed as appropriate to make sure the

program makes sense.

· For C/C++ in the line: float x = "This is red"++

o The semantic analysis would reveal the types do not match and cannot be made to

match, so the statement would be rejected and an error reported.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 51: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· While in the statement: float y = 5 + 3.0;

o The semantically analysis would reveal that 5 is an integer, and 3.0 is a double, and also that the rules for the language allow 5 to be converted to a double, so the addition could be done, so the expression would then be transformed to a double and the addition performed. Then, the compiler would recognize y as a float, and perform another conversion from the double 8.0 to a float and process the assignment.

5. Intermediate code generation

· Depending on the compiler, this step may be skipped, and instead the program may be

translated directly into the target language (usually machine object code). If this step is

implemented, the compiler designers also design a machine independent language of their

own that is close to machine language and easily translated into machine language for

any number of different computers.

· The purpose of this step is to allow the compiler writers to support different target

computers and different languages with a minimum of effort.

· The part of the compiler which deals with processing the source files, analyzing the

language and generating the intermediate code is called the front end, while the process

of optimizing and converting the intermediate code into the target language is called the

back end.

6. Code optimization · During this process the code generated is analyzed and improved for efficiency. The

compiler analyzes the code to see if improvements can be made to the intermediate code

that couldn't be made earlier.

· For example, some languages like Pascal do not allow pointers, while all machine

languages do. When accessing arrays, it is more efficient to use pointers, so the code

optimizer may detect this case and internally use pointers.

7. Code generation · Finally, after the intermediate code has been generated and optimized, the compiler will

generate code for the specific target language. Almost always this is machine code for a

particular target machine.

· Also, it us usually not the final machine code, but is instead object code, which contains

all the instructions, but not all of the final memory addresses have been determined.

· A subsequent program, called a linker is used to combine several different object code

files into the final executable program.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 52: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Interpreter

· An Interpreter reads, and translates code line by line.

· A linker combines one or more object files and possible some library code into

executable, some library or a list of error messages.

· A loader reads the executable code into

to run the program resulting in a running program or an error message (or both).

· During program execution, constructs and statements are executed in a prescribed order.

· Execution in computer and software engineering

virtual machine performs the instructions of a

program trigger sequences of simple actions on the executing machine. Those actions

produce effects according to the

· Programs for a computer may execute in a

user may type commands

"commands" are simply programs, wh

r reads, and translates code line by line.

combines one or more object files and possible some library code into

executable, some library or a list of error messages.

reads the executable code into memory does some address translation and tries

to run the program resulting in a running program or an error message (or both).

, constructs and statements are executed in a prescribed order.

software engineering is the process by which a

performs the instructions of a computer program. The instructions in the

program trigger sequences of simple actions on the executing machine. Those actions

produce effects according to the semantics of the instructions in the program.

Programs for a computer may execute in a batch process without human interaction, or a

in an interactive session of an interpreter. In this case the

"commands" are simply programs, whose execution is chained together.

combines one or more object files and possible some library code into some

does some address translation and tries

to run the program resulting in a running program or an error message (or both).

, constructs and statements are executed in a prescribed order.

is the process by which a computer or a

. The instructions in the

program trigger sequences of simple actions on the executing machine. Those actions

of the instructions in the program.

human interaction, or a

. In this case the

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 53: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

C is a general-purpose high level language that was originally developed by Dennis Ritchie

for the Unix operating system. It was first implemented on the Digital

PDP-11 computer in 1972.

The Unix operating system and virtually all Unix applications are written in the C language. C

has now become a widely used professional language for various reasons.

· Easy to learn

· Structured language

· It produces efficient programs.

· It can handle low-level activities.

· It can be compiled on a variety of computers.

Facts about C

· C was invented to write an operating system called UNIX.

UNIT III

Introduction to C

purpose high level language that was originally developed by Dennis Ritchie

for the Unix operating system. It was first implemented on the Digital Equipment

ystem and virtually all Unix applications are written in the C language. C

has now become a widely used professional language for various reasons.

It produces efficient programs.

level activities.

be compiled on a variety of computers.

C was invented to write an operating system called UNIX.

purpose high level language that was originally developed by Dennis Ritchie

Equipment Corporation

ystem and virtually all Unix applications are written in the C language. C

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 54: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· C is a successor of B language which was introduced around 1970

· The language was formalized in 1988 by the American National Standard Institute

(ANSI).

· By 1973 UNIX OS almost totally written in C.

· Today C is the most widely used System Programming Language.

· Most of the state of the art software have been implemented using C

Uses of C

C was initially used for system development work, in particular the programs that make-up

the operating system. C was adoped as a system development language because it produces code

that runs nearly as fast as code written in assembly language. Some examples of the use of C

might be:

· Operating Systems

· Language Compilers

· Assemblers

· Text Editors

· Print Spoolers

· Network Drivers

· Modern Programs

· Data Bases

· Language Interpreters

· Utilities

C Program File

All the C programs are writen into text files with extension ".c" for example hello.c. You can

use "vi" editor to write your C program into a file.

This tutorial assumes that you know how to edit a text file and how to write programming

insturctions inside a program file.

1. IDENTIFIERS

Identifiers are names given to C entities, such as variables, functions, structures etc. Identifier

is created to give unique name to C entities to identify it during the execution of program. For

example:

int money;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 55: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

int mango_tree;

Identifier names must be a sequence of letters and digits and must begin with a letter.

· The underscore character (_) is also permitted in identifiers. It is usually as a link

between two words in long identifiers.

· Names should not be the same as a keyword.

· C is a case sensitive (i.e. upper and lower case letters are treated differently). Thus the

names price, Price and PRICE denote different identifier.

Valid examples are:

City, Age, basic_pay, result, date_of_birth, Mark, num1, num2

The following identifiers are invalid:

Invalid Identifiers Reason For Invalidity

Basic Pay Blank space is not allowed

1price Must start with a letter

$amount Special characters is not allowed

break break is a keyword

2. KEYWORDS:

Keywords are the reserved words used in programming. Each keywords has fixed meaning

and that cannot be changed by user. For example:

int money;

Here, int is a keyword that indicates, 'money' is of type integer.

As, C programming is case sensitive, all keywords must be written in lowercase. Here is the

list of all keywords predefined by ASCII C.

Keywords in C Language

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 56: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

default goto sizeof volatile

const float short unsigned

3. VARIABLES

Variables are memory location in computer's memory to store data. To indicate the memory

location, each variable should be given a unique name called identifier. Variable names are just

the symbolic representation of a memory location. Examples of variable name: sum, car_no,

count etc.

int num;

Here, num is a variable of integer type.

Rules for writing variable name in C

i. Variable name can be composed of letters (both uppercase and lowercase letters), digits

and underscore '_' only.

ii. The first letter of a variable should be either a letter or an underscore. But, it is

discouraged to start variable name with an underscore though it is legal. It is because,

variable name that starts with underscore can conflict with system names and compiler

may complain.

iii. There is no rule for the length of length of a variable. However, the first 31 characters

of a variable are discriminated by the compiler. So, the first 31 letters of two variables in a

program should be different.

In C programming, declare variable before using it in the program.

Declaration of variable

C has a concept of 'data types' which are used to define a variable before its use. The

definition of a variable will assign storage for the variable and define the type of data that will

be held in the location.

data_type V1, V2, . . . Vn ;

4. DATA TYPES

In C, variable (data) should be declared before it can be used in program. Data types are the

keywords, which are used for assigning a type to a variable.

Data types in C

· Fundamental Data Types

o Integer types

o Floating Type

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 57: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

o Character types

· Derived Data Types

o Arrays

o Pointers

o Structures

o Enumeration

Syntax for declaration of a variable

data_type variable_name;

i. Integer data types

Keyword int is used for declaring the variable with integer type. For example:

int var1;

ii. Floating types

Variables of floating types can hold real values(numbers) such as: 2.34, -9.382 etc. Keywords

either float or double is used for declaring floating type variable. For example:

float var2;

double var3;

Here, both var2 and var3 are floating type variables.

In C, floating values can be represented in exponential form as well. For example:

float var3=22.442e2

iii. Character types

Keyword char is used for declaring the variable of character type. For example:

char var4='h';

Here, var4 is a variable of type character which is storing a character 'h'.

The size of char is 1 byte. The character data type consists of ASCII characters. Each character is

given a specific value. For example:

For, 'a', value =97

For, 'b', value=98

For, 'A', value=65

For, '&', value=33

For, '2', value=49

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 58: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Data Type Size Range

char 1 byte -128 to 127

Int 2 bytes -32,768 to 32,767

float 4 bytes 3.4e-38 to 3.4e+38

double 8 bytes 1.7e-308 to 1.7e+308

Integer Data Type

Type Length Range

Unsigned int (or)

unsigned short int

16 bits 0 to 65,535

int (or)

short int (or)

signed int (or)

signed short int

16 bits

-32,768 to 32,767

Unsigned long (or)

Unsigned long int

32 bits 0 to 4,294,967,295

long (or)

long int (or)

signed long int

32 bits

-2,147,483,648 to 2,147,483,647

Floating point Data Type

Type Length Range

float 32 bits 3.4e-38 to 3.4e+38

double 64 bits 1.7e-308 to 1.7e+308

long double 80 bits 3.4e-4932 to 1.1e+4932

Character Data Type

Type Length Range

unsigned char 8 bits 0 to 255

char (or ) signed char 8 bits -128 to 127

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 59: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

5. CONSTANTS

Constants refer to fixed values that do not change during the execution of a program. Figure

below shows the various types of constants available in C:

Integer constants

Integer constants are the numeric constants(constant associated with number) without any

fractional part or exponential part. There are three types of integer constants in C language:

decimal constant(base 10), octal constant(base 8) and hexadecimal constant(base 16) .

Decimal digits: 0 1 2 3 4 5 6 7 8 9

Octal digits: 0 1 2 3 4 5 6 7

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

For example:

Decimal constants: 0, -9, 22 etc

Octal constants: 021, 077, 033 etc

Hexadecimal constants: 0x7f, 0x2a, 0x521 etc

Floating-point constants

Floating point constants are the numeric constants that has either fractional form or exponent

form. For example:

-2.0

0.0000234

-0.22E-5

Note:Here, E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022.

Constants

Numeric

constant

Character

constant

Integer constant Real constant Single character

constant

String constant

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 60: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Character constants

Character constants are the constant which use single quotation around characters. For

example: 'a', 'l', 'm', 'F' etc.

Escape Sequences

Sometimes, it is necessary to use newline(enter), tab, quotation mark etc. in the program

which either cannot be typed or has special meaning in C programming. In such cases, escape

sequence are used. For example: \n is used for newline. The backslash( \ ) causes "escape" from

the normal way the characters are interpreted by the compiler.

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark

\0 Null character

String constants

String constants are the constants which are enclosed in a pair of double-quote marks. For

example:

"good" //string constant

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 61: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

"" //null string constant

" " //string constant of six white space

"x" //string constant having single character.

"Earth is round\n" //prints string with newline

Enumeration constants

Keyword enum is used to declare enumeration types. For example:

enum color {yellow, green, black, white};

Here, the variable name is color and yellow, green, black and white are the enumeration

constants having value 0, 1, 2 and 3 respectively by default.

6. INPUT AND OUTPUT FUNCTIONS

ANSI standard has defined many library functions for input and output in C language.

Functions printf() and scanf() are the most commonly used to display out and take input

respectively. Let us consider an example:

scanf(“control strings”, arg1, arg2, . . . argn),

Example

#include<stdio.h>

int main()

{

int c=5;

printf("Number=%d",c);

return 0;

}

Output

Number=5

Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this

conversion format string matches with remaining argument,i.e, c in this case, value of c is

displayed.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 62: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf(“control strings”, arg1, arg2, . . . argn) ;

Example

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

int main()

{

printf("C Programming"); //displays the content inside quotation

return 0;

}

Output

C Programming

Explanation of how this program works

· Every program starts from main() function.

· printf() is a library function to display output which only works if #include<stdio.h>is

included at the beginning.

· Here, stdio.h is a header file (standard input output header file) and #include is command

to paste the code from the header file when necessary. When compiler encounters printf()

function and doesn't find stdio.h header file, compiler shows error.

· Code return 0; indicates the end of program. You can ignore this statement but, it is good

programming practice to use return 0;.

Format

Specifier

Type of

Argument

Input

%c Character Reads a single character

%d or %i Integer Reads a decimal integer

%e or %E or

%f or %g or

%G

Floating point Reads a floating point value

%hd or %hi Short integer Reads decimal short integer

%hu Short integer Reads decimal unsigned short integer

%ld or %li Long integer Reads decimal long integer

%le or %lf or Double Reads signed double

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 63: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

%lg

%Le or %Lf or

%Lg

Long double Reads signed long double

%lo Long integer Reads an octal long integer

%lu Long integer Reads decimal unsigned long integer

%lx Long integer Reads hexadecimal long integer

%o Octal integer Reads an unsigned octal integer

%s Sequence of

characters

Reads a string

%u Integer Reads an unsigned decimal integer

%x or %X Hexadecimal

integer

Reads a unsigned hexadecimal integer

ESCAPE SEQUENCES (BACKSLASH CHARACTER CONSTANTS)

ASCII Value Escape

Sequences Meaning

000 \0 Null

007 \a Audible alter (bell)

008 \b Backspace

009 \t Horizontal tab

010 \n New line

011 \v Vertical tab

012 \f Form feed

013 \r Carriage return

034 \” Double quote

039 \’ Single quote

063 \? Question mark

092 \\ Backslash

Others

getchar():getchar() is used to get or read the input (i.e a single character) at run time.

getch(): getch() is used to get a character from console but does not echo to the screen

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 64: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

getche(): reads a single character from the keyboard and echoes it to the current text

window, using direct video or BIOS

gets(): reads characters from the standard input stream until an end-of-line or character

or character sequence is seen, or until the end of file, whichever comes first.

putchar() : The C library function int putchar(int char) writes a character (an unsigned

char) specified by the argument char to stdout.

puts() The C library function int puts(const char *str) writes a string to stdout up to but

not including the null character. A newline character is appended to the output.

7. OPERATORS: Operators are the symbol which operates on value or a variable.

For example: + is a operator to perform addition.

1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operator

5. Increment and decrement operators

6. Conditional operators

7. Bitwise operators

8. Comma operator

9. sizeof operator

S.no Types of Operators Description

1 Arithmetic_operators

These are used to perform mathematical calculations like

addition, subtraction, multiplication, division and

modulus

2 Assignment operators

These are used to assign the values for the variables in C

programs.

3 Relational operators

These operators are used to compare the value of two

variables.

4 Logical operators

These operators are used to perform logical operations on

the given two variables.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 65: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

5 Bit wise operators

These operators are used to perform bit operations on

given two variables.

6 Conditional (ternary)

operators

Conditional operators return one value if condition is true

and returns another value is condition is false.

7 Increment / decrement

operators

These operators are used to either increase or decrease

the value of the variable by one.

8 Special operators &, *, sizeof( ) and ternary operators

Arithmetic Operators:

Operator Meaning

+ Addition or unary plus

- Subtraction or unary minus

* Multiplication

/ Division

% Modulo division or remainder after division

Relational Operators

Operator Meaning

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

!= Not equal to

Logical Operators

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Assignment Operator =,+=,-=,*=,/=,%=

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 66: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Increment and Decrement Operators

Conditional Operators

Bit wise Operators

Operator

&

|

^

<<

>>

~

8. INITIALIZING, STATEM

Initialization is the process assigning a value to a variable during variable declara

int i=0;

Statement : Every line in a program. Eg. Int a,b;

Expression: The expression may consist of a single entity, such as a constant or variable, or it

may consist of some combination of such entities, interconnected by one or more

C=a+b;

Lvalues means address of the variable

Rvalues means value of the variable.

9. TYPEDEF

C automatically converts any intermediated values to the proper type so that the

expression can be evaluated without losing any significance. This auto

known implicit type conversion

Type casting is a way to convert a variable from one data type to another data type. For

example, if you want to store a long va

int. One can convert values from one type to another explicitly using the

follows:

(type_name) expression

Increment and Decrement Operators ++,--

exp1 ? exp2 : exp3 ;

Meaning

Bitwise AND

Bitwise OR

Bitwise XOR

Shift left

Shift right

One’s complement

INITIALIZING, STATEMENT, EXPRESSION, LVALUES AND RVALUES

assigning a value to a variable during variable declara

Every line in a program. Eg. Int a,b;

The expression may consist of a single entity, such as a constant or variable, or it

may consist of some combination of such entities, interconnected by one or more

means address of the variable

means value of the variable.

C automatically converts any intermediated values to the proper type so that the

expression can be evaluated without losing any significance. This automatic conversion is

Type casting is a way to convert a variable from one data type to another data type. For

example, if you want to store a long value into a simple integer then one can type cast long to

values from one type to another explicitly using the cast operator

LUES AND RVALUES

assigning a value to a variable during variable declaration. (eg)

The expression may consist of a single entity, such as a constant or variable, or it

may consist of some combination of such entities, interconnected by one or more operators..

C automatically converts any intermediated values to the proper type so that the

matic conversion is

Type casting is a way to convert a variable from one data type to another data type. For

can type cast long to

cast operator as

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 67: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Consider the following example where the cast operator causes the division of one integer

variable by another to be performed as a floating-point operation:

#include <stdio.h>

main()

{

int sum = 17, count = 5;

double mean;

mean = (double) sum / count;

printf("Value of mean : %f\n", mean );}

10. CONTROL STATEMENTS

Types

1. Sequential control structure

2. Selective control structure

3. Iterative control structure

Sequential Control Structure

The normal flow of control of all programs is sequential. In sequential structure, a sequence

of programs statements are executed one after another in the order in which they are placed. Both

selection and repetition statements allow allow the programmer to alter the normal sequential

flow of control.

Sequential programming can also be called linear programming. The sequential programs

are non-modular in nature. That is, reusability of code is not possible. Thus, they are difficult to

maintain and understand. Examples of sequence control structure statements are, the program

will have statements that are placed sequentially and there is no decision involved in the process.

Also, the program does not require a specific task to be repeated over and over again.

Selective Control Structure (or) Decision Control Structure

The selective structure allows the usual sequential order of execution to be modified. It

consists of a test for a condition followed by alternative paths that the program can follow. The

program selects one of the alternative paths depending upon the result of the test for condition.

Examples of selective control structures statements are :

1. Simple if statement

2. if . . . else statement

3. Nested if . . . else statement

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 68: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

4. else if ladder

5. switch . . . case . . .default statement

Iterative Control Structure (or) Loop Control Structure

The iterative structure provides the ability to go back and repeat a set of statements.

Iterative structure is otherwise referred to as repetitive structure. Examples of iterative control

structure statements are :

1. while statement

2. do . . . while statement

3. for statement

if STATEMENTS

C allows decisions to be made by evaluating a given expression as true or false. Such an

expression involves the relational and logical operators. Depending on the outcome of the

decision, program execution proceeds in one direction or another. The C statement that enables

these tests to be made is called the if statements.

The if statements may be implemented in different forms depending on the complexity of

conditions to be tested. They are :

1. Simple if statement

2. if . . . else statement

3. Nested if . . . else statement

4. else if ladder

5. The if, if...else and nested if...else statement are used to make one-time decisions

in C Programming, that is, to execute some code/s and ignore some code/s

depending upon the test expression.

Simple if statement

if (test expression) {

statement/s to be executed if test expression is true;

}

The if statement checks whether the text expression inside parenthesis ( ) is true or not. If the test

expression is true, statement/s inside the body of if statement is executed but if test is false,

statement/s inside body of if is ignored.

Example 1: C if statement

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 69: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Write a C program to print the number entered by user only if the number entered is

negative.

#include <stdio.h>

int main(){

int num;

printf("Enter a number to check.\n");

scanf("%d",&num);

if(num<0) { /* checking whether number is less than 0 or not. */

printf("Number = %d\n",num);

}

/*If test condition is true, statement above will be executed, otherwise it will not be executed */

printf("The if statement in C programming is easy.");

return 0;

}

Output 1

Enter a number to check.

-2

Number = -2

The if statement in C programming is easy.

When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2 is

displayed in the screen.

Output 2

Enter a number to check.

5

The if statement in C programming is easy.

When the user enters 5 then, the test expression (num<0) becomes false. So, the statement/s

inside body of if is skipped and only the statement below it is executed.

C if...else statement

The if...else statement is used if the programmer wants to execute some statement/s when the test

expression is true and execute some other statement/s if the test expression is false.

Syntax of if...else

if (test expression) {

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 70: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

statements to be executed if test expression is true;

}

else {

statements to be executed if test expression is false;

}

Flowchart of if statement

Flowchart of if...else statement

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 71: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Example 2: C if...else statement

Write a C program to check whether a number entered by user is even or odd

#include <stdio.h>

int main(){

int num;

printf("Enter a number you want to check.\n");

scanf("%d",&num);

if((num%2)==0) //checking whether remainder is 0 or not.

printf("%d is even.",num);

else

printf("%d is odd.",num);

return 0;

}

Output 1

Enter a number you want to check.

25

25 is odd.

Output 2

Enter a number you want to check.

2

2 is even.

Nested if...else statement (if...elseif....else Statement)

The nested if...else statement is used when program requires more than one test

expression.

Syntax of nested if...else statement.

if (test expression1){

statement/s to be executed if test expression1 is true;

}

else if(test expression2) {

statement/s to be executed if test expression1 is false and 2 is true;

}

else if (test expression 3) {

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 72: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

statement/s to be executed if text expression1 and 2 are false and 3 is true;

}

else {

statements to be executed if all test expressions are false;

}

How nested if...else works?

The nested if...else statement has more than one test expression. If the first test expression is true,

it executes the code inside the braces{ } just below it. But if the first test expression is false, it

checks the second test expression. If the second test expression is true, it executes the statement/s

inside the braces{ } just below it. This process continues. If all the test expression are false,

code/s inside else is executed and the control of program jumps below the nested if...else

The ANSI standard specifies that 15 levels of nesting may be continued.

Example 3: C nested if else statement

Write a C program to relate two integers entered by user using = or > or < sign.

#include <stdio.h>

int main(){

int numb1, numb2;

printf("Enter two integers to check\n");

scanf("%d %d",&numb1,&numb2);

if(numb1==numb2) //checking whether two integers are equal.

printf("Result: %d = %d",numb1,numb2);

else

if(numb1>numb2) //checking whether numb1 is greater than numb2.

printf("Result: %d > %d",numb1,numb2);

else

printf("Result: %d > %d",numb2,numb1);

return 0;

}

Output 1

Enter two integers to check.

5

3

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 73: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Result: 5 > 3

Output 2

Enter two integers to check.

-4

-4

Result: -4 = -4

switch STATEMENT

Decision making are needed when, the program encounters the situation to choose a particular

statement among many statements. If a programmer has to choose one block of statement among

many alternatives, nested if...else can be used but, this makes programming logic complex. This

type of problem can be handled in C programming using switch statement.

Syntax of switch...case

switch (n) {

case constant1:

code/s to be executed if n equals to constant1;

break;

case constant2:

code/s to be executed if n equals to constant2;

break;

.

.

.

default:

code/s to be executed if n doesn't match to any cases;

}

The value of n is either an integer or a character in above syntax. If the value of n matches

constant in case, the relevant codes are executed and control moves out of the switch statement.

If the n doesn't matches any of the constant in case, then the default codes are executed and

control moves out of switch statement.

Example of switch...case statement

Write a program that asks user an arithmetic operator('+','-','*' or '/') and two

operands and perform the corresponding calculation on the operands.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 74: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

/* C program to demonstrate the working of switch...case statement */

/* C Program to create a simple calculator for addition, subtraction,

multiplication and division */

# include <stdio.h>

int main() {

char o;

float num1,num2;

printf("Select an operator either + or - or * or / \n");

scanf("%c",&o);

printf("Enter two operands: ");

scanf("%f%f",&num1,&num2);

switch(o) {

case '+':

printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);

break;

case '-':

printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);

break;

case '*':

printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);

break;

case '/':

printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);

break;

default:

/* If operator is other than +, -, * or /, error message is shown */

printf("Error! operator is not correct");

break;

}

return 0;

}

Output

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 75: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Enter operator either + or - or * or /

*

Enter two operands: 2.3

4.5

2.3 * 4.5 = 10.3

The break statement at the end of each case cause switch statement to exit. If break statement is

not used, all statements below that case statement are also executed.

goto STATEMENT

The goto statement is used to alter the normal sequence of program execution by

unconditionally transferring control to some part of the program. The syntax is :

goto label :

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 76: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Where label is an identifier used to label the target statement to which the control would

be transferred. Control may be transferred to any other statement within the current function. The

target function must be labeled followed by a colon. The syntax is :

label : statement ;

Example of goto statement

/* C program to demonstrate the working of goto statement. */

/* This program calculates the average of numbers entered by user. */

/* If user enters negative number, it ignores that number and

calculates the average of number entered before it.*/

# include <stdio.h>

int main(){

float num,average,sum;

int i,n;

printf("Maximum no. of inputs: ");

scanf("%d",&n);

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

printf("Enter n%d: ",i);

scanf("%f",&num);

if(num<0.0)

goto jump; /* control of the program moves to label jump */

sum=sum+num;

}

jump:

average=sum/(i-1);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 77: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf("Average: %.2f",average);

return 0;

}

Output

Maximum no. of inputs: 4

Enter n1: 1.5

Enter n2: 12.5

Enter n3: 7.2

Enter n4: -1

Average: 7.07

Though goto statement is included in ANSI standard of C, use of goto statement should be

reduced as much as possible in a program.

Reasons to avoid goto statement

Though, using goto statement give power to jump to any part of program, using goto

statement makes the logic of the program complex and tangled. In modern programming, goto

statement is considered a harmful construct and a bad programming practice.

The goto statement can be replaced in most of C program with the use of break and

continue statements. In fact, any program in C programming can be perfectly written without the

use of goto statement. All programmer should try to avoid goto statement as possible as they can.

C programming loops

Loops causes program to execute the certain block of code repeatedly until some

conditions are satisfied, i.e., loops are used in performing repetitive work in programming.

Suppose you want to execute some code/s 10 times. You can perform it by writing that

code/s only one time and repeat the execution 10 times using loop.

There are 3 types of loops in C programming:

1. for loop

2. while loop

3. do...while loop

for loop

Loops cause program to execute the certain block of code repeatedly until test condition

is false. Loops are used in performing repetitive task in programming.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 78: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

for Loop Syntax

for(initialization statement; test expression; update statement) {

code/s to be executed;

}

loop works in C programming as follows:

The initialization statement is executed only once at the beginning of the for loop. Then

the test expression is checked by the program. If the test expression is false, for loop is

terminated. But if test expression is true then the code/s inside body of for loop is executed and

then update expression is updated. This process repeats until test expression is false.

This flowchart describes the working of for loop in C programming.

for loop example

Write a program to find the sum of first n natural numbers where n is entered by

user. Note: 1,2,3... are called natural numbers.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 79: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

#include <stdio.h>

int main(){

int n, count, sum=0;

printf("Enter the value of n.\n");

scanf("%d",&n);

for(count=1;count<=n;++count) //for loop terminates if count>n

{

sum+=count; /* this statement is equivalent to sum=sum+count */

}

printf("Sum=%d",sum);

return 0;

}

Output

Enter the value of n.

19

Sum=190

In this program, the user is asked to enter the value of n. Suppose you entered 19 then,

count is initialized to 1 at first. Then, the test expression in the for loop,i.e., (count<= n)

becomes true. So, the code in the body of for loop is executed which makes sum to 1. Then, the

expression ++count is executed and again the test expression is checked, which becomes true.

Again, the body of for loop is executed which makes sum to 3 and this process continues. When

count is 20, the test condition becomes false and the for loop is terminated.

while loop

The while loop checks whether the test expression is true or not. If it is true, code/s

inside the body of while loop is executed,that is, code/s inside the braces { } are executed. Then

again the test expression is checked whether test expression is true or not. This process continues

until the test expression becomes false.

Syntax of while loop

while (test expression) {

statement/s to be executed. }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 80: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Example of while loop

Write a C program to find the factorial of a number, where the number is entered

by user. (Hints: factorial of n = 1*2*3*...*n

/*C program to demonstrate the working of while loop*/

#include <stdio.h>

int main(){

int number,factorial;

printf("Enter a number.\n");

scanf("%d",&number);

factorial=1;

while (number>0){ /* while loop continues util test condition number>0 is true */

factorial=factorial*number;

--number;

}

printf("Factorial=%d",factorial);

return 0;

}

Output

Enter a number.

5

Factorial=120

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 81: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

do...while loop

In C, do...while loop is very similar to while loop. Only difference between these two

loops is that, in while loops, test expression is checked at first but, in do...while loop code is

executed at first then the condition is checked. So, the code are executed at least once in

do...while loops.

Syntax of do...while loops

do {

some code/s;

}

while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is

true, code/s inside body of do are executed again and the process continues until test expression

becomes false(zero).

Notice, there is semicolon in the end of while (); in do...while loop.

Example of do...while loop

Write a C program to add all the numbers entered by a user until user enters 0.

/*C program to demonstrate the working of do...while statement*/

#include <stdio.h>

int main(){

int sum=0,num;

do /* Codes inside the body of do...while loops are at least executed once. */

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 82: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

{

printf("Enter a number\n");

scanf("%d",&num);

sum+=num;

}

while(num!=0);

printf("sum=%d",sum);

return 0;

}

Output

Enter a number

3

Enter a number

-2

Enter a number

0

sum=1

In this C program, user is asked a number and it is added with sum. Then, only the test

condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0,

the body of do...while loop is again executed until num equals to zero.

break; and continue

There are two statements built in C programming, break; and continue; to alter the

normal flow of a program. Loops perform a set of repetitive task until text expression becomes

false but it is sometimes desirable to skip some statement/s inside loop or terminate the loop

immediately without checking the test expression. In such cases, break and continue statements

are used. The break; statement is also used in switch statement to exit switch statement.

i. break Statement

In C programming, break is used in terminating the loop immediately after it is

encountered. The break statement is used with conditional if statement.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 83: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Syntax of break statement

break;

The break statement can be used in terminating all three loops for, while and do...while

loops.

Example of break statement

nt can be used in terminating all three loops for, while and do...while

nt can be used in terminating all three loops for, while and do...while

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 84: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Write a C program to find average of maximum of n positive numbers entered by

user. But, if the input is negative, display the average(excluding the average of

negative input) and end the program.

/* C program to demonstrate the working of break statement by terminating a loop, if

user inputs negative number*/

# include <stdio.h>

int main(){

float num,average,sum;

int i,n;

printf("Maximum no. of inputs\n");

scanf("%d",&n);

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

printf("Enter n%d: ",i);

scanf("%f",&num);

if(num<0.0)

break; //for loop breaks if num<0.0

sum=sum+num;

}

average=sum/(i-1);

printf("Average=%.2f",average);

return 0;

}

Output

Maximum no. of inputs

4

Enter n1: 1.5

Enter n2: 12.5

Enter n3: 7.2

Enter n4: -1

Average=7.07

In this program, when the user inputs number less than zero, the loop is terminated using

break statement with executing the statement below it i.e., without executing sum=sum+num.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 85: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

ii. continue Statement

It is sometimes desirable

to skip some statements inside the

loop. In such cases, continue

statements are used.

Syntax of continue Statement

continue;

Just like break, continue is also used with conditional if statement.

Example of continue statement

Write a C program to find the product of 4 integers entered by a user. If user enters

0 skip it.

//program to demonstrate the working of continue statement in C programming

# include <stdio.h>

int main(){

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 86: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

int i,num,product;

for(i=1,product=1;i<=4;++i){

printf("Enter num%d:",i);

scanf("%d",&num);

if(num==0)

continue; / *In this program, when num equals to zero, it skips the statement

product*=num and continue the loop. */

product*=num;

}

printf("product=%d",product);

return 0;

}

Output

Enter num1:3

Enter num2:0

Enter num3:-5

Enter num4:2

product=-30

Typedef

C automatically converts any intermediated values to the proper type so that the

expression can be evaluated without losing any significance. This automatic conversion is

known implicit type conversion

Type casting is a way to convert a variable from one data type to another data type. For

example, if you want to store a long value into a simple integer then you can type cast long to

int. You can convert values from one type to another explicitly using the cast operator as

follows:

(type_name) expression

Consider the following example where the cast operator causes the division of one integer

variable by another to be performed as a floating-point operation:

#include <stdio.h>

main()

{

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 87: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

int sum = 17, count = 5;

double mean;

mean = (double) sum / count;

printf("Value of mean : %f\n", mean );}

UNIT IV

1. ARRAYS

· C programming language provides a data structure called the array, which can store a

fixed-size sequential collection of elements of the same type.

· An array is used to store a collection of data, of the same data name and data type.

· Example: If the user wants to store marks of 100 students. This can be done by creating

100 variables individually but, this process is rather tedious and impracticable. This type of

problem can be handled in C programming using arrays.

An array is a sequence of data item of homogeneous value (same type).

· Arrays are of two types:

i. One-dimensional arrays

ii. Multidimensional arrays

Declaration of one-dimensional array

· To declare an array in C, a programmer specifies the type of the elements and the number

of elements required by an array as follows:

data_type array_name[array_size];

· Example:

int age[5];

Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of

array age. All element in an array are of the same type (int, in this case).

Array elements

· Size of array defines the number of elements in an array. Each element of array can be

accessed and used by user according to the need of program. For example:

int age[5];

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 88: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

o The first element is numbered

o Here, the size of array

o Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes.

Then, the next address (address of a[1]) will be 2124d, address of a[2] will be

2128d and so on.

Initialization of one-dimensional array:

· Arrays can be initialized at declaration time

int age[5]={2,4,34,3,4};

It is not necessary to define the size of arrays during initialization.

int age[]={2,4,34,3,4};

In this case, the compiler determines

an array.

Accessing array elements

In C programming, arrays can be acc

Example of array in C programming

/* C program to find the sum marks of n students using arrays */

#include <stdio.h>

int main(){

int marks[10],i,n,sum=0;

printf("Enter number of students: ");

scanf("%d",&n);

for(i=0;i<n;++i){

printf("Enter marks of student%d: ",i+1);

first element is numbered is indexed as 0 and so on.

ay age is 5 times the size of int because there are 5 elements.

Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes.

Then, the next address (address of a[1]) will be 2124d, address of a[2] will be

dimensional array:

Arrays can be initialized at declaration time in this source code as:

It is not necessary to define the size of arrays during initialization.

In this case, the compiler determines the size of array by calculating the number of elements of

In C programming, arrays can be accessed and treated like variables in C.

Example of array in C programming

/* C program to find the sum marks of n students using arrays */

printf("Enter number of students: ");

printf("Enter marks of student%d: ",i+1);

is 5 times the size of int because there are 5 elements.

Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes.

Then, the next address (address of a[1]) will be 2124d, address of a[2] will be

the size of array by calculating the number of elements of

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 89: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

scanf("%d",&marks[i]);

sum+=marks[i];

}

printf("Sum= %d",sum);

return 0;

}

Output

Enter number of students: 3

Enter marks of student1: 12

Enter marks of student2: 31

Enter marks of student3: 2

sum=45

2. MULTIDIMENSIONAL ARR

· C programming language allows programmer to create

multidimensional arrays.

· Example: float a[2][6];

o Here, a is an array of two dimension, which is an

array. This array has 2 rows and 6 columns

o For better understanding of multidimensional arrays, array element

example can be think

Initialization of Multidimensional Arrays

In C, multidimensional arrays can be initialized in different number of ways.

int c[2][3]={{1,3,0}, {-1,5,9}};

OR

int c[][3]={{1,3,0}, {-1,5,9}};

scanf("%d",&marks[i]);

MULTIDIMENSIONAL ARRAYS

C programming language allows programmer to create arrays of arrays

is an array of two dimension, which is an example of multidimensional

array. This array has 2 rows and 6 columns

For better understanding of multidimensional arrays, array element

example can be think of as below:

Initialization of Multidimensional Arrays

In C, multidimensional arrays can be initialized in different number of ways.

1,5,9}};

1,5,9}};

arrays of arrays known as

example of multidimensional

For better understanding of multidimensional arrays, array elements of above

In C, multidimensional arrays can be initialized in different number of ways.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 90: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

OR

int c[2][3]={1,3,0,-1,5,9};

Example:

#include <stdio.h>

int main ()

{

/* an array with 5 rows and 2 columns*/

int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

int i, j;

/* output each array element's value */

for ( i = 0; i < 5; i++ )

{

for ( j = 0; j < 2; j++ )

{

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

}

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

a[0][0]: 0

a[0][1]: 0

a[1][0]: 1

a[1][1]: 2

a[2][0]: 2

a[2][1]: 4

a[3][0]: 3

a[3][1]: 6

a[4][0]: 4

a[4][1]: 8

Initialization Of three-dimensional Array

double cprogram[3][2][4]={

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 91: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

{{-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2}},

{{0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}},

{{8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0}}

};

· Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold

i*j*k*m numbers of data.

· Similarly, the array of any dimension can be initialized in C programming.

Example of Multidimensional Array in C

Write a C program to find sum of two matrix of order 2*2 using multidimensional

arrays where, elements of matrix are entered by user.

#include <stdio.h>

int main(){

float a[2][2], b[2][2], c[2][2];

int i,j;

printf("Enter the elements of 1st matrix\n");

/* Reading two dimensional Array with the help of two for loop. If there was an array of

'n' dimension, 'n' numbers of loops are needed for inserting data to array.*/

for(i=0;i<2;++i)

for(j=0;j<2;++j){

printf("Enter a%d%d: ",i+1,j+1);

scanf("%f",&a[i][j]);

}

printf("Enter the elements of 2nd matrix\n");

for(i=0;i<2;++i)

for(j=0;j<2;++j){

printf("Enter b%d%d: ",i+1,j+1);

scanf("%f",&b[i][j]);

}

for(i=0;i<2;++i)

for(j=0;j<2;++j){

/* Writing the elements of multidimensional array using loop. */

c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 92: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

}

printf("\nSum Of Matrix:");

for(i=0;i<2;++i)

for(j=0;j<2;++j){

printf("%.1f\t",c[i][j]);

if(j==1) /* To display matrix sum in order. */

printf("\n");

}

return 0;

}

Ouput

Enter the elements of 1st matrix

Enter a11: 2;

Enter a12: 0.5;

Enter a21: -1.1;

Enter a22: 2;

Enter the elements of 2nd matrix

Enter b11: 0.2;

Enter b12: 0;

Enter b21: 0.23;

Enter b22: 23;

Sum Of Matrix:

2.2 0.5

-0.9 25.0

3. STRING

· In C programming, array of character are called strings. A string is terminated by null

character /0.

· Example: "c string tutorial"

o Here, "c string tutorial" is a string. When, compiler encounters strings, it

appends null character at the end of string.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 93: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Example

· Following is the memory presentation of above defined string in C/C++:

Program

#include <stdio.h>

int main ()

{

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '

printf("Greeting message: %s\n", greeting );

return 0;

}

Output

Greeting message: Hello

C supports a wide range of functions that manipulate null

S.N. Function & Purpose

1 strcpy(s1, s2); Copies string s2 into string s1.

2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.

3 strlen(s1); Returns the length of string s1.

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++:

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

n", greeting );

C supports a wide range of functions that manipulate null-terminated strings:

Copies string s2 into string s1.

Concatenates string s2 onto the end of string s1.

Returns the length of string s1.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 94: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

Following example makes use of few of the above-mentioned functions:

#include <stdio.h>

#include <string.h>

int main ()

{

char str1[12] = "Hello";

char str2[12] = "World";

char str3[12];

int len ;

/* copy str1 into str3 */

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */

len = strlen(str1);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 95: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf("strlen(str1) : %d\n", len );

return 0;

}

Output

strcpy( str3, str1) : Hello

strcat( str1, str2): HelloWorld

strlen(str1) : 10

4. ARRAYS OF STRINGS

· An array of strings is a special form of a two-dimensional array.

· The size of the left index determines the number of strings.

· The size of the right index specifies the maximum length of each string.

For example, the following declares an array of 30 strings, each having a maximum

length of 80 characters (with one extra character for the null terminator):

char string_array[30][81];

· For accessing an individual string, one simply specifies only the left index:

firstString = string_array[0];

sixthString = string_array[5];

· The following example calls the gets() function with the third string in the array:

gets(string_array[2]);

This program accepts lines of text entered at the keyboard and redisplays them after a blank line

is entered.

// includes go here

int main()

{

int t, i;

char text[100][80];

for(t=0; t<100; t++) {

cout << t << “: “;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 96: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

gets(text[t]);

if(!text[t][0]) break; // quit on blank line

}

for(i=0; i<t; i++) // redisplay the strings

cout << text[i] << ‘\n’;

return(0);}

An Example Using String Arrays

Arrays of strings are commonly used for handling tables ofvinformation.

One such application would be an employee database that stores

• the name

• telephone number

• hours worked per pay period, and

• hourly wage.

These data we could store in arrays:

char name[20][80]; // employee names

int phone[20]; // phone numbers

float hours[20]; // hours worked

float wage[20]; // wage

5. ONE DIMENSIONAL CHARACTER ARRAY INITIALIZATION

Character arrays that will hold strings allow a shorthand initialization that takes this form:

Char array-name[size] = “string”;

For example, the following code fragment initializes Str to the phrase “hello”:

char str[6] = “hello”;

This is the same as writing

char str[6] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

Remember that one has to make sure to make the array long enough to include the

null terminator.

#include <stdio.h>

int main(void)

{

char text[10][80];

int i;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 97: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

for(i = 0; i < 10; i++) {

printf("some string for index %d: ", i + 1);

gets(text[ i ]);

}

do {

printf("Enter number of string (1 - 10) : ");

scanf("%d", &i);

i--; /* adjust value to match array index */

if(i >= 0 && i < 10)

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

} while(i>=0);

return 0;

}

6. TWO-DIMENSIONAL ARRAY OF CHARACTERS IN C

PROGRAMMING LANGUAGE

· It has 2 sub scripts.

· The order of the subscripts in the array declaration is important. The first subscript gives

the number of names in the array, while the second subscript gives the length of each

item in the array.

· Example

char masterlist[6][10] = {

"akshay",

"parag",

"raman",

"srinivas",

"gopal",

"rajesh"};

· Instead of initializing names, names can supplied from the keyboard

for ( i = 0 ; i <= 5 ; i++ )

scanf ( "%s", &masterlist[i][0] ) ;

· The names would be stored in the memory as shown in Figure. Note that each string ends

with a ‘\0’. The arrangement is similar to that of a two-dimensional numeric array.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 98: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Here, 65454, 65464, 65474, etc. are the base addresses o

· Even though 10 bytes are reserved for storing the name “akshay”, it occupies only 7

bytes. Thus, 3 bytes go waste.

· ‘Array of pointers’ used to avoid wastage.

7. FUNCTION

· In programming, a function

· A function is a self-contained block of statements that performs a specified task.

specified task is repeated each time that the program calls the function.

· Functions break large computing tasks into smaller ones.

accomplish the goal of the whole program.

· Every program must contain one function named main()

begin execution.

· The function name is an identifier and should be unique.

Types of C functions

Basically, there are two types of functions in C on basis of whether it is defined by user or not.

· Library function

· User defined function

i. Library function

Library functions are the in-built function

main()

- The execution of every C program starts from

printf()

- prinf() is used for displaying output in C.

Here, 65454, 65464, 65474, etc. are the base addresses of successive names.

though 10 bytes are reserved for storing the name “akshay”, it occupies only 7

bytes. Thus, 3 bytes go waste.

used to avoid wastage.

In programming, a function is a segment that groups code to perform a specific task.

contained block of statements that performs a specified task.

specified task is repeated each time that the program calls the function.

break large computing tasks into smaller ones. They work togeth

accomplish the goal of the whole program.

Every program must contain one function named main() where the program always

The function name is an identifier and should be unique.

functions in C on basis of whether it is defined by user or not.

built function in C programming system. For example:

The execution of every C program starts from this main() function.

prinf() is used for displaying output in C.

f successive names.

though 10 bytes are reserved for storing the name “akshay”, it occupies only 7

orm a specific task.

contained block of statements that performs a specified task. The

They work together to

where the program always

functions in C on basis of whether it is defined by user or not.

in C programming system. For example:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 99: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

scanf()

- scanf() is used for taking input in C.

ii. User defined function

· C allows programmer to define their own function

These types of functions are known as user

· Example: Suppose, a programmer wants to

whether it is prime or not in same program.

defined functions in that program: one for finding facto

whether it is prime or not.

Working of user-defined function

· Every C program begins from main() and program starts executing the codes inside

main() function.

· When the control of program reaches to function_nam

control of program jumps to void function_name() and executes the codes inside it.

· When all the codes inside that user

jumps to the statement just after function_name()

Example of user-defined function

Write a C program to add two integers. Make a function

display sum in main() function.

scanf() is used for taking input in C.

allows programmer to define their own function according to their requirement.

re known as user-defined functions.

, a programmer wants to find factorial of a number and check

whether it is prime or not in same program. Then, he/she can create two separate user

defined functions in that program: one for finding factorial and other for checking

defined function in C Programming

very C program begins from main() and program starts executing the codes inside

When the control of program reaches to function_name() inside main() function. The

control of program jumps to void function_name() and executes the codes inside it.

When all the codes inside that user-defined function are executed, control of the program

jumps to the statement just after function_name() from where it is called.

defined function

Write a C program to add two integers. Make a function add to add integers and

to their requirement.

find factorial of a number and check

Then, he/she can create two separate user-

rial and other for checking

very C program begins from main() and program starts executing the codes inside

e() inside main() function. The

control of program jumps to void function_name() and executes the codes inside it.

defined function are executed, control of the program

dd integers and

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 100: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

/*Program to demonstrate the working of user defined function*/

#include <stdio.h>

int add(int a, int b); //function prototype(declaration)

int main(){

int num1,num2,sum;

printf("Enters two number to add\n");

scanf("%d %d",&num1,&num2);

sum=add(num1,num2); //function call

printf("sum=%d",sum);

return 0;

}

int add(int a,int b) //function declarator

{

/* Start of function definition. */

int add;

add=a+b;

return add; //return statement of function

/* End of function definition. */

}

Function prototype(declaration):

· Every function in C programming should be declared before they are used. These type of

declaration are also called function prototype.

· Function prototype gives compiler information about function name, type of arguments to

be passed and return type.

Syntax of function prototype

return_type function_name(type(1) argument(1),....,type(n) argument(n));

· In the above example,int add(int a, int b); is a function prototype which provides

following information to the compiler:

o name of the function is add()

o return type of the function is int.

o two arguments of type int are passed to function.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 101: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Function prototype are not needed if user-definition function is written before

main() function.

Function call

· Control of the program cannot be transferred to user-defined function unless it is

called invoked.

· Syntax of function call

function_name(argument(1),....argument(n));

· In the above example, function call is made using statement add(num1,num2);

from main().

· This makes the control of program jump from that statement to function definition

and executes the codes inside that function.

Function definition

· Function definition contains programming codes to perform specific task.

Syntax of function definition

return_type function_name(type(1) argument(1),..,type(n) argument(n))

{

//body of function

}

Function definition has two major components:

1. Function declarator

· Function declarator is the first line of function definition. When a function is

called, control of the program is transferred to function declarator.

Syntax of function declarator

· return_type function_name(type(1) argument(1),....,type(n) argument(n))

· Syntax of function declaration and declarator are almost same except, there is no

semicolon at the end of declarator and function declarator is followed by function

body.

2. Function body

· Function declarator is followed by body of function inside braces.

The advantages of functions:

1. The length of a source program can be reduced using functions at appropriate places.

2. It is easy to locate and isolate a faulty function.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 102: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

3. A function may be used by many other programs

8. TYPES OF FUNCTIONS

For better understanding of arguments and return type in functions, user

can be categorized as:

1. Function with no arguments and no return values

2. Function with arguments but no return values

3. Function with arguments and

Passing arguments to functions

· In programming, argument(parameter) refers to data this is passed to

function(function definition) while calling function.

· In above example two variable, num1 and num2 are passed to function during

function call and these arguments are accepted by arguments a and b in function

definition.

· Arguments that are passed in function call and argument

function definition should have same data type. For example:

· If argument num1 was of int type and

variable a should be of type int and b should be of type float,i.e., type of

argument during function call and function definition should be same.

· A function can be called with or without an argument.

· Calling a Function :

A function may be used by many other programs.

TYPES OF FUNCTIONS

For better understanding of arguments and return type in functions, user-defined functions

Function with no arguments and no return values

Function with arguments but no return values

Function with arguments and return values

In programming, argument(parameter) refers to data this is passed to

function(function definition) while calling function.

In above example two variable, num1 and num2 are passed to function during

and these arguments are accepted by arguments a and b in function

Arguments that are passed in function call and arguments that are accepted in

function definition should have same data type. For example:

was of int type and num2 was of float type then, argument

should be of type int and b should be of type float,i.e., type of

tion call and function definition should be same.

A function can be called with or without an argument.

defined functions

In programming, argument(parameter) refers to data this is passed to

In above example two variable, num1 and num2 are passed to function during

and these arguments are accepted by arguments a and b in function

s that are accepted in

was of float type then, argument

should be of type int and b should be of type float,i.e., type of

tion call and function definition should be same.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 103: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

o Call a C function just by writing function name with opening and

closing round brackets followed with semicolon.

o If we have to supply parameters then we can write parameters inside pair

of round brackets.

o Parameters are optional.

· Call Function without Passing Parameter :

display();

· Passing 1 Parameter to function :

display(num);

· Passing 2 Parameters to function :

display(num1,num2);

· Called function: It is a function and a function is a group of statements that

together perform a task.

Return Statement

Return statement is used for returning a value from function definition to calling

function.

Syntax of return statement

return (expression);

For example:

return a;

return (a+b);

i. Function With No Arguments and No Return Values

· The function does not receive any data from the calling function.

· The function has no return values, which mean calling function does not receive

any data from the called function.

· There is no data transfer between the calling function and the called function.

/*C program to check whether a number entered by user is prime or not using function with no

arguments and no return value*/

#include <stdio.h>

void prime();

int main(){

prime(); //No argument is passed to prime().

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 104: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

return 0;

}

void prime(){

/* There is no return value to calling function main(). Hence, return type of prime() is void */

int num,i,flag=0;

printf("Enter positive integer enter to check:\n");

scanf("%d",&num);

for(i=2;i<=num/2;++i){

if(num%i==0){

flag=1;

}

}

if (flag==1)

printf("%d is not prime",num);

else

printf("%d is prime",num);

}

Expected output

Enter positive integer enter to check 5

5 is prime

ii. Function With Arguments But No Return Values

· The function receives data from the calling function.

· The main() function will not have any control over the way the functions receive

input data.

· User can read data from the input terminal and pass it to the called function.

#include <stdio.h>

void prime(int);

int main(){

int n=5;

// printf("Enter positive integer enter to check:\n");

// scanf("%d",&n);

prime(n); //No argument is passed to prime().

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 105: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

return 0;

}

void prime(int n){

/* There is no return value to calling function main(). Hence, return type of prime() is void */

int num=n,i,flag=0;

for(i=2;i<=num/2;++i){

if(num%i==0){

flag=1;

}

}

if (flag==1)

printf("%d is not prime",num);

else

printf("%d is prime",num);

}

Expected output

Enter positive integer enter to check 5

5 is prime

iii. Function With Arguments and Return Values

· The function receives data from the calling function and does some process and

then returns the result to the called function.

· In this way, the main() function will have control over the function. This

approach seems better because the calling function can check the validity of data

before it passed to the calling function and to check the validity of the result

before it is sent to the standard output device (i.e. screen).

· When a function is called, a copy of the values of actual arguments is passed to

the called function.

Example : find Factorial of a number.

9. FUNCTION PROTOTYPES

· Any C function returns n integer value by default.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 106: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· If a function should return a value other than an int, then it is necessary to mention the

calling function in the called function, which is called as the function prototype.

· Function prototype are usually written at the beginning of the program explicitly

before all user defined functions including the main() function. The syntax is :

return_type function_name(dt1 arg1, dt2 arg2, . . . dtn argn) ;

o Where return_type represents the data type of the value that is returned by

the function and dt1, dt2, . . . dtn represents the data type of the arguments

arg1, arg2, . . . argn.

o The data types of the actual arguments must confirm to the data types of

the arguments with the prototype. For example :

long fact(long num) ;

o Here fact is the name of the function, long before the function name fact

indicates that the function returns a value of type long. num inside the

parenthesis is the parameter passed to the called function. long before the

num indicates that it is of type long.

10. STORAGE CLASS

· Every variable in C programming has two properties: type and storage class.

o Type refers to the data type of variable whether it is character or integer or

floating-point value etc.

o Storage class determines how long it stays in existence.

· There are 4 types of storage class:

i. automatic

ii. external

iii. static

iv. register

Automatic storage class

Keyword for automatic variable is auto

· Variables declared inside the function body are automatic by default. These variable

are also known as local variables as they are local to the function and doesn't have

meaning outside that function

· Variable inside a function is automatic by default, keyword auto are rarely used.

· Example

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 107: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

void main()

{

auto mum = 20 ;

{

auto num = 60 ;

printf("nNum : %d",num);

}

printf("nNum : %d",num);

}

Output :

Num : 60

Num : 20

External storage class

· External variable can be accessed by any function. They are also known as global

variables. Variables declared outside every function are external variables.

· In case of large program, containing more than one file, if the global variable is

declared in file 1 and that variable is used in file 2 then, compiler will show error.

· To solve this problem, keyword extern is used in file 2 to indicate that, the variable

specified is global variable and declared in another file.

Example to demonstrate working of external variable

int num = 75 ;

void display();

void main()

{

extern int num ;

printf("nNum : %d",num);

display();

}

void display()

{

extern int num ;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 108: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf("nNum : %d",num);

}

Output :

Num : 75

Num : 75

Register Storage Class

Keywords to declare register variable register

Example of register variable

register int a;

· Register variables are similar to automatic variable and exists inside that particular

function only.

· If the compiler encounters register variable, it tries to store variable in

microprocessor's register rather than memory.

· Values stored in register are much faster than that of memory. In case of larger

program, variables that are used in loops and function parameters are declared register

variables.

· Since, there are limited number of register in processor and if it couldn't store the

variable in register, it will automatically store it in memory.

Register storage classes example #include<stdio.h>

int main()

{

int num1,num2;

register int sum;

printf("\nEnter the Number 1 : ");

scanf("%d",&num1);

printf("\nEnter the Number 2 : ");

scanf("%d",&num2);

sum = num1 + num2;

printf("\nSum of Numbers : %d",sum);

return(0);

}

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 109: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Static Storage Class

· The value of static variable persists until the end of the program. A variable can be

declared static using keyword: static. For example:

static int i;

Here, i is a static variable.

Example to demonstrate the static variable

#include <stdio.h>

void Check();

int main(){

Check();

Check();

Check();

}

void Check(){

static int c=0;

printf("%d\t",c);

c+=5;

}

Output

0 5 10

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 110: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· During first function call, it will display 0. Then, during second function call, variable

c will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second

function call and 10 in third call.

· If variable c had been automatic variable, the output would have been:

0 0 0

11. RECURSION

· In C it is possible for the functions to call itself.

· Recursion is a process by which a function calls itself repeatedly until some specified

condition has been satisfied.

· A function is called recursive if a statement within the body of a function calls the

same function, sometimes called circular definition.

· Recursion is the process of defining something in terms of itself.

· When a recursive program is executed the recursive function calls are not executed

immediately, they are placed on a Stack (Last In First Out) until the condition that

terminates the recursive function.

· The function calls are then executed in reverse order as they are popped off the stack.

· Recursive functions can be effectively used in applications in which the solution to a

problem can be expressed in terms of successively applying the same solution to the

subsets of the problem.

· Simple example

void count_to_ten ( int count )

{

/* we only keep counting if we have a value less than ten

if ( count < 10 )

{

count_to_ten( count + 1 );

}

}

int main()

{

count_to_ten ( 0 );

}

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 111: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Example: Factorial of a number

/* Source code to find factorial of a number. */

#include<stdio.h>

int factorial(int n);

int main()

{

int n;

printf("Enter an positive integer: ");

scanf("%d",&n);

printf("Factorial of %d = %ld", n, factorial(n));

return 0;

}

int factorial(int n)

{

if(n!=1)

return n*factorial(n-1);

}

Difference between Recursion and Iteration

RECURSION ITERATIONS

Recursive function – is a function that is

partially defined by itself

Iterative Instructions –are loop based

repetitions of a process

Recursion Uses selection structure Iteration uses repetition structure

Infinite recursion occurs if the recursion step

does not reduce the problem in a manner that

converges on some condition.(base case)

An infinite loop occurs with iteration if

the loop-condition test never becomes

false

Recursion terminates when a base case is

recognized

Iteration terminates when the loop-

condition fails

Recursion is usually slower then iteration due

to overhead of maintaining stack

Iteration does not use stack so it's faster

than recursion

Recursion uses more memory than iteration Iteration consume less memory

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 112: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Infinite recursion can crash the system infinite looping uses CPU

cycles repeatedly

Recursion makes code smaller Iteration makes code longer

12. POINTERS

· Pointer is a variable that holds a memory address, usually the location of another variable

in memory. The pointers are one of C’s most useful and strongest features.

· C Pointer is a variable that stores/points the address of another variable. C Pointer is used

to allocate memory dynamically i.e. at run time. The pointer variable might be belonging

to any of the data type such as int, float, char, double, short etc.

Syntax : data_type *var_name;

Example : int *p; char *p;

· Where, * is used to denote that “p” is pointer variable and not a normal variable.

· Here, p is the name of a variable that stores the value 10 and is stored in memory in the

address, say 1234. This could be represented as follows :

/* Example to demonstrate use of reference operator in C programming. */

#include <stdio.h>

int main(){

int var=5;

printf("Value: %d\n",var);

printf("Address: %d",&var); //Notice, the ampersand(&) before var.

return 0;

}

Output

Value: 5

Address: 2686778

Uses of POINTERS

There are number of advantages of using pointers. They are :

1234 ß Address of the variable p

10 ß Value of the variable p

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 113: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

1. Pointers increase the speed of execution of a program.

2. Pointers reduce the length and complexity of a program.

3. Pointers are more efficient in handling the data tables.

4. A pointer enables us to access a variable that is defined outside the function.

5. The use of a pointer array to character strings results in saving of data storage space in

memory.

INITIALIZING POINTERS

· It is always good practice to initialize pointers as soon as it is declared. Since a pointer is

just an address, if it is not initialized, it may randomly point to some location in memory.

· The ampersand (&) symbol, also called address operator, is applied to a variable to refer

the address of that variable.

· Initializing pointers can be made to point to a variable using an assignment statement.

The syntax is :

ptr_variable = &variable ;

· Here, the address of the variable is assigned to ptr_variable as its value.

· example :

ptr = &price ;

· Will cause ptr to point to price i.e., ptr now contain the address of price.

· A pointer variable can be initialized in its declaration itself.

For example :

int price, *ptr = &price ;

Is also valid.

ACCESSING A VARIABLE THROUGH ITS POINTER

· Accessing the value of the variable using pointer is done by using unary operator *

(asterisk), usually known as indirection operator. Consider the following statements :

int price, *ptr, n ;

price = 100 ;

ptr = &price ;

n = *ptr ;

o The first line declares the price and n as integer variables and ptr as a pointer

variable pointing to an integer.

o The second line assigns the value 100 to price and

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 114: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

o Third line assigns the address of price to the pointer variable ptr.

o The fourth line contains the indirection operator *.

· When the operator * is placed before a pointer variable in an expression (on the right

hand side of the equal sign), the pointer returns the value of the variable of which the

pointer value is the address.

· *ptr returns the value of the variable price, because ptr is the address of price. The * can

be remembered as value at address. Thus the value of n would be 100.

C Program to compute sum of the array elements using pointers #include<stdio.h>

#include<conio.h>

void main() {

int numArray[10];

int i, sum = 0;

int *ptr;

printf("\nEnter 10 elements : ");

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

scanf("%d", &numArray[i]);

ptr = numArray; /* a=&a[0] */

for (i = 0; i < 10; i++) {

sum = sum + *ptr;

ptr++;

}

printf("The sum of array elements : %d", sum);

}

Output:

Enter 10 elements : 11 12 13 14 15 16 17 18 19 20

The sum of array elements is 155

13. ARRAYS AND POINTERS

· Arrays are closely related to pointers in C programming but the important difference is, a

pointer variable can take different addresses as value whereas, in case of array it is fixed.

This can be demonstrated by an example:

#include <stdio.h>

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 115: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

int main(){

char c[4];

int i;

for(i=0;i<4;++i){

printf("Address of c[%d]=%x\n",i,&c[i]);

}

return 0;

}

Address of c[0]=28ff44

Address of c[1]=28ff45

Address of c[2]=28ff46

Address of c[3]=28ff47

· Notice, that there is equal difference (difference of 1 byte) between any two consecutive

elements of array.

Relation between Arrays and Pointers

· Consider an array:

int arr[4];

· In arrays of C programming, name of the array always points to the first element of an

array. Here, address of first element of an array is &arr[0]. Also, arr represents the

address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.

· Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0]

is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to *arr.

· Similarly,

&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).

&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).

&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).

.

.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 116: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).

· In C, one can declare an array and can use pointer to alter the data of an array.

//Program to find the sum of six numbers with arrays and pointers.

#include <stdio.h>

int main(){

int i,class[6],sum=0;

printf("Enter 6 numbers:\n");

for(i=0;i<6;++i){

scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]

sum += *(class+i); // *(class+i) is equivalent to class[i]

}

printf("Sum=%d",sum);

return 0;

}

Output

Enter 6 numbers:

2

3

4

5

3

4

Sum=21

14. POINTER AND FUNCTIONS

· When, argument is passed using pointer, address of the memory location is passed instead

of value.

Program to swap two number using call by reference. /* C Program to swap two numbers using pointers and function. */

#include <stdio.h>

void swap(int *a,int *b);

int main(){

int num1=5,num2=10;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 117: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

swap(&num1,&num2); /* address of num1 and num2 is passed to swap

function */

printf("Number1 = %d\n",num1);

printf("Number2 = %d",num2);

return 0;

}

void swap(int *a,int *b){ /* pointer a and b points to address of num1 and

num2 respectively */

int temp;

temp=*a;

*a=*b;

*b=temp;

}

Output

Number1 = 10

Number2 = 5

· Explanation

o The address of memory location num1 and num2 are passed to function and the

pointers *a and *b accept those values. So, the pointer a and b points to address of

num1 and num2 respectively.

o When, the value of pointer are changed, the value in memory location also

changed correspondingly. Hence, change made to *a and *b was reflected in

num1 and num2 in main function.

o This technique is known as call by reference in C programming.

15. MEMORY ALLOCATION

· The size of array declared initially can be sometimes insufficient and sometimes more

than required.

· Dynamic memory allocation allows a program to obtain more memory space, while

running or to release space when no space is required.

· Although, C language inherently does not have any technique to allocated memory

dynamically, there are 4 library functions under "stdlib.h" for dynamic memory

allocation.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 118: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

malloc()

· The name malloc stands for "memory allocation". The function malloc() reserves a block

of memory of specified size and return a pointer of type void which can be casted into

pointer of any form.

Syntax of malloc()

ptr=(cast-type*)malloc(byte-size)

o Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area

of memory with size of byte size. If the space is insufficient, allocation fails and

returns NULL pointer.

ptr=(int*)malloc(100*sizeof(int));

o This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes

respectively and the pointer points to the address of first byte of memory.

calloc()

· The name calloc stands for "contiguous allocation". The only difference between malloc()

and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates

multiple blocks of memory each of same size and sets all bytes to zero.

Syntax of calloc()

ptr=(cast-type*)calloc(n,element-size);

o This statement will allocate contiguous space in memory for an array of n

elements. For example:

ptr=(float*)calloc(25,sizeof(float));

Function Use of Function

malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space

calloc() Allocates space for an array elements, initializes to zero and then returns a pointer

to memory

free() dellocate the previously allocated space

realloc() Change the size of previously allocated space

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 119: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

o This statement allocates contiguous space in memory for an array of 25 elements

each of size of float, i.e, 4 bytes.

free()

· Dynamically allocated memory with either calloc() or malloc() does not get return on its

own. The programmer must use free() explicitly to release space.

syntax of free()

free(ptr);

o This statement cause the space in memory pointer by ptr to be deallocated.

Examples of calloc() and malloc()

A C program to find sum of n elements entered by user. To perform this program,

allocate memory dynamically using malloc() function.

#include <stdio.h>

#include <stdlib.h>

int main(){

int n,i,*ptr,sum=0;

printf("Enter number of elements: ");

scanf("%d",&n);

ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc

if(ptr==NULL)

{

printf("Error! memory not allocated.");

exit(0);

}

printf("Enter elements of array: ");

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

{

scanf("%d",ptr+i);

sum+=*(ptr+i);

}

printf("Sum=%d",sum);

free(ptr);

return 0;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 120: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

}

A C program to find sum of n elements entered by user. To perform this program,

allocate memory dynamically using calloc() function.

#include <stdio.h>

#include <stdlib.h>

int main(){

int n,i,*ptr,sum=0;

printf("Enter number of elements: ");

scanf("%d",&n);

ptr=(int*)calloc(n,sizeof(int));

if(ptr==NULL)

{

printf("Error! memory not allocated.");

exit(0);

}

printf("Enter elements of array: ");

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

{

scanf("%d",ptr+i);

sum+=*(ptr+i);

}

printf("Sum=%d",sum);

free(ptr);

return 0;

}

realloc()

· If the previously allocated memory is insufficient or more than sufficient. Then, you can

change memory size previously allocated using realloc().

Syntax of realloc()

ptr=realloc(ptr,newsize);

Here, ptr is reallocated with size of newsize.

#include <stdio.h>

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 121: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

#include <stdlib.h>

int main(){

int *ptr,i,n1,n2;

printf("Enter size of array: ");

scanf("%d",&n1);

ptr=(int*)malloc(n1*sizeof(int));

printf("Address of previously allocated memory: ");

for(i=0;i<n1;++i)

printf("%u\t",ptr+i);

printf("\nEnter new size of array: ");

scanf("%d",&n2);

ptr=realloc(ptr,n2);

for(i=0;i<n2;++i)

printf("%u\t",ptr+i);

return 0;}

Source Code to Find Largest Element Using Dynamic Memory Allocation

#include <stdio.h>

#include <stdlib.h>

int main(){

int i,n;

float *data;

printf("Enter total number of elements(1 to 100): ");

scanf("%d",&n);

data=(float*)calloc(n,sizeof(float)); /* Allocates the memory for 'n' elements */

if(data==NULL)

{

printf("Error!!! memory not allocated.");

exit(0);

}

printf("\n");

for(i=0;i<n;++i) /* Stores number entered by user. */

{

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 122: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf("Enter Number %d: ",i+1);

scanf("%f",data+i);

}

for(i=1;i<n;++i) /* Loop to store largest number at address data */

{

if(*data<*(data+i)) /* Change < to > if you want to find smallest number */

*data=*(data+i);

}

printf("Largest element = %.2f",*data);

return 0;

}

Output

UNIT V

1. STRUCTURE

· Structure is the collection of variables of different types under a single name for better

handling.

· Arrays allow defining type of variables that can hold several data items of the same kind but

structure allows combining data items of different kinds.

Structure Definition in C

Keyword struct is used for creating a structure.

Syntax of structure

struct structure_name

{

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 123: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

data_type member1;

data_type member2;

.

.

data_type memeber;

};

Example to create the structure for a person as mentioned above as:

struct person

{

char name[50];

int cit_no;

float salary;

};

This declaration above creates the derived data type struct person.

Structure variable declaration

When a structure is defined, it creates a user-defined type but, no storage is allocated. For

the above structure of person, variable can be declared as:

struct person

{

char name[50];

int cit_no;

float salary;

};

Inside main function:

struct person p1, p2, p[20];

Another way of creating sturcture variable is:

struct person

{

char name[50];

int cit_no;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 124: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

float salary;

}p1 ,p2 ,p[20];

In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person

are created.

Accessing members of a structure

· There are two types of operators used for accessing members of a structure.

i. Member operator(.)

· Any member of a structure can be accessed as: structure_variable_name.member_name

· Suppose, we want to access salary for variable p2. Then, it can be accessed as:

p2.salary

· Example:

#include<stdio.h>

struct Vehicle

{

int wheels;

char vname[20];

char color[10];

}v1 = {4,"Nano","Red"};

int main()

{

printf("Vehicle No of Wheels : %d",v1.wheels);

printf("Vehicle Name : %s",v1.vname);

printf("Vehicle Color : %s",v1.color);

return(0);

}

Output :

Vehicle No of Wheels : 4

Vehicle Name : Nano

Vehicle Color : Red

ii. Structure pointer operator(->)

#include<stdio.h>

#include<malloc.h>

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 125: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

struct emp {

int eid;

char name[10];

}*ptr;

int main() {

int i;

printf("Enter the Employee Details : ");

ptr = (struct emp *) malloc(sizeof(struct emp));

printf("\nEnter the Employee ID : ");

scanf("%d", &ptr->eid);

printf("\nEnter the Employee Name : ");

scanf("%s", ptr->name);

printf("\nEmployee Details are : ");

printf("\nRoll Number : %d", ptr->eid);

printf("\nEmployee Name : %s", ptr->name);

return (0);

}

Output :

Enter the Employee Details :

Enter the Employee ID : 1

Enter the Employee Name : Pritesh

Employee Details are :

Employee ID : 1

Name : Pritesh

Example of C Program on Student details using structure.

/* Student details using structure */

#include<stdio.h>

#include<conio.h>

struct stu

{ int stuno;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 126: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

char sname[10];

int mar;

} ;

void main()

{ struct stu s[10];

int n,i;

clrscr();

printf("\n how many records");

scanf("%d",&n);

printf("\n enter the records");

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

scanf("%d%s%d",&s[i].stuno,s[i].sname,&s[i].mar);

printf("\n entered records are");

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

printf("\n %d\n %s\n %d",s[i].stuno,s[i].sname,s[i].mar);

getch();

}

Keyword typedef while using structure

· Programmer generally uses typedef while using structure in C language. For example:

typedef struct complex{

int imag;

float real;

}comp;

Inside main:

comp c1,c2;

· Here, typedef keyword is used in creating a type comp(which is of type as struct

complex). Then, two structure variables c1 and c2 are created by this comp type.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 127: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Structures within structures

Consider an example to access structure's member through pointer.

#include <stdio.h>

struct name{

Consider an example to access structure's member through pointer.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 128: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

int a;

float b;

};

int main(){

struct name *ptr,p;

ptr=&p; /* Referencing pointer to memory address of p */

printf("Enter integer: ");

scanf("%d",&(*ptr).a);

printf("Enter number: ");

scanf("%f",&(*ptr).b);

printf("Displaying: ");

printf("%d%f",(*ptr).a,(*ptr).b);

return 0;

}

· In this example, the pointer variable of type struct name is referenced to the address of p.

Then, only the structure member through pointer can can accessed.

· Structure pointer member can also be accessed using -> operator.

(*ptr).a is same as ptr->a

(*ptr).b is same as ptr->b

Accessing structure member through pointer using dynamic memory allocation

· To access structure member using pointers, memory can be allocated dynamically using

malloc() function defined under "stdlib.h" header file.

· Syntax to use malloc()

ptr=(cast-type*)malloc(byte-size)

Example to use structure's member through pointer using malloc() function.

#include <stdio.h>

#include<stdlib.h>

struct name {

int a;

float b;

char c[30];

};

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 129: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

int main(){

struct name *ptr;

int i,n;

printf("Enter n: ");

scanf("%d",&n);

ptr=(struct name*)malloc(n*sizeof(struct name));

/* Above statement allocates the memory for n structures with pointer ptr pointing to base

address */

for(i=0;i<n;++i){

printf("Enter string, integer and floating number respectively:\n");

scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);

}

printf("Displaying Infromation:\n");

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

printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);

return 0;

}

Output

Enter n: 2

Enter string, integer and floating number respectively:

Programming

2

3.2

Enter string, integer and floating number respectively:

Structure

6

2.3

Displaying Information

Programming 2 3.20

Structure 6 2.30

In C, structure can be passed to functions by two methods:

· Passing by value (passing actual value as argument)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 130: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· Passing by reference (passing address of an argument)

i. Passing structure by value

· A structure variable can be passed to the function as an argument as normal variable. If

structure is passed by value, change made in structure variable in function definition

does not reflect in original structure variable in calling function.

· Example: C program to create a structure student, containing name and roll. Ask

user the name and roll of a student in main function. Pass this structure to a

function and display the information in that function.

#include <stdio.h>

struct student{

char name[50];

int roll;

};

void Display(struct student stu);

/* function prototype should be below to the structure declaration otherwise compiler shows

error */

int main(){

struct student s1;

printf("Enter student's name: ");

scanf("%s",&s1.name);

printf("Enter roll number:");

scanf("%d",&s1.roll);

Display(s1); // passing structure variable s1 as argument

return 0;

}

void Display(struct student stu){

printf("Output\nName: %s",stu.name);

printf("\nRoll: %d",stu.roll);

}

Output

Enter student's name: Kevin Amla

Enter roll number: 149

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 131: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Output

Name: Kevin Amla

Roll: 149

ii. Passing structure by reference

· The address location of structure variable is passed to function while passing it by

reference.

· If structure is passed by reference, change made in structure variable in function

definition reflects in original structure variable in the calling function.

· Example: C program to add two distances(feet-inch system) entered by user. To

solve this program, make a structure. Pass two structure variable (containing

distance in feet and inch) to add function by reference and display the result in

main function without returning it.

#include <stdio.h>

struct distance{

int feet;

float inch;

};

void Add(struct distance d1,struct distance d2, struct distance *d3);

int main()

{

struct distance dist1, dist2, dist3;

printf("First distance\n");

printf("Enter feet: ");

scanf("%d",&dist1.feet);

printf("Enter inch: ");

scanf("%f",&dist1.inch);

printf("Second distance\n");

printf("Enter feet: ");

scanf("%d",&dist2.feet);

printf("Enter inch: ");

scanf("%f",&dist2.inch);

Add(dist1, dist2, &dist3);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 132: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

/*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by

reference */

printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);

return 0;

}

void Add(struct distance d1,struct distance d2, struct distance *d3)

{

/* Adding distances d1 and d2 and storing it in d3 */

d3->feet=d1.feet+d2.feet;

d3->inch=d1.inch+d2.inch;

if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet. */

d3->inch-=12;

++d3->feet;

}

}

Output

First distance

Enter feet: 12

Enter inch: 6.8

Second distance

Enter feet: 5

Enter inch: 7.5

Sum of distances = 18'-2.3"

Explanation

· In this program, structure variables dist1 and dist2 are passed by value (because value of

dist1 and dist2 does not need to be displayed in main function) and dist3 is passed by

reference ,i.e, address of dist3 (&dist3) is passed as an argument.

· Thus, the structure pointer variable d3 points to the address of dist3. If any change is

made in d3 variable, effect of it is seed in dist3 variable in main function.

· Unions are quite similar to the structures in C. Union is also a derived type as structure.

Union can be defined in same manner as structures just the keyword used in defining

union in union where keyword used in defining structure was struct.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 133: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

union car{

char name[50];

int price;

};

Union variables can be created in similar manner as structure variable.

union car{

char name[50];

int price;

}c1, c2, *c3;

OR;

union car{

char name[50];

int price;

};

-------Inside Function-----------

union car c1, c2, *c3;

· In both cases, union variables c1, c2 and union pointer variable c3 of type union car is

created.

· Accessing members of an union

· The member of unions can be accessed in similar manner as that structure. Suppose, we

you want to access price for union variable c1 in above example, it can be accessed as

c1.price. If you want to access price for union pointer variable c3, it can be accessed as

(*c3).price or as c3->price.

Source Code to Store Information of 10 students Using Structure

#include <stdio.h>

struct student{

char name[50];

int roll;

float marks;

};

int main(){

struct student s[10];

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 134: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

int i;

printf("Enter information of students:\n");

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

{

s[i].roll=i+1;

printf("\nFor roll number %d\n",s[i].roll);

printf("Enter name: ");

scanf("%s",s[i].name);

printf("Enter marks: ");

scanf("%f",&s[i].marks);

printf("\n");

}

printf("Displaying information of students:\n\n");

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

{

printf("\nInformation for roll number %d:\n",i+1);

printf("Name: ");

puts(s[i].name);

printf("Marks: %.1f",s[i].marks);

}

return 0;

}

Output

Enter information of students:

For roll number 1

Enter name: Tom

Enter marks: 98

For roll number 2

Enter name: Jerry

Enter marks: 89

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 135: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

.

.

.

Displaying information of students:

Information for roll number 1:

Name: Tom

Marks: 98

2. Union

· C Union is also like structure, i.e. collection of different data types which are grouped

together. Each element in a union is called member.

· Union and structure in C are same in concepts, except allocating memory for their

members.

· Structure allocates storage space for all its members separately.

· Union allocates one common storage space for all its members

· One can access only one member of union at a time. We can’t access all member

values at the same time in union. But, structure can access all member values at the

same time. Union allocates one common storage space for all its members.

Whereas Structure allocates storage space for all its members separately.

· Many union variables can be created in a program and memory will be allocated for each

union variable separately.

· Below table will help you how to form a C union, declare a union, initializing and

accessing the members of the union.

Type Using normal variable Using pointer variable

Syntax union tag_name

{

data type var_name1;

data type var_name2;

union tag_name

{

data type var_name1;

data type var_name2;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 136: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

data type var_name3;

};

data type var_name3;

};

Example union student

{

int mark;

char name[10];

float average;

};

union student

{

int mark;

char name[10];

float average;

};

Declaring

union variable

union student report; union student *report, rep;

Initializing

union variable

union student report = {100,

“Mani”, 99.5};

union student rep = {100, “Mani”,

99.5};report = &rep;

Accessing

union members

report.mark

report.name

report.average

report -> mark

report -> name

report -> average

Difference between union and structure

Structure Union

1.The keyword struct is used to define a

structure

1. The keyword union is used to define a

union.

2. When a variable is associated with a

structure, the compiler allocates the memory

for each member. The size of structure is

greater than or equal to the sum of sizes of its

members. The smaller members may end with

unused slack bytes.

2. When a variable is associated with a union,

the compiler allocates the memory by

considering the size of the largest memory. So,

size of union is equal to the size of largest

member.

3. Each member within a structure is

assigned unique storage area of location.

3. Memory allocated is common for all

members of union.

4. The address of each member will be in

ascending order This indicates that memory for

each member will start at different offset

4. The address is same for all the members of a

union. This indicates that every member begins

at the same offset value.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 137: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

values.

5 Altering the value of a member will not

affect other members of the structure.

5. Altering the value of any of the member will

alter other member values.

6. Individual member can be accessed at a

time

6. Only one member can be accessed at a

time.

7. Several members of a structure can

initialize at once.

7. Only the first member of a union can be

initialized

Example for union

#include <stdio.h>

union job { //defining a union

char name[32];

float salary;

int worker_no;

}u;

struct job1 {

char name[32];

float salary;

int worker_no;

}s;

int main(){

printf("size of union = %d",sizeof(u));

printf("\nsize of structure = %d", sizeof(s));

return 0;

}

Output

size of union = 32

size of structure = 40

Program explanation

· The amount of memory required to store a structure variables is the sum of memory size

of all members.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 138: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· But, the memory required to store a union variable is the memory required for largest

element of a union.

Example :structure and union :all members of structure can be accessed at any time. But, only

one member of union can be accessed at a time in case of union and other members will contain

garbage value.

#include <stdio.h>

union job {

char name[32];

float salary;

int worker_no;

}u;

int main(){

printf("Enter name:\n");

scanf("%s",&u.name);

printf("Enter salary: \n");

scanf("%f",&u.salary);

printf("Displaying\nName :%s\n",u.name);

printf("Salary: %.1f",u.salary);

return 0;

}

Output

Enter name

ut, the memory required to store a union variable is the memory required for largest

all members of structure can be accessed at any time. But, only

one member of union can be accessed at a time in case of union and other members will contain

n",u.name);

ut, the memory required to store a union variable is the memory required for largest

all members of structure can be accessed at any time. But, only

one member of union can be accessed at a time in case of union and other members will contain

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 139: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Hillary

Enter salary

1234.23

Displaying

Name: f%Bary

Salary: 1234.2

Note: You may get different garbage value of name.

· Initially, Hillary will be stored in u.name and other members of union will contain

garbage value. But when user enters value of salary, 1234.23 will be stored in u.salary

and other members will contain garbage value. Thus in output, salary is printed

accurately but, name displays some random string.

3. typedef and enumumerated type

(i) typedef is a powerful tool that allows programmers to define and then use their own

data types. For example:

typedef int Integer;

Integer nStudents, nCourses, studentID;

o Note that in the typedef statement, the newly defined type name goes in the place

where a variable name would normally go.

(ii) An enumeration is a user-defined data type consists of integral constants and each

integral constant is give a name. Keyword enum is used to defined enumerated data type.

enum type_name{ value1, value2,...,valueN };

o Here, type_name is the name of enumerated data type or tag. And value1,

value2,....,valueN are values of type type_name.

o By default, value1 will be equal to 0, value2 will be 1 and so on but, the

programmer can change the default value as below:

enum suit{

club=0;

diamonds=10;

hearts=20;

spades=3;

};

Declaration of enumerated variable :Variable of type enum can be created as:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 140: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

enum boolean{

false;

true;

};

enum boolean check;

· Here, a variable check is declared which is of type enum boolean.

Example1 of enumerated type

#include <stdio.h>

enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};

int main(){

enum week today;

today=wednesday;

printf("%d day",today+1);

return 0;

}

Output

4 day

Example2 of enumerated type

#include< stdio.h>

void main()

{

int i;

enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};

clrscr();

for(i=JAN;i<=DEC;i++)

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

}

Output

01234567891011

4. File Management in C

In C programming, file is a place on disk where a group of related data is stored.

Importance of files .

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 141: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

When the program is terminated, the entire data is lost in C programming. If you want to

keep large volume of data, it is time consuming to enter the entire data. But, if file is created, this

information can be accessed using few commands.

There are large numbers of functions to handle file I/O in C language.

High level file I/O functions can be categorized as:

i. Text file

ii. Binary file

File Operations

i. Creating a new file

ii. Opening an existing file

iii. Reading from and writing information to a file

iv. Closing a file

Working with file

While working with file, you need to declare a pointer of type file. This declaration is

needed for communication between file and program.

FILE *ptr;

Opening a file

Opening a file is performed using library function fopen(). The syntax for opening a file

in standard I/O is:

ptr=fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\program.txt","w");

/* --------------------------------------------------------- */

E:\\cprogram\program.txt is the location to create file.

"w" represents the mode for writing.

/* --------------------------------------------------------- */

Here, the program.txt file is opened for writing mode.

Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

r Open for reading. If the file does not exist, fopen() returns NULL.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 142: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

w Open for writing. If the file exists, its contents are overwritten. If the file

does not exist, it will be created.

a Open for append. i.e, Data is

added to end of file. If the file does not exists, it will be created.

r+ Open for both reading and

writing. If the file does not exist, fopen() returns NULL.

w+ Open for both reading and

writing.

If the file exists, its contents are overwritten. If the file

does not exist, it will be created.

a+ Open for both reading and

appending. If the file does not exists, it will be created.

Closing a File: The file should be closed after reading/writing of a file. Closing a file is

performed using library function fclose().

fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions.

The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only

difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure

FILE

Writing to a file

#include <stdio.h>

int main()

{

int n;

FILE *fptr;

fptr=fopen("C:\\program.txt","w");

if(fptr==NULL){

printf("Error!");

exit(1);

}

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 143: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf("Enter n: ");

scanf("%d",&n);

fprintf(fptr,"%d",n);

fclose(fptr);

return 0;

}

Output:

· This program takes the number from user and stores in file.

· After compile and run this program, a text file program.txt created in C drive of the

computer. Similarly, fscanf() can be used to read data from file.

Reading from file

#include <stdio.h>

int main()

{

int n;

FILE *fptr;

if ((fptr=fopen("C:\\program.txt","r"))==NULL){

printf("Error! opening file");

exit(1); /* Program exits if file pointer returns NULL. */

}

fscanf(fptr,"%d",&n);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 144: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf("Value of n=%d",n);

fclose(fptr);

return 0;

}

If you have run program above to write in file successfully, you can get the integer back

entered in that program using this program.

Other functions like fgetchar(), fputc() etc. can be used in similar way.

Binary Files

Depending upon the way file is opened for processing, a file is classified into text file and

binary file.

If a large amount of numerical data it to be stored, text mode will be insufficient. In such

case binary file is used.

Working of binary files is similar to text files with few differences in opening modes,

reading from file and writing to file.

Opening modes of binary files

Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference

between opening modes of text and binary files is that, b is appended to indicate that, it is binary

file.

Reading and writing of a binary file.

Functions fread() and fwrite() are used for reading from and writing to a file on the disk

respectively in case of binary files.

Function fwrite() takes four arguments, address of data to be written in disk, size of data

to be written in disk, number of such type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);

Function fread() also take 4 arguments similar to fwrite() function as above.

The following example shows the usage of fread() and fwrite() functions.

#include <stdio.h>

#include <string.h>

int main()

{

FILE *fp;

char c[] = "Welcome to FXEC";

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 145: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

char buffer[20];

/* Open file for both reading and writing */

fp = fopen("file.txt", "w+");

/* Write data to the file */

fwrite(c, strlen(c) + 1, 1, fp);

/* Seek to the beginning of the file */

fseek(fp, SEEK_SET, 0);

/* Read and display data */

fread(buffer, strlen(c)+1, 1, fp);

printf("%s\n", buffer);

fclose(fp);

return(0);

}

Output

Welcome to FXEC

5. File operation functions in C:

Function Name Operation

fopen() Creates a new file for use

Opens a new existing file for use

Fclose Closes a file which has been opened for use

getc() Reads a character from a file

putc() Writes a character to a file

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values from a file

getw() Reads a integer from a file

putw() Writes an integer to the file

fseek() Sets the position to a desired point in the file

ftell() Gives the current position in the file

rewind() Sets the position to the begining of the file

Defining and opening a file:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 146: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· If we want to store data in a file into the secondary memory, we must specify certain

things about the file to the operating system. They include the fielname, data structure,

purpose.

· The general format of the function used for opening a file is

FILE *fp;

fp=fopen(“filename”,”mode”);

· The first statement declares the variable fp as a pointer to the data type FILE. As stated

earlier, File is a structure that is defined in the I/O Library. The second statement

opens the file named filename and assigns an identifier to the FILE type pointer fp.

This pointer, which contains all the information about the file, is subsequently used as

a communication link between the system and the program.

· The second statement also specifies the purpose of opening the file. The mode does

this job.

R open the file for read only.

W open the file for writing only.

A open the file for appending data to it.

Consider the following statements:

FILE *p1, *p2;

p1=fopen(“data”,”r”);

p2=fopen(“results”,”w”);

· In these statements the p1 and p2 are created and assigned to open the files data and

results respectively the file data is opened for reading and result is opened for writing.

· In case the results file already exists, its contents are deleted and the files are opened

as a new file. If data file does not exist error will occur.

Closing a file:

· The input output library supports the function to close a file; it is in the following

format.

fclose(file_pointer);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 147: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· A file must be closed as soon as all operations on it have been completed. This would

close the file associated with the file pointer.

· Observe the following program.

….

FILE *p1 *p2;

p1=fopen (“Input”,”w”);

p2=fopen (“Output”,”r”);

….

fclose(p1);

fclose(p2)

· The above program opens two files and closes them after all operations on them are

completed, once a file is closed its file pointer can be reversed on other file.

· The getc and putc functions are analogous to getchar and putchar functions and handle

one character at a time. The putc function writes the character contained in character

variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc

function is used to read a character from a file that has been open in read mode.

c=getc(fp2).

· The program shown below displays use of a file operations. The data enter through the

keyboard and the program writes it. Character by character, to the file input. The end

of the data is indicated by entering an EOF character, which is control-z. the file input

is closed at this signal.

#include< stdio.h >

main()

{

file *f1;

printf(“Data input output”);

f1=fopen(“Input”,”w”); /*Open the file Input*/

while((c=getchar())!=EOF) /*get a character from key board*/

putc(c,f1); /*write a character to input*/

fclose(f1); /*close the file input*/

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 148: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf(“\nData output\n”);

f1=fopen(“INPUT”,”r”); /*Reopen the file input*/

while((c=getc(f1))!=EOF)

printf(“%c”,c);

fclose(f1);

}

The getw and putw functions:

· These are integer-oriented functions. They are similar to get c and putc functions and

are used to read and write integer values. These functions would be usefull when we

deal with only integer data. The general forms of getw and putw are:

putw(integer,fp);

getw(fp);

/*Example program for using getw and putw functions*/

#include< stdio.h >

main()

{

FILE *f1,*f2,*f3;

int number I;

printf(“Contents of the data file\n\n”);

f1=fopen(“DATA”,”W”);

for(I=1;I< 30;I++)

{

scanf(“%d”,&number);

if(number==-1)

break;

putw(number,f1);

}

fclose(f1);

f1=fopen(“DATA”,”r”);

f2=fopen(“ODD”,”w”);

f3=fopen(“EVEN”,”w”);

while((number=getw(f1))!=EOF)/* Read from data file*/

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 149: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

{

if(number%2==0)

putw(number,f3);/*Write to even file*/

else

putw(number,f2);/*write to odd file*/

}

fclose(f1);

fclose(f2);

fclose(f3);

f2=fopen(“ODD”,”r”);

f3=fopen(“EVEN”,”r”);

printf(“\n\nContents of the odd file\n\n”);

while(number=getw(f2))!=EOF)

printf(“%d%d”,number);

printf(“\n\nContents of the even file”);

while(number=getw(f3))!=EOF)

printf(“%d”,number);

fclose(f2);

fclose(f3);

}

6. File access:

One can access the data stored in the file in two ways.

· Sequentially: Data accessed serially. To access the forty fourth record then first forty

three records read one after the other to reach forty four records.

· Randomly: In random access, data can be accessed and processed directly. There is no

need to read each record sequentially. To access a particular record random access takes

less time than the sequential access.

Random access to files:

· Random access means we can move to any part of a file and read or write data from it

without having to read through the entire file.

· Sometimes it is required to access only a particular part of the and not the complete file.

This can be accomplished by using the following function:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 150: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

fseek( ) Function

ftell ( ) Function

i. fseek function:

· This function is used for setting the file position pointer at the specified bytes. fseek is a

function belonging to the ANCI C standard Library and included in the file stdio.h.

· Its purpose is to change the file position indicator for the specified stream.

int fseek(FILE *stream_pointer, long offset, int origin);

Argument meaning:

o stream_pointer is a pointer to the stream FILE structure of which the

position indicator should be changed;

o offset is a long integer which specifies the number of bytes from origin

where the position indicator should be placed;

o origin is an integer which specifies the origin position. It can be:

Constant Description

SEEK_SET Beginning of file

SEEK_CUR Current position of the file pointer

SEEK_END End of file

The following example shows the usage of fseek() function.

#include <stdio.h>

int main ()

{

FILE *fp;

fp = fopen("file.txt","w+");

fputs("This is a sample program", fp);

fseek( fp, 7, SEEK_SET );

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 151: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

fputs(" C Programming Langauge", fp);

fclose(fp);

return(0);

}

Output

This is C Programming Langauge

ftell ( ) Function

The C library function long int ftell(FILE *stream) returns the current file position of the

given stream.

Declaration

· Following is the declaration for ftell() function.

· long int ftell(FILE *stream)

Parameters

· stream -- This is the pointer to a FILE object that identifies the stream.

Return Value

· This function returns the current value of the position indicator. If an error occurs, -1L is

returned, and the global variable errno is set to a positive value.

Example

#include <stdio.h>

int main ()

{

FILE *fp;

int len;

fp = fopen("file.txt", "r");

if( fp == NULL )

{

perror ("Error opening file");

return(-1);

}

fseek(fp, 0, SEEK_END);

len = ftell(fp);

fclose(fp);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 152: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

printf("Total size of file.txt = %d bytes\n", len);

return(0);

}

· Assuming we have a text file file.txt, which has the following content:

This is tutorialspoint.com

Output

Total size of file.txt = 27 bytes

ii. The rewind() Function

· The rewind() function can be used in sequential or random access C file programming, and

simply tells the file system to position the file pointer at the start of the file. Any error flags

will also be cleared, and no value is returned.

Description

The C library function void rewind(FILE *stream) sets the file position to the beginning of the

file of the given stream.

Declaration

Following is the declaration for rewind() function.

void rewind(FILE *stream)

Parameters

stream -- This is the pointer to a FILE object that identifies the stream.

Return Value

This function does not return any value.

Example

#include <stdio.h>

int main()

{

char str[] = "This is tutorialspoint.com";

FILE *fp;

int ch;

/* First let's write some content in the file */

fp = fopen( "file.txt" , "w" );

fwrite(str , 1 , sizeof(str) , fp );

fclose(fp);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 153: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

fp = fopen( "file.txt" , "r" );

while(1)

{

ch = fgetc(fp);

if( feof(fp) )

{

break ;

}

printf("%c", ch);

}

rewind(fp);

printf("\n");

while(1)

{

ch = fgetc(fp);

if( feof(fp) )

{

break ;

}

printf("%c", ch);

}

fclose(fp);

return(0);

}

Assuming we have a text file file.txt having the following content:

This is tutorialspoint.com

Output:

This is tutorialspoint.com

This is tutorialspoint.com

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 154: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

fseek(), ftell() and rewind()

fseek() - It is used to moves the reading control to different positions using fseek function.

ftell() - It tells the byte location of current position in file pointer.

rewind() - It moves the control to beginning of a file.

Program

1

2

3

4

5

6

7

8

9

10

11

12

13

14

#include

void main(){

FILE *fp;

int i;

clrscr();

fp = fopen("CHAR.txt","r");

for (i=1;i&lt;=10;i++){

printf("%c : %d\n",getc(fp),ftell(fp));

fseek(fp,ftell(fp),0);

if (i == 5)

rewind(fp);

}

fclose(fp);

}

Output

W : 0

e : 1

l : 2

c : 3

o : 4

W : 0

e : 1

l : 2

c : 3

o : 4

7. command line arguments

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 155: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

· It is possible to pass some values from the command line to the C programs when they are

executed. These values are called command line arguments and many times they are

important for the c program.

· The command line arguments are handled using main() function arguments where argc

refers to the number of arguments passed, and argv[] is a pointer array which points to each

argument passed to the program.

· main() function of a C program accepts arguments from command line or from other shell

scripts by following commands. They are,

argc

argv[]

· where,

o argc - Number of arguments in the command line including program name

o argv[] – This is carrying all the arguments

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 156: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

8. C Program to read, print name and other details of 50 students

Problem Statement : The annual examination is conducted for 50 students for three subjects.

Write a program to read the data and determine the following:

(a) Total marks obtained by each student.

(b) The highest marks in each subject and the Roll No. of the student who secured

it.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 157: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

(c) The student who obtained the highest total marks.

#include<stdio.h>

#define SIZE 50

struct student {

char name[30];

int rollno;

int sub[3];

};

void main() {

int i, j, max, count, total, n, a[SIZE], ni;

struct student st[SIZE];

clrscr();

printf("Enter how many students: ");

scanf("%d", &n);

/* for loop to read the names and roll numbers*/

for (i = 0; i < n; i++) {

printf("\nEnter name and roll number for student %d : ", i);

scanf("%s", &st[i].name);

scanf("%d", &st[i].rollno);

}

/* for loop to read ith student's jth subject*/

for (i = 0; i < n; i++) {

for (j = 0; j <= 2; j++) {

printf("\nEnter marks of student %d for subject %d : ", i, j);

scanf("%d", &st[i].sub[j]);

}

}

/* (i) for loop to calculate total marks obtained by each student*/

for (i = 0; i < n; i++) {

total = 0;

for (j = 0; j < 3; j++) {

total = total + st[i].sub[j];

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 158: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

}

printf("\nTotal marks obtained by student %s are %dn", st[i].name,total);

a[i] = total;

}

/* (ii) for loop to list out the student's roll numbers who have secured the highest marks in each

subject */

/* roll number who secured the highest marks */

for (j = 0; j < 3; j++) {

max = 0;

for (i = 0; i < n; i++) {

if (max < st[i].sub[j]) {

max = st[i].sub[j];

ni = i;

}

}

printf("\nStudent %s got maximum marks = %d in Subject : %d",st[ni].name,

max, j);

}

max = 0;

for (i = 0; i < n; i++) {

if (max < a[i]) {

max = a[i];

ni = i;

}

}

printf("\n%s obtained the total highest marks.", st[ni].name);

getch();

}

Enter how many students: 2

Enter name and roll number for student 0 : Pritesh 1

Enter name and roll number for student 1 : Suraj 2

www.Vidyarthiplus.com

www.Vidyarthiplus.com

Page 159: S.PRINCY SUGANTHI BAI - Vidyarthiplus

http:\\www.francisxavier.ac.in

Enter marks of student 0 for subject 0 : 90

Enter marks of student 0 for subject 1 : 89

Enter marks of student 0 for subject 2 : 78

Enter marks of student 1 for subject 0 : 67

Enter marks of student 1 for subject 1 : 88

Enter marks of student 1 for subject 2 : 99

Total marks obtained by student Pritesh are 257

Total marks obtained by student Suraj are 254

Student Pritesh got maximum marks = 90 in Subject : 0

Student Pritesh got maximum marks = 89 in Subject : 1

Student Suraj got maximum marks = 99 in Subject : 2

Pritesh obtained the total highest marks.

www.Vidyarthiplus.com

www.Vidyarthiplus.com