BCA 101 - Computer Fundamentals and Programming - BCA
BCA 101 - Computer Fundamentals and Programming - BCA
in
UNIT 2 PROGRAMMING
FUNDAMENTALS:
ALGORITHMS AND
FLOWCHARTS
Self-Instructional Material 51
Programming
Step 2: long product,
Fundamentals: Algorithms
and Flowcharts //Declare variables as long data types
Step 3: print ‘Enter a value for ‘for’ loop [up to 5]’;
NOTES Step 4: read n;
Step 5: product1;
Step 6: for i1 to n
{
print ‘Enter a value [From 1 to
20]’; read number;
print ‘Values you entered
:’ print number;
productproduct*number;
}
Step 7: print ‘Product of entered items =’;
Step 8: print product;
In this algorithm, the ‘for’loop is used to run the counter value till 10,
which means 10 values are to be accepted for deciding the maximum and
minimum value in the given list.
Implementation of finding the maximum and minimum value of the given
list of numbers
/*—————————— START OF PROGRAM ——————————*/
#include
<stdio.h>
#include
<conio.h> void
main()
{
int number, counter, large,small;
clrscr(); //Clear the screen of
previous for(counter=1; counter<10; i+
+)
{
printf(“Enter next number :
“); scanf(“%d”, number);
if(large<number)
large=number;
//The maximum value is assigned as the value of
number if(small>number) Self-Instructional Material 53
small=number;
Programming
//The value itself is assigned as samll
Fundamentals: Algorithms
and Flowcharts }
printf(“\nMaximum value in the list is = %d”,
large); printf(“\nMinimum value in the list is =
NOTES
%d”, small); getch();
}
The result of the above program is as
follows: Enter next number
12
Enter next number
56
Enter next number
3
Enter next number
90
Enter next number
468
Enter next number
25
Enter next number
54
Enter next number
25
Enter next number
67
Enter next number
38
Maximum value in the list is
=468 Minimum value in the list
is =3
ALGORITHM DEVELOPMENT
In general, an algorithm can be defined as a well-defined procedure for
computation that takes an input of some values and produces an output.
Hence, an algorithm is a sequence of steps which transform an ‘input’ into
‘output’.
It can also be considered as a tool for solving a well-specified
‘computational problem’. The problemstatement defines the input/output
relationship. The algorithm lists a specific computational procedure to reach
that input/output relationship.
54 Self-Instructional Material
To put it simply, ‘An algorithm is a step-by-step procedure for Programming
performing some task in a finite amount of time.’ Fundamentals: Algorithms
and Flowcharts
Definition
An algorithm is composed of a finite set of steps each of which mayrequire NOTES
one or more operations. Every operation may be characterized as either a
simple or complex. Operations performed on scalar quantities are termed
simple, while operations on vector data normally termed as complex.
Properties of Algorithm
The following are the five important properties (features) of algorithm:
Finiteness
Definitiveness
Input
Output
Effectiveness
Finiteness: An algorithm must always terminate after a finite number
of steps. If we trace out the instructions of an algorithm, then for all
cases, the algorithm terminates after a finite number of steps.
Definitiveness: Each operation must have a definite meaning and it
must be perfectly clear. All steps of an algorithm need to be precisely
defined. The actions to be executed in each case should be rigorously
and clearly specified.
Inputs: An algorithm may have zero or more ‘inputs’ quantities.
These inputs are given to the algorithm initially prior to its beginning or
dynamically as it runs. An input is taken from a specified set of objects.
Also, it is externally supplied to the algorithm.
Output: An algorithm has one or more ‘output’quantities. These
quantities have a specified relation to the inputs. An algorithm produces
at least one or more outputs.
Effectiveness: Each operation should be effective, i.e. the operation
must be able to carry out in a finite amount of time.
An algorithm is usually supposed to be ‘effective’ in the sense that all
its operations needs to be sufficiently basic so that they can in principle be
executed exactly in the same way in a finite length of time by someone
using pencil and paper.
Criteria forAlgorithm Design
Several active areas of research are included in the studyofalgorithms. The
following four distinct areas can be identified:
Self-Instructional Material 55
Programming
Fundamentals: Algorithms 1. Devising algorithms
and Flowcharts
The creation of an algorithm is an art. It may never be fully
automated. A few design techniques are especially useful in fields
NOTES other than computer science, such as operations research and electrical
engineering. All of the approaches we consider have applications in a
variety of areas including computer science. However, some
important design techniques such as linear, non-linear and integer
programming are not covered here as they are traditionally covered in
other courses.
2. Validating algorithms
Once you have devised an algorithm, you need to show that it
computes the correct answer for all possible legal inputs. This process
is referred to as algorithm validation. It is not necessaryto express the
algorithmas a program. If it is stated in a precise way, it will do. The
objective of the validation is to assure the user that the algorithm will
work correctly and independently of the issues concerning the
programming language in which it will eventually be written. After the
validity of the method is shown, it is possible to write the program.
On the completion of writing the program, a second phase begins.
This phase is called program providing or sometimes as program
verification. A proof of correctness requires that the solution be stated
in two forms. One form is usually as a program, which is annotated by
a set of assertions about the input and output variables of the program.
The second form is called specification and this may also be expressed
in the predicate calculus. Aproof consists of showing that these two
forms are equivalent in that for every given legal input, they describe
the same output. Acomplete proof of program correctness requires
that each statement of the programming language be precisely
defined and all basic operations be proved correct. All these details
may cause a proof to be very much longer than the program.
3. Analysing algorithms
As an algorithm is executed, it uses computer’s central processing unit
(CPU) for performing operation. It also uses the memory for holding
the program and its data. Analysis of algorithms is the process to
determine the computing time and storage required by an algorithm.
4. Testing a program
Testing of a program comprises two phases: (i) debugging and (ii) profiling.
Debugging refers to the process of carrying out programs on sample
data sets for determining if there are any faulty results. If any faulty
result occurs, it is corrected by debugging. A proof of correctness is
much more valuable than a thousand tests since it guarantees that the
programwill work correctly for a possible input.
56 Self-Instructional Material
Profiling refers to the process of the execution of a correct program on Programming
data sets and the measurement of the time and space it takes in Fundamentals: Algorithms
and Flowcharts
computing the results. It is useful in the sense that it confirms a
previously done analysis and points out logical places for performing
useful optimization. NOTES
An example of profiling:
If we wish to measure the worst-case performance of the sequential search
algorithm, we need to do the following:
Decide the values of n for which the times are to be obtained
Determine for each of the above value of n the data that exhibits the
worst- case behaviour
Algorithm for sequential search:
1. Algorithm seqsearch (a, x, n)
2. //search for x in a[l: n] . a[0] is used as
additional space
3. {
4. i := n; a[0] := x;
5. while(a[i] * x) do i := i “ 1;
6. return
i;
7. }
The decision on which the values of n to use is based on the amount of
timing we
wish to perform and also on what we expect to do with the times once they
are obtained. Assume that for algorithm, our interest is to simply predict how
long it will take, in the worst case, to search for x, given the size n of a.
Algorithms as Technology
If computers were infinitely fast and computer memory was free, you would
be in a position to adopt any correct method to solve a problem. In all
likelihood, you would like your implementation to be adhering to good
software engineering practice. However, you would use the method which is
the easiest to implement.
However, computers may be fast, but they cannot be infinitely fast.
Similarly, memory may be cheap, but it cannot be free. Thus, computing time
and space in memory are bounded resources . You need to use these
resources wisely. Such algorithms which are efficient in terms of time or
space will be helpful.
Efficiency
It has been found that algorithm devices used for solving the same problem
usually differ considerably in their efficiency. These differences are more
significant than those due to hardware and software.
Self-Instructional Material 57
Algorithms and Other Technologies
Algorithms are indeed very important for contemporary computers
considering other advanced technologies:
Programming
Fundamentals: Algorithms Hardware with high clock rates, pipelining and super scalar architectures
and Flowcharts
Easy to use, intuitive graphical user interfaces (GUIs)
Local area networking (LAN) and wide area networking (WAN)
NOTES
A truly skilled programmer possesses a solid algorithmic knowledge and
technique. It separates him/her froma novice. It is true that with modern
computing technology, you can performsome tasks even if you do not have
much knowledge of algorithms. However, if you are with a good background
in algorithms, you can perform much more.
Types of Algorithms
Approximate algorithm
Probabilistic algorithm
Infinite algorithm
Heuristic algorithm
Approximate Algorithm
An algorithm is said to approximate if it is infinite and repeating., 2
e.g. 1.414 ,
58 Self-Instructional Material
Step 5: If B > C Programming
Fundamentals: Algorithms
Print B as the largest
and Flowcharts
number. Else
Print C as the largest number.
NOTES
Step 6: Stop.
Start
Read A,B,C
Yes is No
A>B
is No No is
A>C B>C
Yes Yes
Start
Read A,B,C
disc = b2 – 4ac
Stop Stop
Start
Read Number
Is another
number
No
Is
maximum
Yesnumber = number
> maximum
No
Is
Yesnumber <
minimum = number
minimum
No
Example 2.4: Algorithm for finding maximum and minimum of given n numbers.
Step 1: Read N.
Step 2: Counter 1.
Read number.
Maximum number.
Minimum number.
Self-Instructional Material 61
Programming
Fundamentals: Algorithms
Step 3: If Counter < N go to Step 4.
and Flowcharts Else go to Step 7.
Step 4: Read number.
NOTES Counter Counter + 1.
Step 5: If number > Maximum
Step 6: Maximum number.
Step 7: Else If number < Minimum
Step 8: Minimum number.
Step 9: go to Step 3.
Step 10: Print Maximum. Print Minimum.
Step 11: Stop.
Start
Read N
Counter = 1
Read Number
Is
Counter No
<N
Print maximum print minimum
Yes
real number stop
Counter = counter + 1
Is
Ye number >
maximum = number s maximum
No
Is
Ye number <
minimum = number s minimum
No
62 Self-Instructional Material
Example 2.5: Algorithm for generating Fibonacci numbers up to N. Programming
Fundamentals: Algorithms
The first and second terms in the Fibonacci series are 0 and 1. The third and and Flowcharts
subsequent terms in the sequence are found by adding the preceding two terms
in the series. The Fibonacci series is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
NOTES
Step 1: Read N.
Step 2: Previous 0. Current 1.
Print Previous, Current.
Step 3: Next Previous +
Current.
Step 4: If Next < N
Print Next.
Previous Current.
Current Next,
go to Step 3.
Else go to Step 5.
Step 5: Stop.
Start
Read N
Previous = 0
Current = 1
Print previous
current
Is
Counter No
<N
Yes stop
print Next
Previous = current
Current = next
Self-Instructional Material 63
Programming
Fundamentals: Algorithms Example 2.6: Algorithm for generating first k Fibonacci numbers.
and Flowcharts
Step 1: Read k.
Step 2: Counter 2.
NOTES Previous 0.
Current 1.
Print ‘First k Fibonacci numbers
are:’ Print Previous, Current.
Step 3: Next Previous + Current.
Counter Counter + 1.
Print Next. Previous Current.
Current Next.
Step 4: If (Counter < k) go to Step 3.
Else go to Step 5.
Step 5: Stop.
Start
Read k
Previous = 0
Current = 1
Counter = 3
Is Counter
<N No
Yes
stop
print Next
64 Self-Instructional Material
Example 2.7: Sum of first n Factorials Programming
Fundamentals: Algorithms
The factorial of a non-negative integer n is the product of all positive and Flowcharts
integers less than or equal to n and is denoted by n! It is defined as
follows:
n! = n(n-1) … 2*1 NOTES
Example 2.8: To find largest value and the second largest value of the
list: The largest and second largest values in the given list are determined
by array implementation. Array can contain the various elements of the list.
The algorithm to find the largest and second largest of given list is as follows:
Algorithm to find the largest value and second largest value of the given list
Step 1: integer M, a[M], i, largest, t, second_largest;
Step 2: print ‘Enter a value for array’;
Step 3: read M;
Step 4: for i1 to M
print ‘Enter
values:’; read a[i];
Step 5: if i==1
largesttsecond_largesta[i];
66 Self-Instructional Material
Step 6: else if Programming
a[i]>largest Fundamentals: Algorithms
and Flowcharts
second_largestlargest;
largesta[i];
Step 7: else if a[i]>second_largest && NOTES
a[i]<largest second_largesta[i];
Step 8: else if a[i]<t
ta[i];
Step 9: print ‘Largest value in the given list =’;
Step 10: print largest;
Step 11: ‘Second largest value in the given list =’;
Step 12: print second_largest;
68 Self-Instructional Material
semicolon (;) because the preprocessor is a program that comes before Programming
main() statement. Fundamentals: Algorithms
and Flowcharts
Example 2.9: Determining nth root of a number.
The nth root of a number a is a number where n is positive integer. The nth NOTES
roots are taken with the following iteration where a is the input values and n
is the root value to be taken. The equation is arranged in the following ways:
bna
where a is the number, n is the nth root and b is the value that retains the nth
root of number a. For example, nth root is equal to 3 and number a is equal
to 2 can be written as 23 = 8. The following algorithm is used to find out the
nth root of a given value:
Algorithm to find the nth root of a number:
Step 1: double calculate_root(double,double);
//Declare a calculate_root function having two parameters
Step 2: double Find_nth_Root(double,double,double);
//Declare a calculate_root function having three
parameters
Step 3: double number(double,double);
//Declare a number function having two parameters
Step 4: double x1, NUMBER_OF_ITERATIONS40, n;
//Assign value 1 to x variable and
NUMBER_OF_ITERATIONS=40
Step 5: double N;
//Declare a variable N as double data type
Step 6: double root;
//Declare a variable root as double data type
Step 7: x_label:
//Assign a label named as x_label
Step 8: print ‘Enter root do want [2,3, …5] ?’
Step 9: read n;
//Accept input value n
Step 10: if n<=0
//Check the condition where n is less than 0
Step 11: print ‘Number should be Greater than
0’; Step 12: print n;
Step 13: goto x_label;
//Go to label on x_label
Step 14: y_label:
//Assign a label named as y_label
Step 15: print ‘Enter the number for Root’;
Step 16: read N;
Self-Instructional Material 69
Step 17: if N<=0
Programming
Step 18: print ‘Number should be greater than 0’;
Fundamentals: Algorithms
and Flowcharts Step 19: print ‘PRESS ANY KEY TO ENTER AGAIN’;
Step 20: goto y_label;
NOTES //Go to label on y_label
Step 21: xcalulate_root(n,N);
//x retains the returned value of function calculate_root
Step 22: print ‘The first assumed root is’,x;
Step 23: rootFind_nth_Root(N,n,x);
//root retains the Find_nth_Root returned value
Step 24: print ‘Root of n’,n;
Step 25: print N;
Step 26: print root;
Step 27: double calculate_root(double n,double N)
Step 28: integer i,xr;
//integer i and xr are declared
Step 29: xr1;
//xr is assigned as 1
Step 30: double j1;
//double j is assigned as 1
Step 31: while(1)
Step 32: for i0 to n //Running for loop
{
xrxr*j; //xr retains the value of xr*j
}
Step 33: if xr>N
Return j-1; //Returns j-1
Step 34: jj+1; //j value is increased by 1
Step 35: xr1; //xr value is increased by 1
Step 36: double Find_nth_Root(double NUM,double n,double
X0) //Function Find_nth_Root starts from here.
Step 37: int i;
Step 38: double d1.0;
Step 39: double first_term, second_term, rootX0;
Step 40: for i1 to NUMBER_OF_ITERATIONS
//Body of for loop starts that calculates first term
and second term value of enter values of
NUMBER_OF_ITERATIONS Step 41: dnumber(root,n);
//d retains the n th value of given number.
Step 42: first_term((n-1)/n)*root;
// first_term retains the value of let say 5 (5-1)/5)*
root value
70 Self-Instructional Material
Step 43: second_term(1/n)*(NUM/d); Programming
Step 44: rootfirst_term+second_term; Fundamentals: Algorithms
and Flowcharts
Step 45: print first_term,second_term,root;
Step 46: return root;
Step 47: double number (double x,double n) NOTES
Step 48: double d1;
Step 49: integer i;
Step 50: for i1 to n-1
Step 51: dd*x; //Printing the final nth root value of
given number n
Step 52: return d;
//Returns the resulted value to d
#include<stdio.h>
#include<conio.h>
#define NUMBER_OF_ITERATIONS 40
//Preprocessor directive where NUMBER_OF_ITERATIONS
is defined as macro
double calculate_root(double,double);
double
Find_nth_Root(double,double,double);
double number(double,double);
void main()
{
double x=1,n;
double N;
double root;
x_label:
printf(“\n Enter root value [2,3, …5] ?”);
scanf(“%f”,&n);
if(n<=0)
Self-Instructional Material 71
Programming
{
Fundamentals: Algorithms
and Flowcharts printf(“\nNumber should be Greater than
0”); printf(“Press any key to enter again”);
getch();
NOTES
goto x_label;
}
y_label:
printf(“\n\rEnter a number =
“); scanf(“%f”,&N);
if(N<=0)
{
printf(“\nNumber should be greater than
0”); printf(“\n PRESS ANY KEY TO ENTER AGAIN
…”);
getch();
goto y_label;
}
x = calulate_root(n,N);
printf(“\n\nThe first assumed root is calculated as
%f\n”,x);
root=Find_nth_Root(N,n,x);
printf(“\n\n%f Root of %f =
“,n,N);
printf(“Root value is =
%f”,root); getch();
}
Self-Instructional Material 73
Programming
Fundamentals: Algorithms Enter a Number = 32, Enter a Root = 5. The (n th) 5th root of 32 is 2.
and Flowcharts
Enter a Number = 11, Enter a Root = 4. The 4th root of 11 is 1.82116.
Example 2.10: Greatest Common Divisor (GCD).
NOTES The GCD of two integers is the largest integer value that divides both
integer values where both the values are not zero. The basic identities of
GCD are as follows:
GCD(A,B)=GCD(B,A)
GCD(A,B)=GCD(-A,B)
GCD(A,0)=ABS(A)
If the two given values are 10, 12 then the greatest common factor is
the number that divides both the values 10 and 12.
74 Self-Instructional Material
The GCD of two given integers (a and b) is the largest positive }
integer which divides both integers a and b, for example, gcd (10,12)=2. end:;
The following table shows the step-by-step procedure to get resultant GCD }
value:
Let the two values be, m =15 and n = 18.
div quo %Quo %div Resultant value
0 1
1 15 False True 1
2 7 False False 1
3 5 False True 3
4 3
The loop exits and returns 3. So, the resultant GCD value of the two
given values 15 and 18 is 3.
Program to find GCD of given values:
/*—————————— START OF PROGRAM ——————————*/
#include
<stdio.h>
#include
<conio.h> void
main()
{
int m, n, q, r;
clrscr();
printf(“Enter two
values:”); scanf(“%d%d”,
&m,&n);
if (m==0||n==0)
printf(“One number is
Zero”); else
reach:
{
q=m/n;
r=m –
q*n;
}
if(r==0)
{
printf(“GCD Value is : %d”,
n); goto end; //Go to end
label
}
else
{
m=n=r;
goto
reach;
Programming Fundamentals: Algorithms
and Flowcharts
NOTES
Self-Instructional Material 75
Programming
Fundamentals: Algorithms The GCD can also be calculated applying Euclidean algorithm. If the integers a
and Flowcharts and b are two positive integers and n is the remainder, then (a, b) = (b,
r).
Euclidean_gcd(a,b)
NOTES
Step 1: integer x, y, f, d;
Step 2: xf; yd;
Step 3: if y=0 return
x Step 4: rx mod y;
Step 5: xy;
Step 6: yr;
Step 7: goto Step 2.
78 Self-Instructional Material
The binary number 1011 is equal to decimal number 11. Programming
/*—————————— START OF PROGRAM ——————————*/ Fundamentals: Algorithms
and Flowcharts
#include <stdio.h> //Declaring Header
files #include <conio.h>
#include <math.h> NOTES
void main() //Start main() function
{
int number,d_val,temp_val,counter,a_val;
// Declaring integer data types
variables temp_val=number;
//Assigning temp_val is equal to
number d_val=0;
counter=0; //Initailizing 0 to
counter printf(“\n Enter a number”);
scanf(“%d”, &number); //Accept input
value if (temp_val>0)
{
a_val = temp_val%10;
//Returns remainder to
d_val p_val =
pow(2,counter);
//Returns counter value raise to the power 2 to
p_val variable
d_val=d_val+ a_val*p_val;
//The value of d_val is added to multiplied value of
a_val and p_val
temp_val = int(temp_val/10)
//if temp_val contains fraction value, int()
function changes the integer type value
counter = counter +1;
//Counter variable is increased
}
printf(“Decimal Value = %d”, d_val); //Printing the
binary value
getch();
//Pressing key to return the program
}
This program is able to convert the binary number into decimal number.
The result of the program is as follows:
Enter a number = 1011
Decimal Value = 11
Self-Instructional Material 79
Programming
Fundamentals: Algorithms When a theoretical algorithm design is combined with the real-world
and Flowcharts data, it is called algorithm engineering. When you take an algorithm and
combine it with a hardware device that is connected to the real-world, you
can verify and validate the algorithm results and behaviour more precisely and
NOTES
accurately. Asimple data acquisition or stimulus device may be considered as
the real-world device. Alternatively, you can implement an algorithm on
some embedded platform, such as a field-programmable gate array
(FPGA) or microprocessor which can be similar to the final system design.
The first specific use of the term, ‘algorithm engineering’ was at the
inaugural Workshop on Algorithm Engineering (WAE) in 1997.
It has of late been used for describing the steps in a graphical system
design: ‘A modern approach to design, prototype and deploy the embedded
systems which combine open graphical programming with the commercial
off-the-shelf (COTS) hardware for dramatically simplifying development,
bringing higher-quality designs with a migration to custom design.’
With the help of algorithm engineering, you can transform a pencil-
and- paper algorithm into a robust, efficient, well-tested and easily usable
implementation. It covers various topics, from modelling cache behaviour to
the principles of good software engineering. However, experimentation is its
main focus.
80 Self-Instructional Material
Check for any unusual sounds. For example, the hard drive creating Programming
sound when the computer is switched on. Fundamentals: Algorithms
and Flowcharts
Start the computer using an external booting or start-up disk.
If the problem persists then contact the hardware engineer to resolve NOTES
it.
Problem Solving for Incorrect Algorithms
An algorithmis used in mathematics, computing, linguistics and other allied
subjects to efficiently solve a problem with the help of set order of
instructions. It is used for data processing, calculation, etc. Flowcharts are
also frequently used to express algorithms graphically. The computer
performs a job with the help of an algorithm which defines the steps to be
performed because every algorithm contains well- defined directives to
complete a task. Beginning from an initialposition, the directives/ instructions
explain the steps of computation that proceeds via well-defined sequences
ofsuccessive states and finally terminate in end state. Thus, an algorithm must
be correct because it is a process which performs some specific sequences of
instructions. If an algorithm is incorrect then either it will not produce the
desired result or it may not function. The following are the methods of
problem solving:
Problem Solving
• Using the programming process for problem solving.
• Solving the problem by:
– analysing the problem by systematically and carefully understanding
it;
– outlining the necessities of the problem;
– designing algorithm steps for the problem;
– implementing the algorithm;
– modifying the program when there is change in problem domain.
Assumptions can be identified behind the problem which play
important role in problem solving. Sometimes these are ignored because
efforts are not made to identify the hidden and unknown assumptions which
may be the real cause of problem. Assumptions are essential because they set
limits to the problem by providing structure to work, reflect preferred values
to be maintained all over the solution and make simpler the problem by
building it more controllable.
Problem Solving Techniques
The basic terminology related to problem solving includes purpose,
situation, problem, cause, solvable cause, issue and solution. All these are
explained in the following:
Purpose: Purpose is considered as the first step in problem solving,
because if the purpose is not clear one cannot resolve the problems. Self-Instructional Material 81
Programming
Fundamentals: Algorithms Situation: Situation is the circumstance which can be good or bad.
and Flowcharts The problematic situations are recognized because all the situations are not
problematic.
NOTES Problem: Problem is the specific part of a situation. The true problems
are identified by specifying the purpose.
Cause: Cause is the effect of a problem. The causes must be
distinguished from problems so that there is correct judgment of situation
and basic problem. Though problems are part of a situation, hence problems
are more common than causes are. Basically, causes are the precise facts
which cause problems. Problem solving can only be specific if specific facts
of causes are distinguished from problems.
Solvable cause: In a problem some causes can be solvable while
some may be unsolvable. While solving a problem, the solvable causes are
selected, because trying to solve unsolvable causes will simply be wastage of
time. To extract solvable causes is an important step in problem solving.
Issue: Issue is the opposite expression of a problem. It specifies that
the cause of the problem must be solved.
Solution: Solution is the precise act to solve any problem. It is similar
to an exact action required to solve an issue. Issues are not the exact
solutions but it specifies actions to be solved.
Other Problem Solving Techniques
Rational thinking: Rational thinking method is also used for problem solving. It
includes the following points:
Setting the perfect situation
Identifying the current situation
Comparing the perfect situation and the current situation
Identifying the problem situation
Breaking down the problem into various causes
Visualizing the alternate solutions to the causes
Evaluating and selecting the logical alternate solutions
Implementing the solutions
The rational thinking method is used to solve almost all types of problems.
Systems thinking: Systems thinking is the scientific approach for
problem solving. The system causing problemis analysed on the basis of
systems functioning. The following are the types of system that are included in
system thinking:
Purpose
Input
Output
82 Self-Instructional Material
Function Programming
Fundamentals: Algorithms
Inside cause (Solvable) and Flowcharts
Outside cause (Unsolvable)
Result
NOTES
To understand the purpose of the problem the input is prepared
using functions to get the desired output. The output may or may not define
the purpose and the end result of the function can be different fromthe purpose
whichis produced by outside cause and inside cause. The inside cause can be
solved whereas the outside cause is not. Systems thinking is considered as
the most comprehensible and practical method for problem solving.
Cause and Effect Thinking: Conventionally, this defines cause and
effect relations. First the cause is checked for the specific problem.
Checking a cause and effect relation and then using problem solving
method is a traditional and successful approach.
Hypothesis thinking: After collecting all relevant information the
problem can be efficiently solved. Sometimes all the relevant information is
not available and in order to collect all one may need longer time frame. In
such cases, hypothesis thinking is very effective because it does not depend on
all collected information. The hypothesis is developed on the basis of
information available. Once the hypothesis is developed, minimum
information is collected to prove this hypothesis. If the analysis proves that the
first hypothesis is correct, then further information is not collected, but if the
first hypothesis is incorrect then the next hypothesis is developed on the
basis of available information. This method is considered as an efficient
problem-solving method, because no time is wasted in collecting pointless
information.
FLOWCHARTING
In the beginning, the use of flowcharts was restricted to electronic data
processing for representing the conditional logic of computer programs.
The1980s witnessed the emergence of structured programming and
structured design. As a result of this, in database programming, data flow
and structure charts began to replace flowcharts. With the widespread
adoption of suchALGOL-like computer languages as Pascal, textual models
like pseudocode are being used frequently for representing algorithms. Unified
modelling language (UML) started the synthesis and codification these
modelling techniques in the 1990s.
A flowchart refers to a graphical representation of a process which
depicts inputs, outputs and units of activity. It represents the whole process
at a high or detailed (depending on your use) level of observation. It serves
as an instruction manual or a tool to facilitate a detailed analysis and
optimization of workflow as well as service delivery.
Self-Instructional Material 83
Programming
Fundamentals: Algorithms Flowcharts have been in use since long. Nobody can be specified as
and Flowcharts the ‘father of the flowchart’. It is possible to customize a flowchart according
to need or purpose. This is why flowcharts are considered a veryunique quality
improvement method for representing data.
NOTES
Symbols
A typical flowchart has the following types of symbols:
Start and end symbols: They are represented as ovals or rounded
rectangles, normally having the word ‘Start’ or ‘End’.
Arrows: They show the ‘flow of control’ in computer science. An
arrow coming from one symbol and ending at another symbol shows
the transmission of control to the symbol the arrow is pointing to.
Processing steps: They are represented as rectangles.
Example: Add 1 to X.
Input/output symbol: It is represented as a parallelogram.
Examples: Get X from the user; display X.
Conditional symbol: It is represented as a diamond (rhombus). It has
a Yes/No question or True/False test. It contains two arrows coming
out of it, normally from the bottom and right points. One of the arrows
corresponds to Yes or True, while the other corresponds to No or False.
These two arrows make it unique.
There are also other symbols in flowcharts may contain, e.g.
connectors. Connectors are normally represented as circles. They represent
converging paths in the flowchart. Circles contain more than one arrow.
However, only one arrow goes out. Some flowcharts may just have an arrow
point to another arrow instead. Such flowcharts are useful in representing an
iterative process, what is known as a loop in terms of computer science. A
loop, for example, comprises a connector where control first enters
processing steps, a conditional with one arrow exiting the loop, and another
going back to the connector. These are listed in Table 2.1.
84 Self-Instructional Material
Table 2.1 Symbols Used in Flowcharts Programming
Fundamentals: Algorithms
and Flowcharts
Shape Symbol Symbol Name Purpose
To represent a decision or
Diamond Decision
comparison control flow
To represent a group of
Hexagon Repetition/ Looping
repetitive statements
It is now used at the beginning of the next line or page with the same
number.
Thus, a reader of the chart is able to follow the path.
Instructions
The following is the step-by-step process for developing a flowchart:
Step 1: Information on how the process flow is gathered. For this, the
following tools are used:
Conservation
Experience
Product development codes Self-Instructional Material 85
Programming
Fundamentals: Algorithms Step 2: The trial of process flow is undertaken.
and Flowcharts
Step 3: Other more familiar personnel are allowed to check for accuracy.
Step 4: If necessary, changes are made.
NOTES
Step 5: The final actual flow is compared with the best possible flow.
Construction/Interpretation Tips for a Flowchart
The boundaries of the process should be defined unambiguously.
The simplest symbols should be used.
It should be ensured that each feedback loop contains an escape.
It should be ensured that there is only one output arrow out of a
process box. Otherwise, it would require a decision diamond.
Types of Flowcharts
A flowchart is common type of chart representing an algorithm or a process
and showing the steps as boxes of different kinds and their order by
connecting these with arrows. We use flowcharts to analyse, design,
document or manage a process or program in different fields.
There are many different types of flowcharts. On the one hand, there
are different types for different users, such as analysts, designers, engineers,
managers or programmers. On the other hand, those flowcharts can represent
different types of objects. Sterneckert (2003) divides four more general types
of flowcharts:
Document flowcharts showing a document flow through system
Data flowcharts showing data flows in a system
System flowcharts showing controls at a physical or resource level
Program flowchart showing the controls in a program within a system
However, there are several of these classifications. For example,
Andrew
Veronis named three basic types of flowcharts: the system flowchart, the
general flowchart, and the detailed flowchart. Marilyn Bohl (1978) stated
‘in practice, two kinds of flowcharts are used in solution planning: system
flowcharts and program flowcharts...’. More recently, Mark A. Fryman
(2001) stated that there are more differences. Decision flowcharts, logic
flowcharts, systems flowcharts, product flowcharts and process flowcharts are
just a few of the different types of flowcharts that are used in business and
government.
Interpretation
Analyse flowchart of the actual process.
Analyse flowchart of the best process.
Compare both charts looking for areas where they are different. Most
of the time, the stages where differences occur are considered to be the
problem area or process.
86 Self-Instructional Material
Take appropriate in-house steps to correct the differences between Programming
the two separate flows. Fundamentals: Algorithms
and Flowcharts
Example: Process flowchart—finding the best way home.
This is a simple case of processes and decisions in finding the best route
NOTES
home at the end of the working day.
A flowchart provides the following:
Communication: Flowcharts are excellent means of communication.
They quickly and clearly impart ideas and descriptions of algorithms
to other programmers, students, computer operators and users.
An overview: Flowcharts provide a clear overview of the entire
problem and its algorithm for solution. They show all major elements
and their relationships.
Algorithm development and experimentation: Flowcharts are a
quick method of illustrating program flow. It is much easier and faster
to try an idea with a flowchart than to write a program and test it on a
computer.
Check program logic: Flowcharts show all major parts of a program.
All details of program logic must be classified and specified. This is a
valuable check for maintaining accuracy in logic flow.
Facilitate coding: Aprogrammer can code the programming
instructions in a computer language with more ease with a
comprehensive flowchart as a guide. Aflowchart specifies all the steps
to be coded and helps to prevent errors.
Program documentation: Aflowchart provides a permanent recording
of program logic. It documents the steps followed in an algorithm.
Advantages of Flowcharts
Clarify the program logic.
Before coding begins, a flowchart assists the programmer in
determining the type of logic control to be used in a program.
Serve as documentation.
Serve as a guide for program coding of program writing.
A flowchart is a pictorial representation that may be useful to the
businessperson or user who wishes to examine some facts of the logic
used in a program.
Help to detect deficiencies in the problem statement.
Limitations of Flowcharts
Program flowcharts are bulky for the programmer to write. As a
result many programmers do not write the chart until after the
program has been completed. This defeats one of its main purposes.
Self-Instructional Material 87
Programming
Fundamentals: Algorithms It is sometimes difficult for a business person or user to understand the
and Flowcharts logic depicted in a flowchart.
Flowcharts are no longer completely standardized tools. The newer
NOTES structured programming techniques have changed the traditional format
of a flowchart.
Differences between Flowcharts and Algorithms
Flowchart
It is the graphical representation of the solution to a problem.
It is connected with the shape of each box indicating the type of
operation being performed. The actual operation, which is to be
performed, is written inside the symbol. The arrow coming out
ofsymbolindicates which operation to perform next.
Algorithm
It is a process for solving a problem.
It is constructed without boxes in a succession of
steps. An algorithm can be written in the following three
ways:
Straight sequential: A series of steps that can be performed one after
the other.
Selection or transfer of control: Making a selection of a choice
from two alternatives of a group of alternatives
Iteration or looping: Performing repeated operations.
The following are the examples of algorithms and flowcharts for some different
problems:
Examples of Straight Sequential Execution
Example 2.12: Write a flowchart to find the maximum and minimum of given
numbers.
88 Self-Instructional Material
Programming
START Fundamentals: Algorithms
and Flowcharts
Read a, b
NOTES
Is a>b T
Write “max:”,a, “min:”,b
STOP
Example 2.13: Write the various steps involved in executing a ‘C’ program
and illustrate it with the help of a flowchart.
Executing a program written in C involves a series of steps. They are as follows:
Creating the program.
Compiling the program.
Linking the program with functions that are needed from the C library.
Executing the program.
Although these steps remain the same irrespective of the operating
system, system commands for implementing the steps and conventions for
naming files may differ on different systems.
An operating system is a program that controls the entire operation
of a computer system. Allinput/output operations are channelled through the
operating system. The operating system, which is an interface between the
hardware and the user, handles the execution of user programs.
The two most popular operating systems today are UNIX (for
minicomputers) and MS-DOS (for microcomputers).
Self-Instructional Material 89
Programming System Ready
Fundamentals: Algorithms
and Flowcharts
Program Code Enter Program
Source Program
C Compile
Compiler Source Program
Object code
No
System Library Link with System Library
No Errors
CORRECT OUTPUT
STOP
Read FirstNum
Read SecondNum
Write Sum
Stop
90 Self-Instructional Material
Algorithm for addition of two numbers: Programming
Fundamentals: Algorithms
Step 1: Start and Flowcharts
Step 2: Read FirstNumber Step 3: Read SecondNumber
Step 4: Sum= FirstNumber + SecondNumber Step 5: Write (Sum)
Step 6: Exit
NOTES
b. Draw a flowchart to find the larger number between two numbers and
write an algorithm for it.
START
Read a, b
IsT
a>b Write a
F
Write b
STOP
Step 1: Start
Step 2: Read a and b
Step 3: IF a > b THEN Write (a)
ELSE Write(b)
Step 5: Stop
Read N
IsF
N>0 STOP
Write N
N=N-1
Self-Instructional Material 91
Programming
Fundamentals: Algorithms d. Draw a flowchart to display number of odd digits in a given number.
and Flowcharts Algorithm for displaying Natural numbers between 1 and N in Reverse Ord
START
Read N
S=0
F
Is N Write S
R= N%10 STOP
Is R%2 T
S=S+1
F
N=N/10
92 Self-Instructional Material
e. Draw a flowchart to evaluate the series 1! + 2!+ 3!+ ... +N! Programming
Fundamentals: Algorithms
Algorithm for evaluating the series and Flowcharts
1!+2!+…..+N!
Step 1: Start
Step 2: Read N NOTES
Step 3: S=0,I=1
Step 4: Repeat while I<=N
K=factorial(I)
S=S+K
I=I+1
Step 5. Write(S)
Step 6: Exit
START
Read N
S=0 I=1
F
Is I<=N
Write S
T
K= factorial(I) STOP
S=S+K
I=I+1
f. Flowchart to evaluate N!
factorial(N)
F=1
F
is N Return F
T
F=F*N
N=N-1
Self-Instructional Material 93
Programming Algorithm to find factorial(N).
Fundamentals: Algorithms and
Where N is a value and function returns
Flowcharts
Factorial value for N
Step 1: F=1
NOTES Step 2: Repeat while N <> 0
F=F*N
N=N-1
Step 3: Return F
F
F=factorial(I) STOP
P=power(X, I)
S=S+P/F
I=I+1
94 Self-Instructional Material
h. Flowchart to evaluate Power(X, Programming
N) Fundamentals: Algorithms
and Flowcharts
power(X,N)
NOTES
I=0 P=1
Is I<N F
Return P
P=P*X
I=I+1
Step 1: I=0,P=1
Step 2: Repeat while I<N
P=P*X I=I+1
Step 3: Return P
STEPWISE REFINEMENT
The program is broken into smaller subproblems and the required algorithm
is specified for each subproblem is known as stepwise refinement. It
supports the breaking of complicated task into smaller task. The word
refinement includes the process of high level procedure specifications. The
stepwise refinement mechanism is used in programming concepts. Arefinement
process in writing a program divides the problem from the top most segment.
It segments into series of small tasks. These tasks perform a sequence of
smaller tasks. These tasks perform an order of performance. For example take
an example of calculating sum of two given values. The steps taken in
refinement concept are as follows:
Self-Instructional Material 95
Programming
Initialize
Fundamentals: Algorithms
and Flowcharts variables Input the
values
Assign third variable that keeps the sum value of
NOTES
variable one and variable two
Print sum
All the variables are to be initialized before using them. The sum
value is decided as per user input value and is not initialized instead
calculated as per provided values. The pseudocode ‘Print sum’ can be
refined as follows:
Input for two values
Set a variable that counts the summation of two
values Print “Sum”, sum
The given problem can be broken down into components which can
be executed directly into the components and associated with
implementation language, such as PROLOG. For example, a procedure is
written as follows:
Biggest(X, Y) :- (X=0; X=1), Y is X+1
true if n = 2 otherwise
prime(n, q)=
prime_test(n, q, false)
The iterative function prime(n,q) is declared as prime: P × N
{true, false}, where n is the defined prime number and q is the
maximum number of elements.
Self-Instructional Material 97
Programming
Fundamentals: Algorithms In Figure 2.2, the four levels are set as SYSTEM, SUB-SYSTEM,
and Flowcharts PROCEDURES and PROGRAMS respectively. The level 1 is SYSTEM
that determines feasibility study including information requirements and data
definitions of the required system, whereas level 2 is SUB-SYSTEM that
NOTES
determines logical design and input/output values. The level 3 is
PROCEDURES containing workflow, machine interface and primary
physical files and level 4 is SOFTWARE ENGINEERING that contains all
aspects of program dependencies, command language, programlogic, method
of implementation, and layouts of input and output.
Stepwise refinement (SWR) is considered as fundamental aspect of
programming sequence. This technique is started with module defining that
writes top level, specifies step, proves structure and then writes step. The
specifying step and writing step are encircled because of depending on user’s
input values or if the values are defined within the program write step
depends on the values (Figure 2.3).
Write top level
Specify Step Prove Structure Write Step
98 Self-Instructional Material
This pseudocode can be refined as follows: Programming
Fundamentals: Algorithms
If counter is not considered as zero, set the average value to the total and Flowcharts
divided by counter value. It prints the average else a message as “No
grades are provided.”
NOTES
Note: A fatal error occurs if a number is divided by zero. So grade is
determined if the values for subjects are provided properly.
Third Refinement
The third refinement keeps the following sequence of pseudocode:
Initialize zero for total value🠆Initialize zero for counter variable🠆Input a
value for first grade🠆Add this grade for running total🠆Add one to the grade
counter🠆Input the very next grade🠆If counter value is not equal to zero🠆Average
is set to the total value divided by counter🠆Print the average🠆Print the message
“No grades are provided.”
The top down stepwise refinement algorithm supports the following
steps:
Divide and conquer strategy
Change the programming part from general to specific
Divide the problems into levels that makes strategy
Do not allow storage concept, for example, put the number into a
specified variable X.
Determine the process of division. Divide by task is possible what
to do?
A general algorithm specifies in stepwise refinement so that it is
suitable for while loop. This is to be continued until and unless number is
not equal to 0. The required pseudocode is necessary to get the result for
positive integer to get the output in number of terms N in the following way:
get a positive integer N from the
user; while N is not 1:
compute N = next term;
output N;
count the term;
output the number of terms;
If you are a movie buff and a fan of old detective movies, it will be very
easy for you to recall how Mr Chan, when the occasion demanded, used to
introduce his sons to his clients. He would say, ‘This is my number 1 son,
my number 2 son, etc.’ It shows that although computers were not heard of
and were to be invented long after that time, Mr Chan used the method of
referring to his sons by their subscripts. You will see the essence of this
method while using arrays in the following example.
Suppose your company has plans to form a new metal alloy and you
have been entrusted with the responsibility of developing a computer
simulation program that provides heat statistics of this new substance to show
how heat passes through it. For the purpose, a thin rod of this new material
is to be used, which is to be placed between two heat sources, with each
source maintaining a constant temperature. It is not required that both heat
sources maintain the same temperature. The initial temperature of the rod is
kept uniform and the rod is fully insulated from its surroundings.
This problem can be solved using a method known as ‘finite
difference method’. To ascertain the temperature at different points along the
rod, the rod is divided into n equal segments of length h each.
Now assume that for your program you divide the whole rod into
1000 equal segments. At the initial stage, the leftmost segment of the rod has
the same temperature as the heat source at the left end, and the same is the
case with the rightmost segment of the rod. The rest of the rod has the initial
temperature. You are required to write a program that simulates the heat flow
along the rod with the passage of time by calculating each segment’s
temperature.
Let us leave aside the actual heat dynamics of this given problem
and concentrate on something that is the main focus of this section. Consider
the 1000 segments the temperature of which is to be measured. For this
purpose, you require 1000 variables; just imagine the complexity of writing
such a program. In real-life situation the number can go much higher, say
10,000 segments.
The problem of using such a great number of variables can be easily
resolved by the use of arrays. Whether there are 1 million variables or
10,000, with the use of arrays both situations can be handled with any
additional complexity. Let us understand arrays in detail.
NOTES
l1
l2+1
...
i1-1
i1
...
u1
Now to calculate the address of the element a[i1][i2], first traverse the i1-l1
rows (each row u 2 l2 1 elements) and then i2 l2 elements. Hence
contains
the address of ai1 i 2 i1 l1 u 2 l 2 1 i 2 l 2 .
Now consider a 3-dimensional array a[0 ... 2] [0 ... 2] [0 ... 1].
i n l n
n
= i l a j with a u k lk 1
j j k
j1...n j j1 an
1
Column Major
Ordering
In this technique we store the columns of an array first. Consider an one
dimensional array al1 ...u1. Suppose its base address (address of the first
element) is .
...
u1
Hence for an N-dimensional array al1 ...u1 l 2 ...u 2 ...l n ...u n , if the
base address be (i.e. the address of al1 , l 2 ,..., l n then the address of
i 2 l 2 u1 l1 1
....
10. The sum of the n rth powers grows as the (r + 1)th power: k r
is (nr1 )
,
k 1
n
e.g. i (n
is (n2)
k
1
1)n
General Rules 2
1. Simple statement sequence: It is to be noted first that a sequence of
statements executed once only is O(1). It is immaterial as to how
many statements are in the sequence; only that the number of
statements (or the time that they take to execute) is constant for all
problems.
2. Simple loops: If a problem of size n can be solved with a simple loop.
For example,
for (i = 0;i < n; ++i)
{
Statement(s);
}
The inner loop i = 0, 1, 2…n gets executed n times, so the total is:
i n(n
n
and the complexity is O(n2).
1)
1 2
Note that the two nested loops also have the same complexity, so the
variable number of iterations of the inner loop does not affect the ‘big
picture’. However, if the number of iterations of one of the loops
decreases by a constant factor with every iteration as shown here:
i = n;
while(i > 0)
{ for(i = 0;i < n; ++i)
{
Statement(s);
}
h = h/2;
}
Then there are log2 n iterations of the outer loop and the inner loop is
O(n). So the overall complexity is O(n log n) .
NOTES O(1) < O(log n) < O(n) < O(n log n) < O(n2) < O(n3) < O(2n) <= O(n!)
Problem of Search
In computer science, a search algorithm refers to an algorithm taking a
problem as input and returning a solution to the problem, usually after it
evaluates of the various possible solutions. Most problem-solving algorithms
studied by computer scientists
Self-Instructional Material 123
Programming
Fundamentals: Algorithms are search algorithms. Search space refers to the set of all possible solutions
and Flowcharts to a problem. In the Brute-force search, commonly known as naïve or
uninformed algorithms, the simplest method of the searching through the
search space is used, whereas in informed search algorithms, heuristic
NOTES
functions are used for applying knowledge about the structure of the search
space so that the amount of time spent in searching is reduced.
Searching refers to an operation of finding the location of an item in a
table or a file. Depending on the location of the records to be searched,
searching techniques are classified into the following two types:
External searching: When the records are stored in files or disk or tape or any
secondary storage, then the searching is known as external searching.
Internal searching: When the records to be searched are stored entirely within
computers memory, then it is known as internal searching.
The locating ofa particular element in a data structure is called searching.
Generally, the methods are used for searching are as follows:
1. Linear search
2. Binary search
3. Fibonacci search
Linear Search or Sequential Search
Linear search is the easiest and least efficient searching technique. In this
technique, the given list of elements are scanned from the first one till either
the required element is found or the list is exhausted. This technique is used
in direct access media such as magnetic tapes.
Example of linear search: Find an element 77 from the given list using
linear search. The list of elements is: 10, 25, 77, 16, 47, 98
Linear search starts by checking the target element (i.e. 77) with the
first element of the list, i.e. 10, which is not equal to the target element; search
continues with the second element, i.e. 25, which is also not equal to the
target element and search continues with the third element, i.e. 77, which is
equal to the target element (=77). So, the search is stopped.
Algorithm for linear search:
LINEAR_SEARCH (L, N, E)
1. [Initialization
] Loc = 1
L[N + 1] = E
2. [Search the element in the
vector] REPEAT WHILE ( K[Loc]<> E
) DO
Loc = Loc + 1
The average linear search times are proportional to the size of the array, i.e.
O(N)
Note: If an array is twice as big, it will take twice as long to search.
Implementation of Linear Search to Find a String from a String Vector/
Array
Program for linear search of strings:
/*—————————START OF PROGRAM——————————*/
#include<stdio.h>
#define MAXROWS 10
#define MAXCOLS 20
#define NOTFOUND -1
typedef char STRINGS[MAXROWS][MAXCOLS];
typedef char STRING[MAXCOLS];
int LSearch(STRINGS s,STRING target,int n)
{
int loc=0;
strcpy(s[n],target);
while(strcmp(s[loc],target))
loc++;
if(loc==n)
return NOTFOUND;
else
return loc;
}
void main()
{
ST RING S a= {“M ON”, ”TUE ”,” WED” ,”T HU”,
”FRI ”, ”SAT”,”SUN”};
int index;
index=LSearch(a,”WED”,7);
if(index==NOTFOUND)
printf(“Record not found”);
Self-Instructional Material 125
Programming
els
Fundamentals: Algorithms
and Flowcharts e printf(“Record found at Location:%d”,index+1);
10 12 18 23 53 67 88 99 102
0 1 2 3 4 5 6 7 8
10 12 18 23 53 67 88 99 102
0 1 2 3 4 5 6 7 8
Note: In the preceding two programs, the array should contain sorted values;
otherwise, use any sorting algorithm before calling BSearch.
Algorithm for Binary Search Using Recursive Technique
Function BSearch(Vector,First_Index,Second_Index,
Target)
1.[Search vector between First_Index and Second_Index
for target]
IF First_Index>Second_Index)
Loc=0
ELSE
Middle_Index=(First_Index+Second_Index)/2;
IF Target > Vector[Middle_Index]
Loc=Bsearch(Vector,Middle_Index+1,Second_Index,Target)
ELSE
IF Target < Vector[Middle_Index]
Loc=Bsearch(Vector,First_Index,Middle_Index-1,
Target)
ELSE
Loc=Middle_Index
2.[Finished]
RETURN(Loc)
In the above algorithm, L[i] and R[j] are the smallest elements of
Self-Instructional Material 137
L and R that are not copied back into A. Figure 2.4 shows the
mergesort process that is based on above mentioned algorithm:
Programming
Fundamentals: Algorithms A … 1 6 6 8 826 9 32 261 329 4242 43
43 …
and Flowcharts
k k k k k k k k
merge
NOTES
L 6 8 26 32 R 1 9 42 43
i i i i i j j j j j
A … 6 8 26 32
32 11 9 4242 43
43 …
p
m
Figure 2.4 Sort the Elements [1, 6, 8, 9, 26, 32, 42, 43] Using Mergesort
The arrays A_Array and B_Array are the input arrays that contain elements
in ascending order. Their sizes are m and n respectively. The C_array
is the output array containing the elements from the two combined arrays in
sorted order.
74 13 52 34 6
13 74 52 34 6
13 52 74 34 6
13 52 34 74 6
13 52 34 6 74
13 52 34 6 74
Apply the same procedure for the unsorted array and repeat the same
process until the elements are not exchanged in any of the pass, then result
will be the sorted list: 6, 13, 34, 52, 74.
Implementation of Bubble Sort to Sort Strings of Vector/Array
Program for bubble sort of numbers:
/*—————————START OF PROGRAM—————————*/
#include<stdio.h>
#include<conio.h>
#define MAXCOLS 20
#define MAXROWS 10
typedef char STRINGS[MAXROWS][MAXCOLS];
typedef char STRING[MAXCOLS];
void bub_sort(STRINGS a,int
n)
142 Self-Instructional Material
{ Programming
int i,j; Fundamentals: Algorithms
and Flowcharts
for(i = 0;i <n – 1; ++i)
{
int pass = 0; NOTES
for(j = 0; j < n – 1 – i; ++j)
{
if(strcmp(a[j], a[j + 1]) > 0)
{
STRING temp;
strcpy(temp,a[j]);
strcpy(a[j], a[j +
1]); strcpy(a[j +
1],temp); pass = 1;
}
}
if(pass == 0)
break;
}
}
void main()
{
STRINGS a = {“EE”,”BA”,”AB”,”CD”,”AA”};
int i;
clrscr();
bub_sort(a,5);
for(i = 0; i < 5; +
+i) printf(“%s
“,a[i]);
}
/*——————————END OF PROGRAM——————————*/
OUTPUT: AA AB BA CD EE
Selection Sort
Selection sort is a simple sorting technique to sort a list of elements. In this
method, first find the smallest value in the array. Exchange it with the first
element. Find the next smallest and exchange it with the second element.
Continue in this manner till all elements are completed. Adisadvantage of
selection sort is that its running time depends only slightly on the amount of
order already in the given list of elements.
SELECTION_SORT(A,N)
[Where A is a vector having N
elements] 1.[Loop on I index]
REPEAT THRU Step 4 FOR I = 1, 2,..., N “ 1
2.[Initially assume minimum index is in
I] Mindex = I
144 Self-Instructional Material
3. [For each pass, get small
value] REPEAT FOR J = I + 1 to
N
IF A[MIndex] >A[J] THEN Programming
Mindex = J 4. Fundamentals: Algorithms
and Flowcharts
[Interchange Elements]
IF Mindex <> I
THEN NOTES
A[I]A[Mindex]
5.[Sorted values will be
returned] RETURN
Set of elements 1st Iteration 2nd Iteration 3rd Iteration 4th Iteration 5th Iteration
16 1 1 1 1 1
19 19 2 2 2 2
4 4 4 4 4 4
1 16 16 16 16 16
20 20 20 20 20 19
2 219 19 19 20
}
}
void main()
{
STRINGS a = {“EE”, “BB”, “EA”, “DD”, “AA”};
int i;
sel_sort(a, 5);
for(i = 0; i < 5; +
+i) printf(“%s “,
a[i]);
}
/*—————————END OF THE PROGRAM—————————*/
OUTPUT: AA BB DD EA EE
Insertion Sort
Insertion sort refers to a simple sorting algorithm. In it, the sorted array (or
list) is built one entry at a time. As compared to more advanced algorithms,
such as quick sort, heap sort or merge sort, it is less efficient on large lists.
However, insertion sort has many advantages, such as:
Its implementation is simple.
It is efficient for every small data sets.
It is effective for data sets that are already considerably sorted. The
time complexity is O(n + d), where d is the number of inversions.
Practically it is more effective as compared to most other simple
quadratic (i.e. O(n2)) algorithms, such as selection sort or bubble sort.
The average running time of insertion sort is n2/4. Further, in the best
case scenario, the running time is linear.
<x x x
becomes
Sorted partial result Unsorted data
<x x x
1 2 3 … (i-1) i (i+1) N
NOTES
The array which is already sorted is considered the best case input. In
the given case, insertion sort has a linear running time, i.e. O(n). During each
iteration, the first remaining element of the input would only be compared with
the rightmost element of the sorted subsection of the array.
An array sorted in the reverse order is the worst case input. In the
given case, insertion sort has a quadratic running time, i.e. O(n2). Every
iteration of the inner loop scans and shifts the entire sorted subsection of the
array before the next element is inserted. The average case is also quadratic.
That is why the insertion sort is not practical for sorting large arrays.
However, for sorting arrays having less than ten elements, insertion sort is
one of the fastest algorithms.
if left.last_item >
right.first_item result =
merge(left, right)
else
result = append(left, right)
return result
Some of the sorting algorithms are required to merge the ordered list.
One popular sorting algorithm is taken as two-way merging. The two-way
merging process is used to merge the two ordered lists. For example,
List_one={a1,a2,…ai…an}a1d”a2d”…d”aid”…an, and List_two={b1,b2,
…bj…bm}b1d” a2d”…d”bjd”… bm,
The merging process combines two given lists into one single list let
say L. The following consequences are made by the case of comparison
between the
keys ai and bj both belongs to List_one and List_two specified lists
respectively:
A_one: If (a < b ) is dropped into the given list L.
then a
i j i
A_two: If (a > b ) then is dropped into the given list L.
b
i j j
A_three: If (a = b ) then a and both are merged into the specified
b
i j i j
list L.
In this case A_one, if ai is dropped into the given list L and the very
next
comparison is possible with b proceeding a . In case of A_two, if bj is
dropped
j i+1
into the specified list L, the next comparison ai goes with aj+1. At the
end of merging process, final list contains (n+m) ordered elements. The
series of comparisons from the lists List_one and List_two and
dropping elements from the smaller elements into the list L proceeding the
following consequences:
B_One: List_one uses up List_two. The remaining element in
the list List_two are dropped into the given list L occurring L2 and
merge process is done.
NOTES
NOTES
NOTES
KEY TERMS
Array: A collection of elements of the same data type.
Searching: Locating a particular element in a data structure.
External searching: When the records are stored in files or on a disk
or tape or any secondary storage, then the searching is known as
external searching.
Internal searching: When the records to be searched are stored
entirely within computer’s memory, then it is known as internal
searching.
Internal sorting: Sorting of records in a file which is stored in the
main memory.
External sorting: Sorting of records in a file which is stored in the
secondary memory.
Algorithm: A sequence of computational steps that transform input
into output.
13. Algorithm:
Step 1: start
Step 2: initialize the variables a, b, c, i, j;
Step 3: enter the first matrix
Step 4: for i = 0, i < 3, j++ is the condition
satisfies go to next step else go to
: for j=0,j<3,j++ is the condition satisfies go
to the next step
: read a value
Step 5: enter the second matrix
Step 6: for i = 0, i < 3, i++ go to next step
else go to step 7
6.1:for j = 0, j < 3, j++ go to 6.2
6.2: read b
Step 7: print addition of matrix
Step 8: for(i = 0, i < 3, i++) go to 8.1 else go to
step 9
8.1: for j = 0, j < 3, j++ go to
8.2 8.2: c[i][j] = a[i][j] + b[i]
[j] 8.3: print c
Step 9: stop
14. Differences between an array and an ordinary variable:
An array is a set of variables of the same data type referred to by
a common name. Avariable is a data name that stores a specific
data type value which may alter during the execution of the
program.
Each member in the group is referred to by its position in the
group (array) using self-scripts. A variable is referred to by its
name.
FURTHER READING
Structure
Introduction NOTES
Unit Objectives
Introduction to Programming
Introduction to C as Reference
Representation of Integers
Data Types
Constants/Literals
Variables
Operators
Program Structures
Arithmetic Expressions
Assignment Statement
Logical Expression
Sequencing
Alteration and Iteration
String Processing
Subprograms
Recursion
Arrays
Functions
Pointers
Input and Output
Files
Structured Programming Concepts
Top-Down and Bottom-Up Design
Development of Efficient Programs
Program Correctness
Debugging and Testing of Programs
Summary
Key Terms
Answers to ‘Check Your Progress’
Questions and Exercises
Further Reading
INTRODUCTION
Programs are the ‘thought processes’ of computers. They are written in
various languages as a set of instructions to be interpreted and executed by
the computer, to enable it to perform the required task. It is also called the
software installed in the computer.
UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand why C program is the most suitable and commonly used
language for computer software
Distinguish between the different components that go into making a
program
Elaborate on the process of writing a C program
Analyse the different parts and functions of the program
Discuss the usage of files for storing data, popularly known as data files
Explain the concept of the programming paradigm
Examine the process of debugging and testing of a program to verify
and validate it
INTRODUCTION TO PROGRAMMING
Integer Constants
NOTES
The following are the types of integers:
int
unsigned
int long
unsigned long
Invalid integers
345.0 /* decimal point not allowed
*/ 112, 345L/* no comma allowed */ NOTES
112 345UL /* = blank not allowed
*/ 112890345L /* exceeds the
maximum */
+112 345UL /* unsigned cannot have +
*/ (345l /* ( not allowed */
–345s /* illegal characters */
a or A for 10
b or B for 11
c or C for 12
d or D for 13
e or E for 14
f or F for 15
0x20B
Programming
Invalid hexadecimal numbers
0x, 123 /* no comma */
0x /* cannot be empty */
NOTES 0A00 /* x is missing */
Character Set
The C language supports and implements the American Standard Code for
Information Interchange (ASCII) for representing characters. The ASCII
uses 7 bits for representing each character or digit. The characters are
coded from 0000000 (decimal 0) to 1111111 (decimal 127). Therefore, the
ASCII consists of a code for 128 characters in all. The ASCII values
(decimal equivalent of the 7 bits) of some alphabets and digits are given in
Table 3.2.
Table 3.2 ASCII Values of Selected Alphabets
The digits and alphabets are organized sequentially and hence, it is easy to
get the ASCII value; for instance, the ASCII value of D is 68, E is 69, 8 is
56, x is 120 and so on.
DATA TYPES
Data is used in a program to get information. In a program used to find out
the greater of two numbers, the numbers are data and the output, which says
which number is greater, is information. C is a versatile language and handles
many different types of data in an elegant manner.
Bit stands for binary digit, i.e., 0 or 1. Each byte contains 8 bits, i.e.,
8 consecutive bits of ‘0’ or ‘1’. Data is handled in a computer generally in
terms of bytes and therefore, will be in the form of multiples of 8 bits.
EachASCII character is represented by one byte.
An item that holds data is also called an object. An object has a name or
identifier associated with it. Each object can hold a specific type of data.
There are five basic data types in C, as follows: NOTES
Character
Integer
Real numbers
Void (comprising an empty set of values)
Enum (which will be introduced later)
You have to understand how a computer works. Assume multiplication of
two numbers a and b. First of all, the two numbers have to be stored in the
memory. Then the required calculation has to be performed. The result has
also to be stored in the memory. Each number is of a specific data type; for
instance, all three of them can be declared to be integers. Each data type
occupies a specific size in the memory. What does one mean by size? It is
the amount of storage space required; each bit needs one storage space. One
byte needs eight storage spaces. If a number is of type integer declared as
int, it is stored in 2 bytes. The number depending on its type gets stored in
different forms. If a number is of float type, it takes 4 bytes to store it.
All characters can be represented according to the ASCII table and hence, 1
byte, i.e., 8 bits are good enough to store a character, which is represented as
char.
These sizes may vary from computer to computer. The header files
<limits.h> and <float.h> contain information about the sizes of the
data types.
Real numbers can be expressed with single precision or double
precision. Double precision means that real numbers can be expressed
more precisely. Double precision also means more digits in mantissa. The
type ‘float’ means single precision and ‘double’ means a double
precision real number. Table 3.3 indicates the size of various data types.
Table 3.3 Size of Data Types
CONSTANTS/LITERALS
Constants are fixed values which remain unchanged during program execution .
These may be numbers or character strings.
e.g. 100, 3.14, ‘Hello World’, etc.
Constants are data values that cannot be changed during the execution of a
program.
A C constant is generally the written version of a number, e.g., 1, 0, 5.73,
12.5e9. Constants can be written in octal or hexadecimal or as long integers.
Octal Constants in octal are written using a leading zero—016.
Hexadecimal constants are written with a leading 0x—0x1AE.
Long constants are written using L in the last —990L.
Character constants are written as character using single quotes; ‘a’,
‘b’, ‘c’. There are characters that cannot be represented like that.
Hence, you have to use a 2-character sequence.
Multibyte character More than one character represented in single quotes ‘xy’
String “World”
176 Self-Instructional Material Note: In Table 3.4 L, U, and F are not case sensitive.
Programming
VARIABLES
where var1, var2,…varN are the names of the variables of the specified data
type.
e.g.: int k; (data type is int and variable name is ‘k’)
float price; (data type is float and variable name is ‘price’)
char name[20]; (data type is char and variable name is ‘name’)
Initialization of a variable
When a value is assigned to a variable while making declaration and is termed as
initialization of the variable.
Syntax:
<data type> var = value;
where ‘var’ is the name of the variable, ‘=’ is the assignment operator and
‘value’ may be constant or expression.
e.g.: int k = 10;(variable ‘k’ is initialized with value 10)
Assigning values to variables
Assignment operator (=) is used to assign values to variables. This operator can be
used in different forms shown as follows:
Syntax:
variable-name = value; (normal assignment)
variable-name = variable-name =…= value; (multiple assignment)
variable-name binary-operator = value; (compound assignment)
Where variable-name is the name of the variable, = is an assignment
operator,
binary operator may be an arithmetic, relational, logical operator and value
may be a constant or an expression.
e.g.: 1. int k;
k = 10; /* 10 will be assigned to the variable
‘k’ */
2. int a,b,c;
a = 10;
c = b = a; /* first a will be assigned to b and
then assigned to c and values
Logical Operators
These operators are used to compare or evaluate logical and relational
expressions. The result of the logical expression will be either true (1) or false
(0).
Operator Activity
&& AND
|| OR
186 Self-Instructional Material ! NOT
&& (AND) operator: If the expressions each side of the && are true the Programming
result of the && is true. If one of them is false the result is false.
Tips to remember the functioning of && and || operators:
General representation Representation in C
NOTES
‘false’ AND <anything> becomes false. (0 && true/false) == 0
‘true’ OR <anything> becomes true. (1 || true/false) == 1
|| (OR) operator: If either of the expressions
each side of the || are true the result of the whole expression is true. The
expression is only false if both expressions are false.
! (NOT) operator: for ! if operand is false (zero value) then result will be true
vice versa.
Demo program to display truth table of && (AND)
/*—————START OF PROGRAM——————*/
#include<stdio.h>
void main()
{
printf(“0 && 0 = %d \n”,0 &&
0); printf(“0 && 1 = %d \n”,0
&& 1); printf(“1 && 0 = %d \
n”,1 && 0); printf(“1 && 1 =
%d \n”,1 && 1);
}
/*——————END OF THE PROGRAM————*/
Output: 0 && 0 = 0
0 && 1 = 0
1 && 0 = 0
1 && 1 = 1
Note: For && if either operands are true (any non-zero value), then result will
be true.
Demo program to show the typical characteristics of && (AND)
/*—————— START OF PROGRAM ————————*/
#include<stdio.h>
void main()
{
int i=5,j=5;
printf(“%d “, 0 && (i=10));
printf(“%d “, 1 && (j=10));
printf(“i=%d j=%d”,i,j);
}
/*—————— END OF THE PROGRAM ————————*/
Self-Instructional Material 187
Programming
Output: 0 1 i=5 j=10
Explanation: If operand1 is false, then && operator will not allow to check
the second operand and return value of the result will be 0. For example, in
NOTES the above example, first printf statement’s first operand is 0; so irrespective
of second expression’s value, it will return 0.
Demo Program to display truth table of || (OR)
/*—————START OF PROGRAM——————*/
#include<stdio.h>
void main()
{ printf(“0 || 0 = %d \n”,0 ||
0); printf(“0 || 1 = %d \n”,0
|| 1); printf(“1 || 0 = %d \
n”,1 || 0); printf(“1 || 1 =
%d \n”,1 || 1);
}
/*——————END OF THE PROGRAM————*/
Output: 0 || 0 = 0
0 || 1 = 1
1 || 0 = 1
1 || 1 = 1
Explanation: The above out put shows the truth table of ! operator
Note: for ! if operand is false (zero value), then result will be true vice versa.
Note:
1’s complement of a binary number obtained by changing 0s to 1s and vice
versa. 2’s compliments = 1’s compliment + 1
Comma (,) Operator
The comma operator separates the expressions.
Syntax: exp1, exp2, … expn
Where exp1, exp2, … expn are expressions.
e.g.: k= (i=5, j=10, i+j);
Here, first the value 5 is assigned to i, then 10 is assigned to j and the result i+j
is assigned to k.
Generally, the comma operator is used in for loops.
e.g.: for( i=0, j=1; i<=10; i++, j++)
Demo program using comma operator
#include<stdio.h>
void main()
{
int a,b,c;
a=(b=10,c=20,b+c,b–c);
printf(“%d”,a);
}
Output: –10
Explanation:
In the first example, sizeof(int) returns 2, because size of int data type is 2.
In the second example, n2 returns 2, because size of integer variable also 2.
PROGRAM STRUCTURES
C Compile
Compiler Source Program
NoObject Code
System Library Link with
System Library
Execu able Object Code
Input Data t
Execute
Object Code
No Errors
CORRECT OUTPUT
Stop
ASSIGNMENT STATEMENT
Assignment operators are written as follows:
identifier =
expression; For
example,
i = 3; Note: 3 is an expression
const A = 3;
‘C’ allows multiple assignments in the following
form: identifier 1 = identifier 2 = =
expression.
For example,
a = b = z = 25;
LOGICAL EXPRESSION
It would be nice if you could check more than one condition at a time. ‘C’
provides three logical operators for combining more than one condition.
These are as follows:
Logical and represented as
&& Logical or represented
as ||
Negation or not represented as ! (exclamation).
Some examples on usage of logical operators are given here.
if x > y and if x > z, then x is the
greatest. You will represent the same as,
if ((x > y) && (x > y))
printf (“x is the greatest”);
ALGORITHM 2
Step 1: If (x > y) and (x > z), x is the
greatest. Step 2: Else if (x<y) and (y>z), y is
the greatest. Step 3: Else print z is the greatest.
The complete program is given in Example 3.1.
Example 3.1:
This Example demonstrates the use of logical operators*/
#include <stdio.h>
main()
{
int x,y,z;
printf (“enter three unequal integers\n”); scanf(“%d%d
%d”, &x, &y, &z);
if ((x>y) && (x>z))
198 Self-Instructional Material
printf(“x is greatest\ Programming
n”); else
{
if((x<y) && (y>z))
printf(“y is greatest\ NOTES
n”); else
printf(“z is greatest\
n”);
}
}
Now you can test the program by giving both the valid and invalid inputs;
valid inputs are the lower case letters and invalid inputs are all other characters.
Result of the program
The result for the invalid input is as follows:
enter lower case
alphabet 8
invalid entry; retry
The programs should be executed, i.e., tested with both the valid and
invalid inputs.
SEQUENCING
Statement two
Statement three
up to … Statement n
NOTES
N
Y
condition n instruction n
N
instruction m
void main()
{
clrscr();//Clears the screen
void calc_values (int, int,
char); int value_1, value_2;
char ch;
printf(“\nEnter two integer values :\
n”); scanf(“%d%d”, &value_1, &value_2);
printf(“\n Enter Arithmetic operator[+,-,*,/,%] : \n”);
scanf(“%c”,&ch); //Accepting input value as
character type
calc_values (a, b, ch);
return 0;
}
void calc_values(int x, int y, char c)
{
switch(c)
{
case ‘+’:printf(“\n Sum of %d and %d is = %d”, x,
y, x+y);
break;
case ‘-’ : printf(“\n Product of %d and %d = %d”, x,
y, x-y);
break;
case ‘*’: printf(“\n Product of %d and %d = %d”, x, y,
x*y);
break;
case ‘/’: if (x<y)
{
printf(“\n First integer must be greater than second
:”);
exit(0);
// The function exit(0)causes the program to exit
as successful termination.
}
do … The syntax of
while The syntax of while loop
is as follows:
do{
-
-
- Block of
statements is
written that is
to be executed
} while
(expression);
for
(expression_one,
expression_two;
expression_three)
{
-
-
- block of
statements to
execute
}
In the above algorithm, s1 and s2 are taken as two strings that are
represented by arrays of characters The function strlen() is used as
standard library function used in C and C++. This function finds the total
length of the specified string no matter space is given. The provided string
for s1 is ‘ababcab’ and for s2 is ‘abc’ can be explained the step-
wise string processing as follows:
'ababcab' i=1,j=1
'abc' NOTES
^ matches: increment i and j
'ababcab' i=2,j=2
'abc'
^ match fails: i=i-j=0, j=-
1, increment i and j
Initializing String
In ‘C’, characters or strings are initialized in one dimensionalarray as
follows:
char name_of_month={‘J’, ‘U’, ‘L’, ‘Y’};
Example:
char month[10];
char address[100];
strupr() function
This function strupr() changes the specified character or string in
lowercase.
#include <conio.h>
#include <stdio.h>
#include <string.h>
void main()
{
clrscr();
char str_string[]=”information technology”;
//String is defined
printf(“\nOriginal string is=%s”, str_string);
//Prints the defined string
strupr(str_string);
//Change the string in uppercase printf(“\
nString is in uppercase=%s”, str_string);
//Prints the string in uppercase
strrev() function
This function strrev() reverses the specified character or string.
#include <conio.h>
#include <stdio.h>
#include <string.h>
void main()
{
clrscr();
char str_string[]=”HELLO!”;
//String is defined
printf(“\nOriginal string is=%s”,
str_string); strrev(str_string);
printf(“\nReversed String is=%s”,
str_string); getch();
}
strlen() function
The function strlen()returns the total length of specified string.
#include <conio.h>
#include <stdio.h>
#include <string.h>
void main()
{
char
str_name[20]; int
i;
clrscr();
printf(“\nEnter a
string:”);
scanf(“%s”,str_name);
i=strlen(str_name);
printf(“\n Length of string (%s) is = %d”,
str_name,i);
strcat() function
The two strings are concatenated by strcat() function. They are
combined if the characters of one string are added at the end of other string.
This is known as concatenating process. The following syntax is preferred to
concatenate the two specified string values:
strcat(string_one, string_two);
For example,
strcpy(string_one,”Red”);
strcpy(string_two,”Flower”);
printf(“%s”,strcat(string_one,string_two));
SUBPROGRAMS
-
-
-
}
int compute_Avg_value(void)
//Declare an integer function as compute_Avg_value
containing void parameter
{
int val,
total_val=0; for(int
i=0;i<10;i++)
//Declaring for loop starting from 0 to 10
{
scanf(“%d”, &val); //Accepting input value as
per for loop
total_val+=val;
//Calculates total value increased by val value
}
return(total_val/10);
}
RECURSION
NOTES
Recursion is a powerful technique, which is used to call a function
itself.
A function, which invokes itself repeatedly until some condition is
satisfied, is called a recursive function.
The number of recursive calls is limited to the size of the stack.
Two or more functions, which invoke (call) each other, are called
mutually recursive functions.
function_1( ) function_2( )
{ {
statements; function_2( ); statements; function_1( );
} }
Here the first function function1() calls the second function; function2(),
which in turn calls the first function function1() again. These two functions
are, therefore, called mutually recursive functions.
For certain problems, a recursive solution is straight forward and
single as in case of factorial of a number; tower of Hanoi problem,
finding GCD, finding Fibonacci series, etc.
A recursive function is often less efficient compared to an iterative
function, but it is more elegant.
An iterative function is preferred when its recursive equivalent is complex.
Recursion is not always the best approach. In some cases, using
bottom-up (stack implementation) is a good approach to remove
recursion from an algorithm. For example, to generate Fibonacci
series through bottom-up approach is more efficient than recursive
method.
Example programs
1. Write a program to display 1 to 10 numbers using
recursion. Recursive function having without arguments and
return value
/*————————START OF PROGRAM————— */
#include<stdio.h>
void main()
{
Output:
1 2 3 4 5 6 7 8 9 10
Explanation: This program prints 1–10 numbers by calling main() function
recursively without having arguments.
2. Write a program to display 1 to n numbers using recursion.
Demo program for recursive functions having fixed number of arguments
/*————————START OF PROGRAM——————————*/
#include<stdio.h>
void display(int n)
{
if(n == 0)
return;
else
display(n – 1);
printf(“%d, n);
}
void main()
{display(10);
}
/*—————————END OF PROGRAM——————————*/
Output:
1 2 3 4 5 6 7 8 9 10
Explanation: This program prints 1 – n numbers by calling display() function
recursively having argument as n.
3. Write a program for recursive functions having fixed number of
arguments having return value.
Finding factorial of a given number
/*—————————START OF PROGRAM——————————*/
#include<stdio.h>
int fact(int n)
Output:
Factorial for 4 is 24.
Explanation: This program accepts a number and passes the number
through the function fact(num). The function int fact (int n) performs
factorial operation n*fact(n – 1) till n becomes zero. If n value is zero,
then it returns 1 to the calling function.
4. Write a program to add sum of digits of a given number using the
recursion method.
Adding digits of a given number
/*————————START OF PROGRAM——————————*/
#include<stdio.h>
Output:
Enter a value for n: 3
Tower of Hanoi problem with 3
disks move disk 1 from a to c
Usage of the above program: At the command prompt type disp_all <path
of a directory> where this program has been stored.
e.g.: C: \> disp_all c:\
The above program displays files in the specified directory as well as all
subdirectories.
7. Write a program to print a box in a text mode for given coordinates with
specified colour (Standard VGA colours only: BLACK, BLUE, GREEN,
CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY,
LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED,
LIGHTMAGENTA, YELLOW, and WHITE).
Printing a box in the text mode
/*——————————STAR OF PROGRAM————————*/
#include<stdio.h>
#include<conio.h>
void box(int x1, int y1, int x2, int y2, int bg, int
fg)
{
int i;
textcolor(fg); /* selects new character color in
text mode */
textbackground(bg); /* select new text background color
*/
gotoxy(x1, y1); /* positions cursor in text window */
cprintf(“%c”, 218); /* writes formatted output to the
text*/
220 Self-Instructional Material
/* window on the screen Programming
*/ gotoxy(x1, y2);
cprintf(“%c”, 192);
gotoxy(x2, y1);
cprintf(“%c”, 191); NOTES
gotoxy(x2, y2);
cprintf(“%c”, 217);
for(i = x1 + 1; i < x2; ++i)
{
gotoxy(i, y1);
cprintf(“%c”,
196); gotoxy(i,
y2); cprintf(“%c”,
196);
}
for(i = y1 + 1; i < y2; ++i)
{
gotoxy(x1, i);
cprintf(“%c”,
179); gotoxy(x2,
i); cprintf(“%c”,
179);
}
}
void main()
{
box(10, 10, 20, 20, WHITE, BLACK);
}
/*———————END OF PROGRAM—————————*/
Output:
Output:
ARRAYS
An array refers to a group of similar elements that share a common name
and are differentiated from one another by their position within the array.
Why do we need an array?
Ordinary variables are capable of holding a single value. However, there
are situations where we want to store more than one value in a single
variable.
For example, if you want to present the percentage of marks obtained
by 100 students in the ascending order, you have the following two options
for storing these marks in the memory:
Here the open and close square brackets are called subscript operator.
Inside this subscript operator, we mention the size of array.
Restrictions: The subscript value must always be the integer constant
while defining an array. It should not be a negative integer. We can use the
constants that are defined using the #define preprocessor directive
statement.
Assigning Constant Value
A global variable is one that is declared outside any function (usually
before main). A special feature of the global arrays is that they can be
initialized when they are declared. This is done by following an array name
with dimension and equal sign, followed by a pair of braces. These braces
contain a series of constant values separated by commas.
Ex: int name[5] = {l, 2, 3, 4, 5};
Since the square brackets following the array name are empty, the
compiler determines how many elements to allocate for array by counting
number of values within curly braces.
This approach can avoid errors. If dimension is specified explicitly,
values then are needed; a syntax error is flagged by the compiler.
Defining the size of each array as a symbolic constant makes
programs more scalable. The ‘C’ language treats character strings simply
as an array of characters.
Ex: char name[10]
Output:
The elements of array a are:
0 element of array a = 1
1 element of array a = 2
2 elements of array a =
3 3 elements of array a
= 4 4 elements of array
a=5
Self-Instructional Material 227
Programming
The elements of array b are:
0 element of array a = 1
1 element of array a = 2
NOTES 2 elements of array a =
3 The string is =
SRINU
Types of Arrays
Arrays are classified into two types, which are as follows:
TYPES OF ARRAYS
Single dimensional
Multi dimensional
Single-dimensional array
It is an array consisting of a single row or a single column.
Single-dimensional array (vector) represents the number of consecutive
memory locations in which data are stored and each element can be
accessed through an index.
Declaration of single-dimensional arrays
Syntax:
<type> <variable_name>[<index>];
Example 3.6:
int num[10]; /* an array of 10 integers */
char vowels[5]; /* an array of 5
characters*/
...
Example 3.8:
/* Program to declare an array, accept number to array
through keyboard and print them */
#include<stdio.h>
228 Self-Instructional Material main ( )
{ Programming
int arr [10], i; /* Array arr declaration
*/
Output:
Enter 1 value: 1
Enter 2 value: 2
Enter 3 value: 3
Enter 4 value : 4
Enter 5 value: 5
Enter 6 value: 6
Enter 7 value: 7
Enter 8 value: 8
Enter 9 value: 9
Enter 10 value: 10
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
arr[5] = 6
arr[6] = 7
arr[7] = 8
arr[8] = 9
arr[9] = 10
Example 3.9:
/* Program to sort in the ascending order
*/ #include<stdio.h>
main( )
{
Output:
Enter numbers for array sort
Sort[0] = 455
Sort[1] = 344
Sort[2] = 5
Sort[3] = 34
Sort[4] = 56
Sort[5] = 345
Sort[6] = 324
Sort[7] = 56
Sort[8] = 45
Sort[9] = 56
Sort [0] = 5
Sort[1] = 34
Sort[2] = 45
NOTES
Sort[3] = 56
Sort[4] = 56
Sort[5] = 56
Sort[6] = 324
Sort[7] = 344
Sort[8] = 345
Sort[9] = 455
Multi-Dimensional Arrays
Definition
An array having more than one dimension is a multi-dimensional array.
In C, you can declare an array of arrays called multi-dimensional as follows:
Declaration of multi-dimension arrays
Syntax:
<type> <variable_name>[index1][index2]...;
Example 3.10:
int a[3][3];
char a[10][3][4];
.....
Example 3.11:
int a[3][3];
char a[10][3];
.....
Output:
The elements of the double-dimensional array
dob [0] [0] = 6
Output:
Output:
Enter value for m <= 10:2
Enter value for n <= 10:2
Enter a value for a[0]
[0]:1
Self-Instructional Material 239
Programming
Enter a value for a[0]
[1]:2 Enter a value for
a[1][0]:3 Enter a value
for a[1][1]:4 Enter a
NOTES
value for b[0][0]:0 Enter
a value for b[0][1]:1
Enter a value for b[1]
[0]:2 Enter a value for
b[1][1]:3 1 1
1 1
Explanation:
The subtraction of two matrices of the same order is again a matrix of the
same type obtained by the subtraction of the corresponding elements of two
matrices.
Multiplication of Arrays
Suppose
1 3 2 0 4
A and B
4
2 3 2 6
The product matrix AB is a 2 × 3 matrix. The elements in the first row of AB
are obtained, respectively, by multiplying the first row of A by each of the
columns of B:
1 32 0
4 1.2 1.0 1.(4) 3.6 11 6 14
3.3 3.2
2 4 3 2 = =
6
Similarly, the elements in the second row of AB are obtained, respectively, by
multiplying the second row of A by each of the columns of B:
= 11 6 14 6 14
11
.2 4.3 2.0 4.2 2.(4) 4.6 1 8 16
2
6
6 14
That is, AB
11 8 16
1
6
240 Self-Instructional Material
The following
algorithm finds the
product AB of matrices
A and B, which are
stored as two-
dimensional arrays:
Algorithm:
(Matrix Multiplication)
MATMUL(A, B, C, M,
P, N)
Let A be an M × P
matrix array, and let B
be a P × N matrix array.
This algorithm stores the
product of A and B in an
M × N matrix array C.
1. Repeat Steps 2 to
4 for I = 1 to M:
2. Repeat Steps 3
and 4 for J = 1 to
N:
3. Set C[I, J] : = 0. [Initializes C[I, J].] Programming
4. Repeat for K = 1 to P:
C[I, J]:=C[I, J] + A[I, K]*B[K, J]
[End of inner loop.] NOTES
[End of Step 2 middle
loop.] [End of Step 1 outer
loop.]
5. Exit.
The complexity of a matrix multiplication algorithm is measured by counting
the number C of multiplications. The reason that additions are not counted
in such algorithms is that computer multiplication takes much more time
than computer addition. The complexity of the above algorithm is equal to
C = m • n • p
This comes from the fact that Step 4, which contains the only multiplication
is executed m • n • p times. Extensive research has been done on finding
algorithms for matrix multiplication, which minimize the number of
multiplications. The next example gives an important and surprising result in
this area.
Example 3.19:
Write a program for multiplication of matrices of form m × n, n × k resulting
m × k matrix
#include<stdio.h>
#include<stdlib.h>
void main()
{ int a[10][10], b[10][10], c[10][10];
int m, n, k, i, j,
l; do
{
printf(“Enter value for m <=
10:”); scanf(“%d”, &m);
}while(m > 10);
do
{
printf(“Enter value for n <=
10:”); scanf(“%d”, &n);
}while(n > 10);
do
{
printf(“Enter value for k <=
10:”); scanf(“%d”, &k);
}while(n > 10);
Self-Instructional Material 241
Programming
for(i = 0; i < m; +
+i) for(j = 0; j < n;
++j)
{
NOTES
printf(“Enter a value for a[%d][%d]:”, i, j);
scanf(“%d”, &a[i][j]);
}
for(i = 0; i < n; +
+i) for(j = 0; j < k;
++j)
{
printf(“Enter a value for b[%d][%d]:”, i, j);
scanf(“%d”, &b[i][j]);
}
for(i = 0; i < m; ++i)
{
for(j = 0; j < k; ++j)
{
c[i][j] = 0;
for(l = 0; l < n; ++l)
c[i][j] += a[i][l] * b[l][j];
}
}
for(i = 0; i < m; ++i, printf(“\
n”)) for(j = 0; j < k; ++j)
printf(“%d “, c[i][j]);
}
Output:
Enter value for m <= 10:2
Enter value for n <= 10:2
Enter value for k <= 10:3
Enter a value for a[0]
[0]:1 Enter a value for
a[0][1]:2 Enter a value
for a[1][0]:3 Enter a
value for a[1][1]:4 Enter
a value for b[0][0]:5
Enter a value for b[0]
[1]:6 Enter a value for
b[0][2]:7 Enter a value
for b[1][0]:8 Enter a
value for b[1][1]:9 Enter
a value for b[1][2]:2
242 Self-Instructional Material
21 24 11
47 54 29
Explanation: Programming
The product of two matrices is defined only when the number of columns
offirst is equal to the number of rows of second. If A and B are two matrices
of order m×n and n×p, respectively, then the product AB will be of order
m×p. NOTES
Thus if A=[aij]mxn and B=[bij]nxp
n
then AB=[c ] where c = air brj ,1 i m and 1 j p
ij mxp ij
r 1
Unsorted Array : 42 23 36 42 65 58 94 36 99 87
Passers
1. : {11 23 36} 42 {65 58 94 74 99 87}
2. : 11 {23 36} 42 {65 58 94 74 99 87}
3. : 11 23 {36} 42 {65 58 94 74 99 87}
4. : 11 23 36 42 {58} 65 {94 74 99 87}
5. : 11 23 36 42 58 65 {94 74 99 87
6. : 11 23 36 42 58 65 {87 74} 94 {99}
7. : 11 23 36 42 58 65 {74} 87 94 {99}
8. : 11 23 36 42 58 65 74 87 99 {99}
9. : 11 23 36 42 58 65 74 87 94 99
Sorted
Describe Quick sort algorithm for the input: 20, 5, 100, 15, 30, 10, 80, 25
1. Choosing a pivot: You can select any item among the given list of
elements as a pivot, choose the leftmost one to avoid confusion.
pivot
2 5 10 1 3 1 8 2
Left Right
5 10 1 3 1 8 2
2
Pivot = 20
5 100 15 30 10
80 25
20
Pivot = 20
Move the left pointer while it points to elements, which are less than
or equal to the pivot and move right, which are greater than or equal
to the pivot
Left
Right
20 5 100 15 30 10 80 25
Pivot = 20
Lower bound Upper bound
Swap the two elements (left and right) on the wrong side of the pivot
Left
Right
20 5 100 15 30 10 80 25
Pivot = 20
20 5 30 100 80 25
10 15
Pivot = 20
NOTES 20 5 10 15 30 100 80 25
Pivot = 20
1 2 6 4 3 5 5 7 8
1
15 5 10 20 30 100 80 25
Continue this process for the Left half portion and the Right half portion
>pivot
< pivot
=
C * N C * N 1 T N 2 C * N C * N 1 C * N 2 T N 3
W W
QS QS
N 1 N
N
c * k TQS
W
C *
ON
2
2
0
k 1
c * N 2cN/2 4c N/4 8 T
B
B
QS N/8 B
TQS 3 * C * N 8TQS N/8
Single operations that involve all arrays are not allowed in ‘C’. if ‘a’ and ‘b’
are similar arrays (same data type, same size). Assignment operations and
comparison operations should necessarily be executed on the element-by-
element basis. This is completed within the loop that is used to process one
array element. The number
248 Self-Instructional Material
of passes through the loop will be equal to the number of array elements to Programming
be processed.
Example 3.20:
Accepting ‘n’ elements for one-dimensional array NOTES
main( )
{
int
a[10], i 0, n;
printf ("enter size of array");
scanf
("%d", & n);
for
(i 0; i n; i )
scanf (" %d", & a[i]);
}
Printing the array elements on the screen
main()
{
int a[10], i = 0;
for(i = 0; i < n; i+
+) printf(“%d”, [i]);
}
Accepting elements and displaying the elements for two-
dimensional array:
scanf(“%d%d”, &m, &n);
for(i = 0; i < n; i+
+)
for(j = 0; j < n; j++)
scanf(“%d”,
&a[i[j]);
FUNCTIONS
In order to use the library functions, you must include the header
files supplied with the system such as stdio.h, string.h, etc. In
effect, the library functions are hiding the programs or in other words, they
are encapsulated. You only pass arguments to use them. The arguments
are, for example, what you put within brackets following printf(),
scanf(), gets(), puts(), etc. The availability of such functions
is a feature of modular programming. The availability of these functions has
reduced considerably the need to code the print or other statements and check
them in every program.
MAIN
f1 f2 f3 f4
Develop the programin such a manner that the main program calls a
number of functions for carrying out specific tasks. Each function may, in
turn, call other specialized functions wherever required. Such a program will
be easy to understand, debug and maintain.
In order to improve the quality of programming, you should, therefore,
call functions wherever required. The functions supplied with the system are
the library functions. User-developed functions are called user-defined
functions.
You now know that each function performs a specified task.
Arguments or data are passed to the function and the function performs some
specified actions. Before you go into more details, you must understand the
usage of functions. Assuming that you want to reverse a number in a
program, you split the program into two parts. The main() function gets
the number to be reversed. It passes the number to a function called
reverse() whose specialized and only job is to get the number, reverse it
and send back the reversed number to the function, which calls it. The
diagrammatic representation is as follows:
main
reverse
If it does not return any value, you may write the above as,
void fun2(float arg1, int arg2);
/*void means nothing*/.
unit. Assume that you wish to get two integers. Pass them to a
function add.
Programming
Add them in the add function. Return the value to the main function and
print it. The algorithm for solving the problem is as follows:
Main Function
Step 1: define function
NOTES
add Step 2: get 2 integers
Step 3: call add and pass the 2 values
Step 4: get the sum
Step 5: print the value
function add
Step 1: get the value
Step 2: add them
Step 3: return the value to main
Thus you have divided the problem. The program is given below:
Example 3.21:
/* use of
function*/ #include
<stdio.h> int main()
{
int a=0, b=0, sum=0;
int add(int a, int b); /*function declaration*/
printf(“enter 2 integers\n”);
scanf(“%d%d”, &a, &b);
sum =add(a, b); /*function call*/
printf(“sum of %d and %d =%d”, a, b,
sum);
}
/*function definition*/
int add (int c, int d) /*function declarator*/
{
int e;
e= c+d;
return e;
}
Therefore, sum gets the value, which is printed in the next statement.
This is how the function works.
Assume now that the program gets a and b values, gets their sum1,
gets c and d and gets their sum2 and then both the sums are passed to
the function to get their total. The program for doing this is as follows:
Example 3.22:
/* A function called many times
*/ #include <stdio.h>
int main()
{
float a, b, c, d, sum1, sum2, sum3;
float add(float a, float b); /*function declaration*/
printf(“enter 2 float numbers\n”);
scanf(“%f%f”, &a, &b);
sum1 =add(a, b); /*function call*/
printf(“enter 2 more float numbers\n”);
scanf(“%f%f”, &c, &d);
sum2 =add(c, d); /*function call*/
sum3 =add(sum1, sum2); /*function call*/
printf(“sum of %f and %f =%f\n”, a, b, sum1);
printf(“sum of %f and %f =%f\n”, c, d, sum2);
printf(“sum of %f and %f =%f\n”, sum1,sum2,
sum3);
}
/*function definition*/
float add (float c, float d) /*function declarator*/
{
float e;
e = c+d;
return
e;
}
Thus the program goes back and forth between main and add as follows:
main()
add (a,
b) main()
add (c,
d) main()
add (sum 1, sum 2)
main()
Had you not used the function add, you would have to write
statements pertaining to add 3 times in the main program. Such a program
would be large and difficult to read. In this method you have to code for
add only once and hence, the program size is small. This is one of the
reasons for the usage of functions.
In Example 3.22, We could add another function call by add
(10.005, 3.1125); This statement will also work perfectly. After the
function is executed, the sum will be returned to the main function.
Therefore, both variables and constants can be passed to a function by
making use of the same function declaration.
You have seen a program, which calls a function thrice. Now a
problem, which calls three functions will be discussed.
Problem
The user gives a four-digit number. If the number is odd, then the number has
to be reversed. If it is even, then the number is to be doubled. If it is evenly
divisible by three, then the digits are to be added. Now write the algorithm
for solving the problem.
Step 1: Get the number.
Step 2: If number is odd, call the reverse function.
Step 3: Else multiply the number by 2 and hence, call multiply.
Step 4: If number is evenly divisible by 3, call add-digits.
Self-Instructional Material 257
Programming
These are the steps. The first one, namely writing a function to multiply
by 2 is simple. You will look at the other two steps now.
Reverse
NOTES You have already seen reversing the number in a program. You will use the
same steps.
Step 1: reverse = 0
Step 2: while ( number > 0 )
reverse = reverse * 10 + (number % 10
) number = number/10
Step 3: return (reverse)
ADD digits function
Step 1: sum = 0
Step 2: while number > 0
sum = sum + (number %
10) number = number /
10
Step 3: return (sum)
See how the above algorithm adds digits and
works. Give 4321 as the number.
Step 1: sum = 0
Step 2: Iteration 1
sum = 0 + modulus of (4321/10)
= 0 + 1 = 1
number = 4321/10 = 432
Iteration 2
sum = 1 + modulus of (432/10)
= 1 + 2
After 4 iterations,
sum =1 + 2 + 3 + 4
Step 3: Sum is returned.
When two integers are received, the main function calls gcd
function. In the gcd function, it is checked whether n equals to zero. If
so, m is the gcd. If not, the function calls gcd again by changing the
arguments as follows:
M = n
N = m % n
The program was executed twice and the result of the program is
given hereafter.
Result of the program
First Time
Enter 2 integers
12 256
GCD of 12 and 256 = 4
Second Time
Enter 2 integers
1225 625
GCD of 1225 and 625 = 25
We can even enter the first number to be lower than the second
number as executed during the first time. The program works all right because
in one iteration, the numbers get reversed, namely the first number is larger
than the second number after iteration. Thus, recursion is quite suitable for
solving this problem.
Definition
NOTES
A pointer is a variable that points to another variable, i.e. it holds the memory
address of another variable.
Pointer Declaration
As in case of all other variables, pointer variables, should also be necessarily
declared before you use them in ‘C’ program. When a pointer variable is
declared, an asterisk (*) must precede the variable name. This identifies
the fact that the variable is a pointer.
Syntax:
data_type *ptvar;
Where ptvar refers to the name of the pointer variable.
Example 3.28:
/* Program to explain pointer variables, how to store
address, and print */
#include
<stdio.h> main ()
{
int a;
int *p;
/* *p = Pointer variable declaration to store the
address of an integer variable, * called
as Indirection operator (or) value at address
operator */
a = 10;
p = &a;
/* Assigning the address of integer variable a
to pointer variable p. & is the address of
operator */
printf(“\n The value of a = %d\n”, a); //
Printing value of a
printf(“\n The address of a = %u\n”, &a); // & a
means address of a
printf(“\n The address of a = %u\n”, p); //
printing the p value
printf(“\n The value of a = %d/n”,*p);
/* *p means value at p contained address
*/
Output:
The value of a = 10
The address of a =
65524 The address of a
= 65524 The value of a
= 10
The address of p =
65522 The value of p =
65524 The value of a =
10
In the statement p = &i, the address operator assign the address of it to the
pointer ‘p’.
Indirection Operator (*): In Example 3.29, the value of i can be accessed by
*p, where * refers to the unary operator which is known as indirection
operator. The indirection operator operates only on a pointer variable.
Example 3.30:
#include
<stdio.h> main (
)
{
int i =
3; int
*p, j; p
= &i
Self-Instructional Material 269
Programming
j = *p;
printf(“%d %d %d”, i, p, j);
}
NOTES Output:
3,4082
i.e. the value of i is indirectly assigned to j.
Pointer to Pointer
As we know a pointer is a variable which holds the address of another
variable. Since a pointer itself is a numeric variable, it is also accumulated in
computer’s memory at a specific address. Apointer to pointer refers to a
variable that controls the address of a pointer variable. To declaring a
pointer to pointer, a double indirection operator should be used.
Syntax:
data_type
*ptvar; int **j
Output:
The address of i = 65524
The address of i = 65524
The address of p = 65522
The address of p = 65522
The address of p1 = 65520
The address of p1 = 65520
The address of p2 = 65518
The value of i = 10
The value of i =
10 The value of i
= 10 The value of
i = 10
The value of p = 65524
The value of p1 = 65522
The value of p2 = 65520
Function with Pointers (Call by Reference)
Pointers are often passed as arguments to a function. When a pointer is
passed to a function, the address of a data item is passed to function. When
the address of a data item is passed as an argument to a function, it is
referred to as call by reference.
The contents of that address can be accessed freely, either within the
function or with the calling portion. Moreover, any change that is made to the
data item will be recognized in both the function and the calling routine.
Example 3.32:
/* Program to illustrate passing the pointer to
function (call by reference) */ Self-Instructional Material 271
Programming
#include <stdio.h>
void swap (int *, int *);
main ( )
{
NOTES
int a, b ;
printf(“Enter two values \
n”); scanf(“%d %d”, &a, &b);
printf(“\n Before swapping the values of a and
b\n”);
printf(“ %d\t %d\n\n”, a,b);
swap (&a, &b); /* Passing address of a and address
of b to swap */
printf(“After swapping the values of a and b\n”);
printf(“%d\t%d”, a, b);
}
void swap (int *p, int *q)
/* p hold address of a and q holds address of b */
{
int temp;
temp = *p; // swapping a and b values through
pointer
*p = *q;
*q = temp;
return;
}
Output:
Enter two
values 12
45
Before swapping the values of a and b
12 45
After swapping the values of a and
b 45 12
Pointer versus srrays
Array elements are invariably accumulated in adjoining memory locations. It
would be easier to access the elements using a subscript if there is fixed logic
involved in accessing the elements.
Array elements should be accessed using pointers, if the elements are
to be accessed in a fixed order, say from beginning to end or from end to
272 Self-Instructional Material
beginning or
every alternate element. Accessing the elements by pointers would work Programming
faster than subscripts.
Example 3.33:
/* Program to illustrate arrays with pointers
NOTES
*/ #include <stdio.h>
main ()
{
int arr[10]. *p, i;
p = &arr [0]; /* Passing the base address
of an array to pointer p. */
printf(“Enter values for array arr\n\
n”); for (i = 0; i < 10; i++)
{
printf(“arr[%d] =”, i);
scanf(“%d”, p + i); /* P initially holds
base address of arr array here p + i means
incrementing pointer p */
}
printf(“\n\n The array elements are \n\n”);
for (i = 0; i < 10; i++)
{printf(“arr [%d] = %d\t%d\t%d\t%d\n”, arr[i], i[arr],
*(i + p), *(p + i)); }
i+9
0 1 23 4 5 6 7 8
i
i+1
0 1 2 3 4 5 6 7 8
i+1
*(i + 2) *(i + 2) + 5
*(*(i + 2) + 5)
First note that (i + 2) is a pointer to row 2. Therefore, the object of this pointer
*(i
+ 2) refers to the entire row. Since row 2 is a one-dimensional array, *(i +
2) is actually a pointer to the first element in row 2. Hence, (*(i + 2)) is a
pointer to element 5 in row 2. The object of this *(*(i + 2) + 5), therefore,
refers to item in column 5 of row 2.
i[2] [5], *(i [2] + 1), *(*(i + 2) + 1)
All above expressions refers to same elements.
Example 3.35:
/* To explain pointers with double dimensions */
#include <stdio.h>
main ( )
{
int dob [3] [3], *p, i, j; for (i = 0; i < 3; i++)
{
274 Self-Instructional Material
printf(“\n\n Enter % d row values \n\n”, i Programming
1); +
Array of Pointers
An array of pointers refers to a collection of addresses. The addresses
present in the array of pointers may be addresses of ordinary variables or
addresses of array variables or any other addresses. All those rules which are
applicable to ordinary arrays are also applicable to array of pointers.
Example 3.36:
/* Program to illustrate the array of pointers
*/ #include <stdio.h>
main ( )
{
int arr[3], *point[3], i, j; /* point[3] is to
store the address */
for (i = 0; i < 3; i++)
point[i] = arr + i; /* Assigning address of
arr array to point array */
printf(“\n\n Enter values \n\
n”); for(i = 0; i < 3; i++)
scanf(%d”, arr + i);
printf(“\n The addresses of each array elements are
\n”);
for (i = 0; i < 3; i++)
printf(“arr [%d] = %u\n”, point[i]);
printf(“\n The addresses of each array
elements
are\n”);
for (i = 0; i < 3; i++)
printf(“arr[%d] = %u\n”, i, &arr[i]);
Self-Instructional Material 275
Programming
printf(“\n The values in dob array are \
n”); for ( i = 0; i < 3; i++)
printf(“arr [%d] = %d\n”, i, *point [i]);
printf(“\n The values in dob array are \
NOTES
n);
for (i = 0; i < 3; i++)
printf(“arr [%d] = %d\n”, i, arr[i]);
}
Output:
String is Srinivas
The realloc( ) function
The realloc( ) function changes the size of a block of memory that was
already allocated by the functions malloc( ) or calloc ( ). This process is
termed as reallocation of memory.
Syntax:
Void *realloc(void *ptr, size_t size);
– Here ptr argument is a pointer to the original block of memory; size
specifies the new size.
Example 3.38:
#include <stdio.h>
#include <alloc.h>
#include
<string.h> main (
)
{
char *name ;
name = (char*) malloc (12);
// Allocating memory
Self-Instructional Material 277
Programming
strcpy (name, “Parthiv Sai”);
printf(“Name is %s\n”, name);
name=(char*) realloc (name,
30);
NOTES
// Reallocating memory to 20)
strcpy (name, “B.S. Software Solutions”);
printf(“String is %s\n”, name);
free (name); /* Releasing memory */
}
Output:
Name is Parthiv Sai
String is B.S. Software Solutions
The free( ) function
The free( ) function is used to de-allocate or free the memory, which is
allocated by the malloc( ), calloc( ) or realloc( ) functions so that the memory
is available for future use.
Syntax:
void free(void *ptr);
– The free( ) function frees the memory pointed to by ptr.
– If ptr is null, free( ) function does nothing.
Built-in String Functions
A string is a collection of characters and terminated with NULL characters
and it is denoted by \0. The four string handling functions are as follows:
strlen() – returns the length of the given string as argument.
strcpy() – to copy the string from source to destination variable.
strcmp() – to compare the two given string.
strcat() – to concatenate (combine or join) the both given strings
into one.
*For all the above functions, we require the header file string.h.
strlen(): The function strlen() takes string as argument and returns the length
of the integers as shown below in the code chunk.
Syntax: int
strlen(char*); int len;
char *str =”Sreenivasa
Rao”; len = strlen(str);
printf(“%d”, len);
strcmp(): The function strcmp() compares the two given strings character
by character, and returns a value 0 if both the strings are equal, and value <
0 if the string one is less than string two and > 1 if string one is greater than
string two. The syntax is as follows:
int strcmp(char *,
char*); int val;
char *str1= “Apple”;
char *str2 = “apple”;
val = strcmp(“Apple”, “apple”);
Here, the first string is less than the second string; hence, the value of val is
less than zero (0), since the ASCII value of character ‘A’ differs from
character ‘a’.
strcat(): This function concatenates two strings resulting in a single string. It
takes two arguments, namely, the pointers to the two strings. The resultant
string is stored in the first string specified in the argument list.
char destination[25];
char *blank = “ “, *c = “Bandaru”, *t =
“Parthiv”; strcpy(destination, t);
strcat(destination, blank);
strcat(destination, c);
printf(“%s\n”,
destination);
The input list gives the names of the variables to which values are to
be given as they are encountered in the input stream.
For example:
Read(A, B, C)
The first four statements assign to the indicated variables on four tests.
The fifth statement computes the average grade. The write statement then
displays this calculated result:
Let us observe the case when we replace the above write statement
with
Write(MARK1, MARK2, MARK3, MARK4, AVERAGE)
NOTES
The resulting output would be as follows:
73 65 94 87 79.75
Note that all numbers are written as real numbers. This is because the
variables themselves are all real variables. Now, however, we have simply
five numbers displayed. Suppose, instead, that we gave the following
output statements:
Write(‘Individual grades are’, MARK1, MARK2,
MARK3, MARK4)
Write(‘Final average is’, AVERAGE)
FILES
For programming <stdio.h> is included in every file. This file is
essential for any program for reading from standard input device or writing
to the standard output device. File <stdio.h> has declarations to the
pointers to three files, namely stdin, stdout and stderr. It means
that the contents of these files are added to the program, when the program
executes. Each of the files performs an essential task as follows:
(a) stdin facilitates usage of the standard input device for program
execution and normally points to the keyboard, which is the default
input device.
(b) stdout facilitates the usage of a standard output device where
program output is displayed and points to the video monitor.
(c) stderr facilitates sending error messages to the standard device
that is again the monitor.
stdin, stdout and stderr are pointers or file pointers and are declared
in
<stdio.h>. So far you have been using stdin and stdout for input
and output. In this unit, we will learn to use disk drives either hard disk or
floppy disk as the medium for input/output. In day-to-day usage of large
applications, the standard input/output is neither convenient nor adequate to
handle large volumes of data and hence, the disk drives only serve as
Input/Output (I/O) devices. You will learn about the usage of files for
storing data, popularly known as data files. Data files stored in the secondary
or auxiliary storage devices, such as hard disk drives or floppy disks, are
permanent unless deleted. In contrast, what is written to the monitor is only
for the immediate use. The data stored in disk drives can be accessed later
and modified, if necessary.
In C, we come across two types of files:
a. Stream-oriented
b. System-oriented
System-oriented files or low-level files are more closely related to
the operating system and hence, require more complex programming skills
284 Self-Instructional Material to use them. They may be found to be more efficient than the former in some
cases, but we will not discuss them further because of their complexity.
Instead, we will discuss stream-oriented files only in this unit.
Stream-oriented files are also called standard files. Data can be stored Programming
in the standard files in two ways as given below:
Storing characters or numerals consecutively. Each character is
interpreted as an individual data item.
NOTES
The data items are arranged in blocks in an unformatted manner.
Each block may be an array or a structure.
Let us see how disk I/O is organized. If the file is stored in a floppy or hard
disk drive, the following actions are involved in reading from the file:
Finding out where the data is.
Positioning the head over the correct location on the disk.
Reading the content.
Transmitting to the main memory.
Similar activities are involved in writing to a disk as well. If the
computer, or more specifically the operating system, which handles files in a
computer, reads or writes one character at a time comprising the four steps
listed above, then it will be uninteresting and the response will be too slow. It
may cause wear out of the storage system quickly. Therefore, it would be
better to receive large volumes of data or characters to a buffer in the
computer system and then perform whatever actions are dictated by the
program. Similarly, all characters to be written can be collected in a buffer
and written on to the disk, either after the buffer is full or after the operation
is completed. This will minimize the overheads required for the read or write
operations. The buffer is also, the memory, which is used to store data
temporarily without the knowledge of the user. In fact, you created a buffer
and stored values into it before printing them using the sprintf() function. The
concept is similar here also. This is a good practice. Therefore, the characters
are read or written through a buffer assigned by the system. The operations
are essentially performed as depicted pictorially as follows:
File Pointer
What is a file pointer? It is a pointer to a file, just like other pointers to arrays,
structures, etc. It points to a structure that contains information about the file.
The information connected with a file is as follows:
Location of the buffer
The position in the file of the character currently being pointed to
Whether the file is being read or written
Whether an error has occurred or the end of the file has been reached
You do not need to know the details of these because stdio.h handles it
elegantly. There is a structure with typedef FILE in stdio.h, which
handles all file-
Text mode needs more than the 2 bytes In binary mode the numbers will be
for storing an integer, since it treats stored in the specified width. 30000
each digit as a character. e.g., 30,000 needs 2 bytes only.
needs 5 bytes.
Therefore, binary files and text files are to be processed taking into
account their properties as above, although the file could be opened in any
mode. The file I/O functions, such as fgetc, fputc, fscanf, fprintf,
fgets, fputs, are applicable to the operations in any of the modes.
The files can be used to store employee records using structures in a
payroll program. Book records can be stored in a file in a library database.
Inventories can be stored in a file. However, storing all these in the text
mode will consume more space on the file. Hence, the binary mode can be
used to create the files. Some files cannot be stored in the text mode at all,
such as executable files.
Formatted I/O Operations with Files
We are familiar with reading and writing. So far we were reading from and
writing to standard input/output. Therefore, we used functions for the
formatted I/O with stdio such as scanf() and printf(). We also
used unformatted I/O such as getch(), putch() and other statements.
When dealing with files, there are similar functions for I/O. The functions
getc(), fgetc(), fputc() and putc() are unformatted file I/O
functions similar to getch() and putch(). We will consider the
formatted file operations in this section. When it pertains to standard input or
output, we use scanf() and printf(). To handle formatted I/O with
files, we have to use fscanf() and fprintf().
We can write numbers, characters, etc. to the file using fprintf().
This helps in writing to the file neatly with a proper format. In fact, any output
can be directed to a file instead of the monitor. However, we have to indicate
which file we are writing to by giving the file pointer. The following syntax has
to be followed for fprintf():
fprintf(filepointer, “format specifier”, variable
names);
We are only adding the file pointer as one of the parameters before
the format specifier. This is similar to sprintf(), which helps in writing to a
buffer.
288 Self-Instructional Material
In the case of sprintf(), buffer was a pointer to a string variable. Here, Programming
instead of a pointer to a string variable, a pointer to a file is given in the
fprintf() statement. Like the string pointer in sprintf(), the file
pointer should have been declared in the function and should be pointing to
the file. NOTES
Before writing to a file, the file must be opened in the write mode. You
can declare the following:
FILE * fp ;
fp = fopen (“filename”, “wb”);
You have to write wb within double quotes for opening a file for
writing in the binary mode. Therefore, fopen() searches the named file.
If the file is found, it starts writing. Obviously the previous contents will
be lost. If a file is not found, a new file will be created. If unable to open a
file for writing, NULL will be returned.
We can also append data to the file after the existing contents. In this
manner, we will be able to preserve the contents of a file. However, when
you open the file in the append mode, and the file is not present, a new file
will be opened. If a file is present, then writing is carried out from the
current end of the file. After writing is completed either in the write mode
or the append mode, a special character will be automatically included at the
end of the text in case of text files. In case of binary files, no special character
will be appended. This can be read back as EOF. Usually it is – 1, but it is
implementation-dependent. Hence, it is safer to use EOF to check the end of
the text files.
Writing and Reading a Data File
Let us look at a program to write numbers to a binary file using
fprintf() and then read from the file using fscanf(). It is given in
Example 3.39.
Example 3.39: writing
digits to a binary file and then
reading*/ #include <stdio.h>
int main()
{
int alpha,i;
FILE *fp;
fp=fopen(“ss.doc”, “wb”);
if(fp==NULL)
printf(“could not open file\
n”); else
{
for (i=0; i<=99; i++)
fprintf(fp,” %d”, i);
fclose(fp);
/*now read the
contents*/
fp=fopen(“ss.doc”,
“rb”);
for (i=0; i<100; i++)
Self-Instructional Material 289
Programming
{
fscanf(fp,”%d”, &alpha);
printf(“ %d”, alpha);
}
NOTES fclose (fp);
}
}
File Copy
File copy can be achieved by reading one character at a time and writing to
another file either in the write mode or the append mode. Here it is proposed
to read from a file and write to two different files, one in the write mode
and another in the append mode. This means we have to open three files in
the following manner:
FILE * fr, *fw; *fa;
You can assign three file pointers as given above. Three files are then opened.
You can use any name for the file pointers and there may be as many file
pointers as the number of files to be used. The program is given below:
After opening the three files, alpha() gets the character, which is written
to both the files using fputc(), and the character is also displayed on the
screen. This is continued till EOF is received in alpha from ss.doc, the
source file.
Finally, the files are closed. Verify that our program has worked alright.
Since, we are also writing to the monitor, in addition to writing and
appending to files, the program output appears as follows.
Result of the program
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
98 99
There are some more mode specifiers with fopen like r+, w+ and
a+, which are given in the table below:
Mode Specifier Purpose
r+ Opens an already existing file for reading and writing.
w+ Opens a new file for writing as well as reading.
a+ Opens an already existing file for appending
and reading.
Self-Instructional Material 293
Programming
Line Input/Output
We have discussed writing to and reading from a file, one character at a
time, using both the unformatted and formatted I/O for the purpose. We can
NOTES also read one line at a time. This is enabled by the fgets() function.
This is a standard library function with the following syntax:
Char * fgets (char * buf, int max line, FILE * fp);
fgets() reads the next line from the file pointed to by fp into the
character array buf. The line means characters up to maxline –1, i.e., if
maxline is 80, each execution of the function will permit reading of up
to 79 characters in the next line. Here 79 is the maximum, but you can even
read 10 characters at a time, if it is specified.
fgets(alpha, 10, fr);
Here alpha is the name of buffer from where 10 characters are to be read
at a time. The file pointer fr points to the file from which the line is read,
and the line read is terminated with NULL. Therefore, it returns a line if
available and NULL if the file is empty or an error occurs in opening the file
or reading the file.
The complementary function to fgets() is fputs(). Obviously
fputs() will write a line of text into the file. The syntax is as follows:
int fputs (char * buf , file * fp );
The contents of array buf are written onto the file pointed to by fp. It
returns EOF on error and zero otherwise. Note that the execution of
fgets() returns a line and fputs() returns zero after a normal
operation.
The functions gets() and puts() were used with stdio, whereas
fgets() and fputs() operate on files.
We can write a program to transfer two lines of text from the buffer to
a file and then read the contents of the file to the monitor. This is shown in
Example 3.43.
Example 3.43: writing and
reading lines on files
*/ #include <stdio.h>
#include<string.h>
int main()
{
int i;
char alpha[80];
FILE *fr,*fw;
fw=fopen(“ws.doc”, “wb”);
for(i=0; i<2; i++)
{
printf(“Enter a line up to 80 characters\n”);
294 Self-Instructional Material
gets(alpha); Programming
fputs(alpha, fw);
}
fclose(fw);
fr=fopen(“ws.doc”, NOTES
“rb”); while
( fgets(alpha,20, fr)!
=NULL) puts(alpha);
fclose (fr);
}
Note carefully the fgets() statement. Here alpha is the buffer with a
width of 80 characters. Each line can be up to 80 characters and two lines
are entered through alpha to ws.doc. Later on, 20 characters are read
into alpha at a time from same file till NULL is returned.
Result of the program
Enter a line upto 80 characters
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Enter a line upto 80 characters
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaabbbb
bbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbb
bb
When a goto statement is used next statement is executed from the NOTES
label indicated
.
Goto statements is discouraged by many computer scientists, notably
Dijkstra.
c. Subroutines
The terminology for subroutines is not standard and it varies. Alternatively
subroutines are known as procedures, routines, functions or methods.
In the early stage of development in1950s, computer memories used to
be very smallhence subroutines were used for reducing program size. For this
reason small codes were written and reused at many places in the program.
These days, subroutines make a program more structured, and
provide modularity.
Minimal structured control flow
In May 1966, Böhm and Jacopini showed that program with gotos could
be transformed into a goto-free form using choice IF THEN ELSE and loops
such as WHILE condition DO xxx. At a later stage authors suggested the use
of loops in place of choice use of Bollean variables with looping and choice
statements using true/false flags could make program totally goto-free.
Such minimization is possible, but it does not mean it is desirable in
all circumstances. But Böhm and Jacopini had shown that it was possible to
make programs goto-free. Research has shown that control structures having
one entry and one exit easier in comparison to any other form. They can be
used anywhere in a program without disrupting the control flow.
Control structures in practice
Most programming languages use control structures with an initial keyword
indicating type of control structure involved. Languages then divide as to whether
or not control structures have a final keyword. Given below are language that
have no final keyword or have to final keyword.
No final keyword: Algol 60, C, C++, Haskell, Java, Pascal, Perl, PHP,
PL/ I, Python, PowerShell. Such languages require ways of grouping
statements together:
Algol 60 and Pascal : begin ... end
C, C++, Java, Perl, PHP, and PowerShell: curly brackets { ... }
PL/1: DO ... END
Python: uses indentation level (see Off-side rule)
Haskell: either indentation level or curly brackets can be used, and
they can be freely mixed
Self-Instructional Material 303
Programming
Final keyword: Ada, Algol 68, Modula-2, Fortran 77, Visual Basic.
The forms of the final keyword vary:
Ada: final keyword is end + space + initial keyword e.g. if ... end
NOTES if, loop ... end loop
Algol 68: initial keyword spelled backwards e.g. if ... fi, case ... esac
Fortran 77: final keyword is end + initial keyword e.g. IF ...
ENDIF, DO ... ENDDO
Modula-2: same final keyword end for everything
Visual Basic: every control structure has its own keyword. If ...
End If; For ... Next; Do ... Loop
Loops
A loop contains a sequence of statements, which is specified once but used
several times in succession. The code “inside” the body of the loop, shown
below as xxx is executed a specified number of times, until some condition is
met.
a. Count-controlled loops
Most programming languages use costructs to repeat a loop a specified
number of times. If N is less than 1 in examples given below then the body
is skipped completely, and if N = 1 the body is executed just once. In most
cases counting goes downwards instead of upwards and step sizes other
than 1 are used.
FOR I = 1 TO N for I := 1 to N do begin
xxx xxx
NEXT I end;
DO I = 1,N for ( I=1; I<=N; ++I ) {
xxx xxx
END DO }
c. Collection-controlled loops
Several programming languages (e.g. Ada, Smalltalk, Perl, Java, C#, Visual NOTES
Basic, Ruby, Python, JavaScript) special constructs allowing implicit looping
through every element of an array, or every member of a set or collection.
someCollection do: [:eachElement |xxx].
foreach someArray { xxx }
Collection<String> coll; for (String s : coll) {}
foreach (string s in myStringCollection) { xxx }
$someCollection | ForEach-Object { $_ }
d. General iteration
General iteration constructs in C is for statement and in Common Lisp it is
do used for expressing any of the above loops, as well as others. Looping is
also possible over a number of collections in parallel. Specific looping
construct is usually preferred over general iteration construct, as it makes
the purpose of the expression more clear.
e. Infinite loops
In certain situations, infinite loops are desired. It is desired that looping
should continue and terminate only when some exception, such as error
occurs. An event- driven program (such as a server) may be required to loop
forever handling events, stopping only when the process is killed by the
operator.
An infinite loop is mostly due to a programming error in a condition-
controlled loop, wherein the loop condition is never changed within the loop.
f. Continuation with next iteration
Sometimes it is desired to skip the remainder of the loop body and continue
with the next iteration. Some languages provide statements such as continue,
skip, or next for this. This, prematurely terminates the innermost loop body,
normal with next iteration. If the iteration is the last one in the loop, it
terminates the entire loop.
g. Redo current iteration
Some languages, such as Perl and Ruby, provide a redo statement that
restarts the current iteration from the beginning.
h. Early exit from loops
In a count-controlled loop that searches through a table, it is desired to stop
when the desired item is found. Statement such as break or exit are
provided by some programming languages.Using break or exit the current
loop is immediately terminated and control is transferred to the statement
immediately following that loop. Things can get a bit messy while searching
a multi-dimensional table using nested loops. Self-Instructional Material 305
Programming
The following example is done in Ada which supports both early exit from
loops and loops with test in the middle. Both these features have similarity
but codes are different. Codes for early exit needs combination with an if
statement whereas a condition in the middle is a self contained construct.
NOTES with Ada.Text IO;
with Ada.Integer Text IO;
procedure Print_Squares
is
X : Integer;
begin
Read_Data : loop
Ada.Integer Text
IO.Get(X); exit Read_Data when
X = 0;
Ada.Text IO.Put (X *
X); Ada.Text
IO.New_Line;
end loop
Read_Data; end
Print_Squares;
Python provides support for conditional execution of code and this depends
on whether a loop was exited early using a break statement or not by using
an else- clause with the loop. For example,
for n in
set_of_numbers: if
isprime(n):
print “Set contains a prime
number” break
b. Exceptions
Modern languages provide a structured construct for handling exception and
do not rely on the use of GOTO:
try {
xxx1 // Somewhere in here
xxx2 // use: ’’throw’’
someValue; xxx3
} catch (someClass& someId) { / / c a t c h v a l u
e o f someClass
actionForSomeClass
} catch (someType& anotherId) { // catch value of
someType
actionForSomeType
} catch (...) { // catch anything not already
caught actionForAnythingElse
}
Catch can have many numbers and varieties of clauses for use. In D,
Java, C#, and Python a finally clause is added to the try construct. It does
not matter how the control comes out of the ‘try’ clause, the code inside the
finally clause is guaranteed to execute. This is useful when writing code that
must relinquish an expensive resource when finished processing:
FileStream stm = null; // C#
example try {
stm = new FileStream (“logfile.txt”,
FileMode.Create);
return ProcessStuff(stm); // may throw an
exception
} finally {
if (stm != null)
stm. Close();
}
Since this pattern is fairly common, C# has a
special syntax:
using (FileStream stm = new FileStream (“logfile.txt”,
FileMode.Create)) {
NOTES On leaving the block, named using, the compiler guarantees the release
of the object stm. With statement of Python and block argument to File.open
of Ruby are used to get similar effect.
All these languages provide definition for standard exceptions and
circumstances under which these are thrown. Users may throw exceptions of
their own. C++ and Python permit users to throw and catch of almost any
type.
In case there is no catch that matches a particular throw, then control
moves back through subroutine calls and/or nested blocks to find a
matching catch or reaching the end of the main program and at this, point
program is forcibly stopped giving suitable error message.
Proposed control structures
In a spoof Datamation article in 1973, a suggestion was put by R.
Lawrence Clark that the COMEFROM statement could replace GOTO and
this provides some interesting examples. This found actual implementation
in programming language INTERCAL, which is a language designed to make
programs as obscure as possible.
Donald Knuth in his article ‘Structured Programming with go to
Statements’, published in 1974, identified two situations that remained
uncovered by the control structures listed above. He produced examples of
control structures capable of handling these situations. These constructions
inspite of their utility failed to find their way into mainstream programming
languages.
Loop with test in the middle
Dahl proposed this in 1972.
loop loop
xxx1 read(char);
while test; while not
atEndOfFile; xxx2 write(char);
repeat; repeat;
Structured programming
Structured programming may be viewed as a subset or subdiscipline of
procedural programming. It is a major programming paradigm. Its popularity
is due to the fact that it reduces reliance on GOTO statement.
Historically, there are different methodologies or techniques adopted
for structured programming. Three most common techniques are:
1. Structured programming of Edsger Dijkstra in which logic of a program
has a structure made up of limited number of similar sub-structures. This
reduces efforts to understand a program as each substructure is small
and entire program is made up of many such similar structures.
2. A view that has been derived from Dijkstra that advocates splitting a
program into manysub-sections with each having one entry point but
there is another view that support the concept of one exit point instead
of entry points.
3. Data Structured Programming or Jackson Structured Programming,
Programming
NOTES
In Figure 3.4, an example of top down design has been taken in which
part design creates assembly which refers to skeleton model. Then skeleton
geometry is created to capture all the interfaces among various
components. So, the information is needed for starting point of the
geometry. The assemble part is created if the skeleton geometry refers to
individual part. Assembling parts make the location where interconnects and
other boundaries occur. At last assembly drawing is created after checking
the condition ‘done assembling parts’ otherwise control goes to iterate the
assemble part.
Bottom up design
The bottom up structured design starts to solve the low level bit
manipulation, number crunching and timestamp problem. It implies to solve
Self-Instructional Material 317
the programming part from lowest level. The lowest level corresponds with
the right inputs and
Programming
outputs linked with the program. It keeps the track of specified input and
output maintaining the data dictionary. It incorporates a hierarchical table
which provides a list of basic and prime data types. This technique refers
the construction of applications that starts with primitive of programming
NOTES
language. It generates complicated features in programming if one
application is linked with the other application. This is considered to be
more useful than top down design because stubs are not needed to simplify
the testing. The test functions are necessarily written as they are easy to
understand and write. This technique is basically used in interactive
programming environment, for example, Common Lisp. In the Common
Lisp, abstract data types are built to use macros in constructing special forms.
It uses lists to pass the arguments and maintains a standardized data structure
which makes it abstract data type more instead of function. The small
modules or pieces of programs are written from bottom end. It is more
reusable in application specific language. The specified language must be
simple to implement the entire class ofapplications. It is easy to maintain by
adding new features in the applications. It lessens in delaying to take the final
decision of exact functionality of applications. The computer languages C and
Java construct abstract data types from primitive of the language or from the
abstract data type.
PROGRAM CORRECTNESS
In Figure 3.6, general outline of the program keeps input conditions and
output conditions. The body of the algorithm continues between these two
requirements and divided into many subtasks, such as subtask 1, subtask 2
and subtask 3. It shows a tree structure because subtasks may have many
branches. Aset of values are assigned to the parameter x is also known
domain of x. For example,
}
printf(“Sum = %d\n”,
sum); getch();
}
Debugging
Debugging refers a process identifying the root cause ofprogramming errors
through which users can edit or correct the program errors. This process
finds the errors to debug from the starting point of the programming part.
User can select any one source to debug the program, such as design, data
program etc. The following factors are available in debugging the programs:
It echoes the programming code on the screen.
It identifies missing variables, operators or values.
It identifies those variables which are un-initialized in the program.
It provides diagnostic capsules, for input and output data sets.
NOTES
Testing
A set of required activity with reference to computer programming is known
as testing (Figure 3.8). It has the following characteristics:
This type of testing works with large number of input values, complex
numerical values, large number of queries that checks the extra loading of the
applications.
NOTES
Load Testing
This testing works with testing of web sites to find the failure point of web
site applications and the performance degrades.
The advantages and disadvantages of black box are as follows:
Advantages of black box testing
The advantages of black box are as follows:
If the testing is done with black box, it is reproducible.
The overall environment in which programruns is also tested in this
method.
The invested effort is reused multiple times.
Disadvantages of black box testing
The disadvantages of black box are as follows:
Produced result is overestimated.
All the properties of software are not tested.
The reason behind failure is not found.
White box (structural testing)
This technique refers to structural design that implies to access the code or
test for all possible paths. These paths are possible path required in structural
testing. The program is analysed by double check conditionals. Paths
represent various routes through that are included in the program. For
example,
if (a>b)
{
p=p+1;
}
else
{
p=p+3;
}
if
(c<d)
{ p=p+3;
}
else
{ p=p+4;
if (Code_C)
{
instruction block B_1
}
else
{
instruction block B_2
}
In the above code, the given conditions specified in a program are not
independent to each other and also all paths are not possible. So, only two
possible routes can work in executing the programs. If the instruction
blocks either A_1 or A_2 is executed because Code_C is satisfied but
paths A_1 and B_2 and A_2 and B_1 are never executed if the given
condition Code_C comes false.
This testing makes path testing complicated. The loop contains bugs that
increase the programming complications and not easy to find. The nested
loops conceal many bugs. For example, the following set of instruction
shows the loop testing: NOTES
label_one:
instruction block
A_1 label_two:
if Code_C1 then goto
label_one: instruction
block A_2
if Code_C2 then goto label_two:
In the above set of instruction, the command goto is
used.
Domain testing
SUMMARY
KEY TERMS
Constants: Refer to fixed values which do not change during the
execution of a program.
Variable: Refers to a symbol that stands for a value which may vary.
Operator: refers to a symbol which indicates an operation to be executed.
Recursion: A powerful technique which is used to call a function itself.
Pointer: A pointer is a variable that points to another variable.
Address operator: An operator which assesses the address of its
operand. Also called a substitute variable.
Dynamic memory allocation: Functions of the C library to allocate
memory storage space at run-time.
Label: An explicit name or number assigned to a fixed position within
the source code, and which may be referenced by control flow
statements appearing elsewhere in source code.
Loops: Asequence of statements which is specified once but which
may be carried out several times in succession.
Debugging: Refers to the process identifying the root cause of
programming errors through which users can edit or correct the
program errors.
Programming
1. The information pointed at by a file pointer is:
Location of the buffer
The position in the file of the character currently being pointed to
NOTES Whether the file is being read or written
Whether an error has occurred or the end of the file has been reached.
2. Count-controlled loop, condition-controlled loop, collection-controlled
loop and infinite loops aer the four types of loops.
3. Common non-local control constructs are exceptions, conditions and
continuations.
4. The steps that can be taken to lessen the memory requirements are:
Program must be simple.
Simple algorithms must be used.
Arrays, strings and pointers must be declared with suitable
memory address and correct sizes
Multidimensional arrays must be limited.
Memory compression features must be evaluated and incorporated.
5. Verification and validation are the two processes to test program.