Stractured Programming Converted.docx
Stractured Programming Converted.docx
MINISTRY OF EDUCATION
DIPLOMA IN INFORMATION
COMMUNICATION
TECHNOLOGY
Structured
Programming
MODULE I: SUBJECT
NO 4
STRUCTURED PROGRAMMING BY LARRY BETT
Contents
CHAPTER 1: INTRODUCTION TO STRUCTURED PROGRAMMING........................................ 4
Basic Programming Concept..................................................................................................... 4
Structured programming and other programming languages.................................................... 4
Development of Programming Language.................................................................................. 5
Programming Paradigms........................................................................................................... 6
Computer hardware and software consideration....................................................................... 6
CHAPTER 2: PROGRAM DEVELOPMENT AND DESIGN........................................................ 10
Introduction to program development...................................................................................... 10
Program Development Cycle................................................................................................... 10
Programming Techniques.........................................................................................................11
Programming Tools.................................................................................................................. 18
CHAPTER 3 PROGRAM STRUCTURE......................................................................................36
Introduction to program structure.............................................................................................36
Format of a structured programming language........................................................................36
Basic C Programs - Variable and I/O instructions.................................................................... 38
Program Structures in Pascal.................................................................................................. 41
Data types, identifiers and operators....................................................................................... 44
Variable Types..........................................................................................................................46
Operator Types........................................................................................................................ 48
CHAPTER 4: PROGRAM WRITING........................................................................................... 60
Content of structured programming......................................................................................... 60
Steps to Develop a Program....................................................................................................60
Error Handling..........................................................................................................................61
CHAPTER 5: CONTROL STRUCTURES................................................................................... 65
Introduction to control structures..............................................................................................65
Sequence structure..................................................................................................................65
Selection/Decision Structure....................................................................................................65
Loops/Iterations....................................................................................................................... 74
Loop Control Statements......................................................................................................... 81
CHAPTER 6: DATA STRUCTURES............................................................................................87
Introduction to Data Structures................................................................................................ 87
STRUCTURED PROGRAMMING BY LARRY BETT
R 1: INTRODUCTION TO STRUCTURED
PROGRAMMING
Basic Programming Concept
Program and Programming
A computer program is a series of organized instructions that directs a computer to perform
tasks. Without programs, computers are useless.
A program is like a recipe. It contains a list of variables (called ingredients) and a list of
statements (called directions) that tell the computer what to do with the variables.
A programming language is a set of words, symbols and codes that enables humans to
communicate with computers.
Programming Paradigms
A programming paradigm is a style or ―way‖ of programming. Some languages make it
easy to write in some paradigms but not others. Never use the phrase ―programming
language paradigm.‖ A paradigm is a way of doing something (like programming), and not a
concrete thing (like a language).
Paradigms are not meant to be mutually exclusive; you can program in a functional, object-
oriented, event-driven style.
On most computer platforms, software can be grouped into a few broad categories:
STRUCTURED PROGRAMMING BY LARRY BETT
● System software is the basic software needed for a computer to operate (most
notably the operating system);
● Application software is all the software that uses the computer system to
perform useful work beyond the operation of the computer itself;
● Embedded software resides as firmware within embedded systems, devices
dedicated to a single use. In that context there is no clear distinction between
the system and the application software.
Software contracts
Software contracts include the costs, purpose and capacity of the software. The
following are covered in software contracts:
STRUCTURED PROGRAMMING BY LARRY BETT
Warrant terms
Support available
Maintenance arrangements
Performance criteria
Ownership
Software licensing
Software licensing covers the following:
Number of users that can install and use the software legally
Limitation of liability e.g. if the user commits fraud using the software
Capacity (e.g. is the hard disk big enough to hold all your data? Is it fast
enough?)
Reliability - can it be depended on?
STRUCTURED PROGRAMMING BY LARRY BETT
Cost - initial cost, running costs, upgrade costs, repair costs, training costs
Compatibility - with your other equipment, and that of your partners and clients
Choosing a supplier
After choosing the hardware equipment and the equipment makers (manufacturers),
one must choose a supplier or reseller (in other words, once you know what you want
to buy, what shop will you choose?)
Factors to consider:
Reputation for support (e.g. phone support, onsite visits, website help)
Geographic location - can you get to them easily if you need to?
Installation
Software and hardware installation is done by supplier’s technicians or the user
organization appointed person to avoid the risks associated with improper installation
of the equipment. The system analyst and other development team members may be
called to assist where appropriate.
User training
It is important that the system users be trained to familiarize themselves with the
hardware and the system before the actual changeover.
The aims of user training are:
CHAPTER 2: PROGRAM
DEVELOPMENT AND
DESIGN
Introduction to program development
Program development in computing; refer to the coding of an individual software
program or to the creation on an entire information system and all related software.
Program design is the activity of progressing from a specification of some required program to a
description of the program itself.
It is the process that organizations use to develop a program. Ideally, the process is
collaborative, iterative, and tentative—stakeholders work together to repeat, review, and refine a
program until they believe it will consistently achieve its purpose.
A program design is also the plan of action that results from that process. Ideally, the plan is
developed to the point that others can implement the program in the same way and consistently
achieve its purpose.
Programming Techniques
Software designing is very anesthetic phase of software development cycle. The beauty of heart,
skill of mind and practical thinking is mixed with system objective to implement design.
The designing process is not simple, but complex, cumbersome and frustrating with many curves
in the way of successful design.
Structural Programming
Modular Designing
Top Down Designing
Bottom Up Designing
Object Oriented Programming
(ii) Demand of Organization: The new system is developed and installed on the
demand of organization and working groups.
(iv) Competition: The new system is a matter of status also. In the age of roaring
competition, if organization does not cope with modem technology failed to face competitions.
1. Structured Programming
This is the first programming approach used widely in beginning. Professor Edsger Wybe
Dijkstra (1960) coins the term Structural Programming. Italian computer scientist C. Bohm and
G. Jacopini (1966) give the basic principal that supports this approach. The structured
programming movement started in 1970, and much has been written about it. It is often regarded
as ―goto-less‖ programming, because it is avoided by programmers.
The program is divided into several basic structures. These structures are called building blocks.
(a) Sequence Structure: This module contains program statements one after another.
This is a very simple module of Structured Programming.
Sequence Structure
(b) Selection or Conditional Structure: The Program has many conditions from which
correct condition is selected to solve problems. These are (a) if-else (b) else-if, and (c)
switch-case
STRUCTURED PROGRAMMING BY LARRY BETT
Conditional structure
(c) Repetition or loop Structure: The process of repetition or iteration repeats statements
blocks several times when condition is matched, if condition is not matched, looping process
is terminated. In C, (a) goto, (b) for (), (c) do, (d) do – while are used for this purpose.
Loop Structure
Advantage:
● Problem can be easily described using Flowchart and flowchart can be easily
coded into program because the nature of this technique is like as flowchart.
● The program is easily coded using modules.
● The testing and debugging is easy because testing and debugging can be
performed module-wise.
● Program development cost low.
● Higher productivity, high quality program production.
● Easy to modify and maintain
STRUCTURED PROGRAMMING BY LARRY BETT
Disadvantage:
More memory space is required. When the numbers of modules are out of certain range,
performance of program is not satisfactory.
2. Modular Programming
When we study educational philosophy, the concept of modulation can be clear without any
ambiguity. Rene Descartes (1596-1650) of France has given concept to reconstruct our
knowledge by piece by piece. The piece is nothing, but it is a module of modem programming
context.
In modular approach, large program is divided into many small discrete components called
Modules. In programming language, different names are used for it.
For example:
It is logically separable part of program. Modules are independent and easily manageable.
Generally modules of 20 to 50 lines considered as good modules when lines are increased, the
controlling of module become complex.
Modules are debugged and tested separately and combined to build system. The top module is
called root or boss modules which charges control over all sub-modules from top to bottom. The
control flows from top to bottom, but not from bottom to top.
The evaluation of modeling is called coupling and cohesion. The module coupling denotes
number of interconnections between modules and module cohesion shows relationship among
data or elements within a module.
STRUCTURED PROGRAMMING BY LARRY BETT
Modular Programming
(b) At first supervisor program is identified to control other sub modules. Main modules are
divided into sub modules, sub-modules into sub- sub- modules. The decomposition of modules
is continuing whenever desired module level is not obtained.
(c) Top module is tested first, and then sub-modules are combined one by one and tested.
Example: The main program is divided into sub-program A, B, and C. The A is divided into
subprogram A1, A2 and A3.The B is into B1, and B2. Just like these subprograms, C is also
divided into three subprogram C1, C2 and C3. The solution of Main program is obtained from
sub program A, B and C.
4. Bottom up Approach
● In this approach designing is started from bottom and advanced stepwise to top.
So, this approach is called Bottom up approach.
● At first bottom layer modules are designed and tested, second layer modules
are designed and combined with bottom layer and combined modules are
tested. In this way, designing and testing progressed from bottom to top.
STRUCTURED PROGRAMMING BY LARRY BETT
(i) Abstraction: The abstraction is an important property of OOP. The use of essential
features over less essential features is called abstraction. The following examples will help to
understand abstraction.
Example: The computer operators know only to operate computer, but they are unaware to
internal organization of computer.
In OOP, there are many devices used for data abstraction such as class, encapsulation, data
hiding etc.
(ii) Class: A class is a collection of similar objects. Objects are members of class. Once a
class is declared, its many members can be easily created in programs. The class binds attributes
(data and functions or methods) of member objects.
STRUCTURED PROGRAMMING BY LARRY BETT
Examples:
Class employee
char name[30];
float basic;
void getdata();
void show();
};
(iii) Polymorphism: The ability to find in many forms is called polymorphism (Poly: many,
Morphe: shape / form). For instance, + is mathematical operator, it concatenates two strings
and give sum of two digits (numbers). Here, operator + has different behavior for numerical
data and strings. Just like it, once declared function has different meaning that is called function
overloading. If operator has different meaning, it is called operator overloading.
(iv) Encapsulation: The encapsulation is a very striking feature of OOP in which data and
function is bound into single unit. Array, records, structure are also example of low level
encapsulation but term encapsulation is mostly used in object oriented language. The data and
function are encapsulated into class. External world or external function cannot access the
data. It can be accessed by its own function or method encapsulated with it into class. It hides
private elements of objects behind public interface.
(a) Single Inheritance: A derived class (child class or sub class) of single base (super or
parent) class is called single Inheritance.
(b) Multiple Inheritances: A derived class of multiple base classes is called Multiple Inheritance.
(c) Multilevel Inheritance: When derived class is derived from another derived class, such
type of inheritance is called Multilevel Inheritance.
Programming Tools
The programming is a solution of different problems of our real life. If efficient programming
tools are used, problems are effectively solved. We code some instructions to instruct computer
for problem solving purposes. The choice of tools depends on nature of problems.
There are many tools for programmers for programming. For instance, algorithms, flowcharts,
pseudocodes, data dictionary, decision table, data flow diagrams etc are effective tools.
Enough and adequate knowledge of programming tools are essential for programming (Software
development).
1. Flowchart
The pictorial presentation of program is called Flowchart. It is a tool and technique to find out
solution of programming problems through some special symbols. It is a way to represent
program using geometrical patterns. Prior to 1964, every manufactures use different types of
symbols, there was no uniformity and standards of flowcharting. The Standard symbols were
developed by American Standard National Institute (ANSI).
(i) Start / Stop: This oval is used to represent START and STOP of program.
(ii) Input/Output: Parallelogram is used to denote input and output of data. We take
data through it and display result also using this symbol.
(iii) Process: Rectangle is used to denote process, formula, increment, and decrement
and assigned value also.
(iv) Pre-defined Process: The predefined process is denoted by this symbol. Example:
Sorting and Display is pre-defined process and represented as:
Pre-defined Process
STRUCTURED PROGRAMMING BY LARRY BETT
(iv) Decision box: It is a symbol of decision. All type of decisions is written in it.
(vi) Data flow: It is used to show data flow from one component to other component,
one process to other and one symbol to other symbol.
The John Von Neumann used flowchart to solve problem in 1945 and explained its importance
in program designing.
Illustration: In our everyday life, there is a sequence of works. These sequences of works are
called routine. We all are tied with it. Suppose, we arise early in the morning at 5 0‘ clock, go to
toilet, after coming from toilet, clean hands with soap and water, brush our teeth then take bath.
Here, one sequence of work is formed.
In computer world, programming language is used to solve certain problems. The solution of
problem is a sequence of processes. In one problem, there may be many processes, the flowchart
help to arrange processes in definite order. Suppose, we have to convert Fahrenheit temperature
into Celsius, it has following five steps:
● Step-1: Start
● Step-2: Enter Fahrenheit temperature (F)
● Step-3: Application of formula: C=(F-32)(5/9)
● Step-4: Displaying the result (C)
● Step-5: Stop
These types of processes involved in solution of problem are called Algorithm. It is a stepwise
presentation of problem solution in simple English without using confusing words and phrases.
Flow Chart
Flowchart is like as city map. Travelers or tourists search places of historical importance through
city map. Buildings are built on the basis of building-design (map) drawn by Architect engineers.
Just like it, program is coded on the basis of flowchart. Flowchart is a language free concept, if it
is prepared, any language can be used for program coding. In software development cycle,
flowcharting is one essential phase.
System Flowchart:
System flowchart is a pictorial representation of procedure flows inside and outside of the
systems. It is also called Data Flow Chart or Procedure Chart.
STRUCTURED PROGRAMMING BY LARRY BETT
(i) Manual Input: It is used to enter data manually. For example, keyboard is a manual
input device.
(v) Display: This is a symbol for online display, Example: Monitor (VDU).
Problem-1: The source program is stored in hard disk and after compilation; the object
program (Machine code) is also stored in hard disk. The rectangle represents compilation
process. The error messages are printed out and displayed on VDU also.
Compilation Process
Problem-3: The headquarter of ABC Private Ltd. is linked with production, marketing and
sale department. The day-by-day information of each department is compiled at headquarter,
stored in master file and report is given to higher authority of company.
STRUCTURED PROGRAMMING BY LARRY BETT
2. Algorithm
Algorithm is a stepwise presentation of procedures of program in simple and phraseless English.
It is also a programming tools used by programmer to develop software. It is a logical
representation of program procedures in order to obtain result. So, sometimes, it is called
Procedure also. An algorithm, named after the ninth Centaury scholar Abu Jafar Muhammad
Ibn Musa Al-Khowarizmi of Bagdad (Iraq).
● Language independent
● Simple, complete, unambiguous, step-by-step program flow
● no standard format or syntax for the algorithm
● helpful to understand problems and plan out solution
● Step-1: Start
● Step-2: Read a,b and c
● Step-3: d=b*b-4*a*c
● Step-4: if D<0, root is imaginary
● Step-5: x1 = (-b + sqrt (D))/(2*a)
X2=(-b-sqrt(D))/(2*a)
● Step-7: Stop
Example: Write an algorithm to find out area of triangle when sides are given.
Algorithm:
Step-1: start
Step-3: S=(a+b+c)/2
Step-4: A=sqrt((s-a)(s-b)(s-c))
Step-5: Display A
Step-6: Stop
Example: Write an algorithm to find out slop and mid point of coordinate.
Algorithm:
Step-1: Start
Step-3: Slop=(y2-y1)/(x2-x1)
Step-4: x-(x1+x2)/2
Step-6: Stop
There are no standard rule for algorithm designing, but we can use some common rules which
are not ambiguous to another computer literates:
(b) Conditional statements: if -endif and if –else-end-if are used for conditions.
STRUCTURED PROGRAMMING BY LARRY BETT
Example:
18‖ Endif
i. do while
(condition)
Statement(s)
endo
stepvalue statement(s)
endfor
Fact = 1
Read number
Endfor
Print ―Factorial:‖,
fact End
STRUCTURED PROGRAMMING BY LARRY BETT
Problem-1: Draw a flow chart to input two numbers and display sum.
Problem-2: Draw a flowchart to enter principal,rate and time and display simple interest.
Solution,
(c) Phrase less statements, contains noun and simple verb of English , and
It is a Program Design Language (PDL) provides skeleton for program design and it can
replace flowchart used to describe system design.
(i) Imperative Sentence: The imperative sentences are used to show actions.
(ii) Operators: Mostly arithmetic operators (+, -, *, / etc) and relational operators (=, =>, =>, <,
> etc.) are used.
(iii) Decision: IF, THEN, ELSE, ENDIF, CASE, ENDCASE are used for decision-making.
Example:
CASE (choice)
ENDCASE.
(iv) Looping: The looping or repetition of statements is shown by FOR, FOR DO,
ENDFOR, DO, DO WHILE, DO UNTIL, ENDDO etc.
Example:
ENDFOR.
Example:
IF age >=18
ELSE
STRUCTURED PROGRAMMING BY LARRY BETT
ENDIF
BEGIN
WRITE a letter
IF bicycle is available
ELSE
ENDIF
BUY a stamp
END.
4. Decision Table
A decision table defines a logical procedure by means of a set of conditions and related actions.
It is used for communicating and documenting complex decision procedures.
Procedure: The decision table is divided into four quadrants: Condition stub, Condition entry,
Action stub, and action entry. The conditions are answered as Y (yes) or N (No). The blank
space shows that the condition involved has not been tested. X (or check marks) represents
response to the answer.
STRUCTURED PROGRAMMING BY LARRY BETT
Condition Stub C1 R1 R2 R3 R4
C2 Condition entry
Cn
Action Stub A1 Action entry
A2
An
Problem: The policy followed by an ABC Ltd. to process agents‘ orders is given by the
following rules:
(i) If the customer order <= that in stock and his credit is OK, supply his requirement.
(ii) If the customer credit is not OK, do not supply. Send him intimation.
(iii) If the customer credit is OK but items in stock are less than his order, supply what
is in stock. Enter the balance to be sent in a back-order file.
Decision Table:
Order <=Stock Y Y N N
y N Y N
Credit OK
A1: Supply order X - - -
Pay cash
-
STRUCTURED PROGRAMMING BY LARRY BETT
Problem: Create a decision table to decide whether on a given data a student in an University
has completed 3 years of enrolment or not.
Decision Table:
Problem: The Delta gas company bills its customers according to the following rate schedule:
The input record has customer identification, name and address, new meter reading, past and
present. Create decision table to obtain bill for customers.
Decision Table:
Charge table:
Go To C1 C2 C3 C4
C1: Charge=50
Problem. A bank has the following policy on deposits: on deposits of Rs. 25000 and above and
for three years or above the interest is 10%. On the same deposit for a period less than three
years it is 8%. On deposits below Rs. 25000 the interest is 6% regardless of the period of
deposit.
Write the above process using
Solution
do If deposit>=25000
Then interest=10%
Else interest=8%
Endif
Else interest 6%
Endfor
STRUCTURED PROGRAMMING BY LARRY BETT
Deposit>=25000 Y Y N
Y N -
Interest % 10 8 6
5. Decision Tree
The tree like presentation of condition and actions are called decision tree. Every node
denotes conditions. It is used for logical variations and problems involving few complex
decisions with complex branching routines.
Example: The person which age is greater or equal to 18 can caste vote in the favour of his leader
otherwise has to wait until age of 18. There is two conditions (a)age<18, and (b)age>=18, both
the conditions have actions.
Decision Tree
Example: The hotel ABC offers new discount scheme foe university students. It provides 15%
and 10% discount to monthly customers for vegetarian and non-vegetarian meal respectively.
The student attend hotel occasionally have discount rate 10% and 5% for vegetarian and non-
vegetarian meal.
STRUCTURED PROGRAMMING BY LARRY BETT
● Preprocessor Commands
● Functions
● Variables
● Statements & Expressions
● Comments
The following program is written in the C programming language. Open a text file hello.c using
vi editor and put the following lines inside that file.
Preprocessor Commands: These commands tells the compiler to do preprocessing before doing
actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler
to include stdio.h file before going to actual compilation. You will learn more about C
Preprocessors in C Preprocessors session.
Functions: are main building blocks of any C Program. Every C Program will have one or more
functions and there is one mandatory function which is called main() function. This function is
prefixed with keyword int which means this function returns an integer value when it exits. This
integer value is retured using return statement.
The C Programming language provides a set of built-in functions. In the above example printf()
is a C built-in function which is used to print anything on the screen.
Variables: are used to hold numbers, strings and complex data for manipulation.
STRUCTURED PROGRAMMING BY LARRY BETT
Statements & Expressions : Expressions combine variables and constants to create new values.
Statements are expressions, assignments, function calls, or control flow statements which make
up C programs.
Comments: are used to give additional useful information inside a C Program. All the
comments will be put inside /*...*/ as given in the example above. A comment can span through
multiple lines.
Note:
● There should be a main ( ) function somewhere in the program to determine where to
start the executions.
● Usually all C statements are entered in small case letters.
● The group of statements in main ( ) are executed sequentially.
● The left brace indicates the program opening.
● The right brace indicates the program closing.
● In C language Comments are enclosed with /* -- */ means these statements won‘t execute
when the program is complied.
A C program consists of one or more functions. Each function performs a specific task. A
function is a group or sequence of C statements that are executed together.
Every C program starts with a function called main(). This is the place where program
execution begins. Hence, there should be main() function in every C program. The functions are
building blocks of C program. Each function has a name and a list of parameters.
Let us look at a simple code that would print the words "Hello World":
1. The first line of the program #include <stdio.h> is a preprocessor command, which tells
a C compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the
message "Hello, World!" to be displayed on the screen.
5. The next line return 0; terminates main()function and returns the value 0.
Each variable in C has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
STRUCTURED PROGRAMMING BY LARRY BETT
a) Working with variables - Let's look at an example of how to declare an integer variable in
the C language, assign value and read the value in the variable to output.
For example:
int age;
#include <stdio.h>
int main()
{
int age;
age = 10;
printf("TechOnTheNet.com is over %d years old.\n", age);
return 0;
}
The special character tells the program how to convert the data.
#include <stdio.h>
main(){
int x;
float y;
char c;
x = -4443;
y = 554.21;
c = 'M';
}
The value of integer variable x is -4443
The value of float variable y is 554.210022
The value of character variable c is M
More examples: Use the scanf function with formatting options assign to assign value to
variables.
This C program would print "Your Name is Kim and you age is over 10 yrs old."
#include <stdio.h>
main(){
int Age;
char Name[10];
}
STRUCTURED PROGRAMMING BY LARRY BETT
● Program name
● Uses command
● Type declarations
● Constant declarations
● Variables declarations
● Functions declarations
● Procedures declarations
● Main program block
● Statements and Expressions within each block
● Comments
Every pascal program generally has a heading statement, a declaration and an execution part
strictly in that order. Following format shows the basic syntax for a Pascal program −
begin
writeln('Hello, World!');
readkey;
end.
Hello, World!
● The first line of the program program HelloWorld; indicates the name of the program.
● The second line of the program uses crt; is a preprocessor command, which tells
the compiler to include the crt unit before going to actual compilation.
● The next lines enclosed within begin and end statements are the main program block.
Every block in Pascal is enclosed within a begin statement and an end statement.
However, the end statement indicating the end of the main program is followed by a
full stop (.) instead of semicolon (;).
● The begin statement of the main program block is where the program execution begins.
● The lines within (*...*) will be ignored by the compiler and it has been put to add a
comment in the program.
● The statement writeln('Hello, World!'); uses the writeln function available in Pascal
which causes the message "Hello, World!" to be displayed on the screen.
● The statement readkey; allows the display to pause until the user presses a key. It is part
of the crt unit. A unit is like a library in Pascal.
● The last statement end. ends your program.
Variables
A variable definition is put in a block beginning with a var keyword, followed by definitions of
the variables as follows:
var
A_Variable, B_Variable ... : Variable_Type;
i.e. A, b, c:interger
Pascal variables are declared outside the code-body of the function which means they are not
declared within the begin and end pairs, but they are declared after the definition of the
procedure/function and before the begin keyword. For global variables, they are defined after the
program header.
Functions/Procedures
In Pascal, a procedure is set of instructions to be executed, with no return value and a function
is a procedure with a return value. The definition of function/procedures will be as follows −
Function Func_Name(params...) : Return_Value;
STRUCTURED PROGRAMMING BY LARRY BETT
Procedure Proc_Name(params...);
Comments
The multiline comments are enclosed within curly brackets and asterisks as {* ... *}. Pascal
allows single-line comment enclosed within curly brackets { ... }.
{* This is a multi-line comments
and it will span multiple lines. *}
Case Sensitivity
Pascal is a case non-sensitive language, which means you can write your variables, functions and
procedure in either case. Like variables A_Variable, a_variable and A_VARIABLE have same
meaning in Pascal.
For example −
Note: All pascal functions and control structures start with name and follow with
Begin..End in place of carry bracket “, -” used in C programs.
1. Function Example
function name(argument(s): type1; argument(s): type2; ...): function_type;
local declarations;
begin
...
< statements >
...
name:= expression;
end;
program exFunction;
var
a, b, ret : integer;
Whitespace - A line containing only whitespace, possibly with a comment, is known as a blank line,
and a C compiler totally ignores it.
STRUCTURED PROGRAMMING BY LARRY BETT
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify where
one element in a statement, such as int, ends and the next element begins. Therefore, in the following
statement:
Data type
In the C programming language, data types refer to an extensive system used for declaring
variables or functions of different types. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted.
● int
● float
● double
● char
Please note that there is not a boolean data type. C does not have the traditional view about
logical comparison, but thats another story.
Variable Types
A variable is just a named area of storage that can hold a single value (numeric or character). The
C language demands that you declare the name of each variable that you are going to use and its
type, or class, before you actually try to do anything with it.
● Local Variables
● Global Variables
Local Variables
● Local variables scope is confined within the block or function where it is defined.
Local variables must always be defined at the top of a block.
● When a local variable is defined - it is not initalised by the system, you must initalise it
yourself.
● When execution of the block starts the variable is available, and when the block ends
the variable 'dies'.
STRUCTURED PROGRAMMING BY LARRY BETT
Here ++ is called incremental operator and it increase the value of any integer variable by 1.
Thus i++ is equivalent to i = i + 1;
You will see -- operator also which is called decremental operator and it idecrease the value of
any integer variable by 1. Thus i-- is equivalent to i = i - 1;
Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by any
function that may reference it.
Global variables are initalised automatically by the system when you define them!
If same variable name is being used for global and local variable then local variable takes
preference in its scope. But it is not a good practice to use global variables and local variables
with the same name.
main()
{
i++; /* Global variable */
func();
printf( "Value of i = %d -- main function\n", i );
}
func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}
i in main function is global and will be incremented to 5. i in func is internal and will be
incremented to 11. When control returns to main the internal variable will die and and any
reference to i will be to the global.
Operator Types
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and
5 are called operands and + is called operator. C language supports following type of operators.
● Arithmetic Operators
● Logical (or Relational) Operators
● Bitwise Operators
● Assignment Operators
● Misc Operators
Arithmetic Operators:
There are following arithmetic operators supported by C language:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
STRUCTURED PROGRAMMING BY LARRY BETT
Example
Try following example to understand all the arithmatic operators. Copy and paste following C
program in test.c file and compile and run this program.
Examples
Assume variable A holds 10 and variable B holds 20 then:
Try following example to understand all the Logical operators. Copy and paste following C
program in test.c file and compile and run this program.
STRUCTURED PROGRAMMING BY LARRY BETT
Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
STRUCTURED PROGRAMMING BY LARRY BETT
Examples
Try following example to understand all the Bitwise operators. Copy and paste following C
program in test.c file and compile and run this program.
STRUCTURED PROGRAMMING BY LARRY BETT
Assignment Operators:
Examples
Try following example to understand all the Assignment Operators. Copy and paste following C
program in test.c file and compile and run this program.
So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y
= x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is
invalid.
Misc Operators
There are few other operators supported by C Language.
Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is interger, will return 4.
& Returns the address of a variable. &a; will give actaul address of the variable.
* Pointer to a variable. *a; will pointer to a variable.
If Condition is true ? Then value X :
?: Conditional Expression
Otherwise value Y
STRUCTURED PROGRAMMING BY LARRY BETT
Examples
sizeof Operator:
Try following example to understand sizeof operators. Copy and paste following C program in
test.c file and compile and run this program.
? : Operator
Try following example to understand ? : operators. Copy and paste following C program in test.c
file and compile and run this program.
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
Precedence of C Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.
STRUCTURED PROGRAMMING BY LARRY BETT
Designing an Algorithm: With the problem statement obtained in the previous step, various
methods available for obtaining the required solution are analyzed and the best suitable method
is designed into algorithm
To improve clarity and understandability of the program flow charts are drawn using the
algorithms.
Coding: The actual program is written in the required programming language with the help of
information depicted in flow charts and algorithms.
Error Handling
As such, C programming does not provide direct support for error handling but being a system
programming language, it provides you access at lower level in the form of return values. Most
of the C or even Unix function calls return -1 or NULL in case of any error and set an error code
errno. It is set as a global variable and indicates an error occurred during any function call. You
can find various error codes defined in <error.h> header file.
STRUCTURED PROGRAMMING BY LARRY BETT
So a C programmer can check the returned values and can take appropriate action depending on
the return value. It is a good practice, to set errno to 0 at the time of initializing a program. A
value of 0 indicates that there is no error in the program.
● The perror() function displays the string you pass to it, followed by a colon, a space,
and then the textual representation of the current errno value.
● The strerror() function, which returns a pointer to the textual representation of the
current errno value.
Let's try to simulate an error condition and try to open a file which does not exist. Here I'm using
both the functions to show the usage, but you can use one or more ways of printing your errors.
Second important point to note is that you should use stderr file stream to output all the errors.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main () {
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL) {
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
}
else {
fclose (pf);
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory
STRUCTURED PROGRAMMING BY LARRY BETT
The code below fixes this by checking if the divisor is zero before dividing −
#include <stdio.h>
#include <stdlib.h>
main() {
exit(0);
}
When the above code is compiled and executed, it produces the following result −
If you have an error condition in your program and you are coming out then you should exit with
a status EXIT_FAILURE which is defined as -1. So let's write above program as follows −
#include <stdio.h>
#include <stdlib.h>
main() {
if( divisor == 0) {
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
When the above code is compiled and executed, it produces the following result −
Value of quotient: 4
STRUCTURED PROGRAMMING BY LARRY BETT
Sequence structure
Sequence structure control structure and its flow of execution is represented in the flow charts
given below.
Execution of instructions flow in order from the first to the last in a linear manner
Selection/Decision Structure
Decision making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Show below is the general form of a typical decision making structure found in most of the
programming languages −
STRUCTURED PROGRAMMING BY LARRY BETT
C programming language assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value.
if statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
The syntax of an 'if' statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will
be executed. If the Boolean expression evaluates to false, then the first set of code after the end
of the 'if' statement (after the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is either
zero or null, then it is assumed as false value.
STRUCTURED PROGRAMMING BY LARRY BETT
Flow Diagram
Example
#include <stdio.h>
int main () {
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
STRUCTURED PROGRAMMING BY LARRY BETT
Syntax
The syntax of an if...else statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
else {
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the
else block will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value.
Flow Diagram
Example
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
When using if...else if..else statements, there are few points to keep in mind −
● An if can have zero or one else's and it must come after any else if's.
● An if can have zero to many else if's and they must come before the else.
● Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
The syntax of an if...else if...else statement in C programming language is −
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
}
else {
/* executes when the none of the above condition is true */
}
Example
#include <stdio.h>
int main () {
printf("Value of a is 20\n" );
}
else if( a == 30 ) {
/* if else if condition is true
*/ printf("Value of a is 30\n" );
}
else {
/* if none of the conditions is true */
printf("None of the values is matching\n" );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
nested if statements
It is always legal in C programming to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows −
if( boolean_expression 1) {
You can nest else if...else in the similar way as you have nested if statements.
Example
#include <stdio.h>
int main () {
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for a switch statement in C programming language is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
● The expression used in a switch statement must have an integral or enumerated type,
or be of a class type in which the class has a single conversion function to an integral or
enumerated type.
● You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
● The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
● When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
● When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
STRUCTURED PROGRAMMING BY LARRY BETT
● Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
● A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
Flow Diagram
Example
#include <stdio.h>
int main () {
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
STRUCTURED PROGRAMMING BY LARRY BETT
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
Syntax
The syntax for a nested switch statement is as follows −
switch(ch1) {
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
#include <stdio.h>
int main () {
switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
STRUCTURED PROGRAMMING BY LARRY BETT
case 200:
printf("This is part of inner switch\n", a );
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Loops/Iterations
You may encounter situations, when a block of code needs to be executed several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given
below is the general form of a loop statement in most of the programming languages −
STRUCTURED PROGRAMMING BY LARRY BETT
C programming language provides the following types of loops to handle looping requirements.
While loop
A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.
Syntax
The syntax of a while loop in C programming language is −
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following
the loop.
Flow Diagram
STRUCTURED PROGRAMMING BY LARRY BETT
Here, the key point to note is that a while loop might not execute at all. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is −
for ( init; condition; increment ) {
statement(s);
}
✔ The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long
as a semicolon appears.
STRUCTURED PROGRAMMING BY LARRY BETT
✔ Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the 'for' loop.
✔ After the body of the 'for' loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
✔ The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After
the condition becomes false, the 'for' loop terminates.
Flow Diagram
STRUCTURED PROGRAMMING BY LARRY BETT
Example
#include <stdio.h>
int main () {
int a;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while
loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.
Syntax
do {
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.
STRUCTURED PROGRAMMING BY LARRY BETT
Flow Diagram
Example
#include <stdio.h>
int main () {
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
STRUCTURED PROGRAMMING BY LARRY BETT
Nested loops
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
Syntax
The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment ) {
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a 'for' loop can be inside a 'while' loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Break statement
The break statement in C programming has the following two usages −
If you are using nested loops, the break statement will stop the execution of the innermost loop
and start executing the next line of code after the block.
Syntax
break;
Flow Diagram
Example
#include <stdio.h>
int main () {
}
STRUCTURED PROGRAMMING BY LARRY BETT
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Continue statement
The continue statement in C programming works somewhat like the break statement. Instead of
forcing termination, it forces the next iteration of the loop to take place, skipping any code in
between.
For the for loop, continue statement causes the conditional test and increment portions of the
loop to execute. For the while and do...while loops, continue statement causes the program
control to pass to the conditional tests.
Syntax
continue;
Flow Diagram
STRUCTURED PROGRAMMING BY LARRY BETT
Example
#include <stdio.h>
int main () {
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto statement
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to understand
and hard to modify. Any program that uses a goto can be rewritten to avoid them.
Syntax
goto label;
..
.
STRUCTURED PROGRAMMING BY LARRY BETT
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.
Flow Diagram
Example
#include <stdio.h>
int main () {
/* do loop execution */
LOOP:do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}
}while( a < 20 );
return 0;
}
STRUCTURED PROGRAMMING BY LARRY BETT
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the for(;;)
construct to signify an infinite loop.
an abstract data type (ADT) is a mathematical model for data types where a data type is defined by
its behavior (semantics) from the point of view of a user of the data, specifically in terms of possible
values, possible operations on data of this type, and the behavior of these operations. This contrasts
with data structures, which are concrete representations of data, and are the point of view of an
implementer, not a user. Note: ADTs are a theoretical concept in computer science, used in the
design and analysis of algorithms, data structures, and software systems, and do not correspond to
specific features of computer languages
NON-PRIMITIVE DATATYPES The data types that are derived from primary data types are
known as non-Primitive data types. These data types are used to store group of values.
Structure
Union
STRUCTURED PROGRAMMING BY LARRY BETT
linked list
Stacks
Queue etc
STRUCTURED PROGRAMMING BY LARRY BETT
Algorithm
An algorithm is a finite set of instructions or logic, written in order, to accomplish a certain
predefined task. Algorithm is not the complete code or program, it is just the core logic(solution)
of a problem, which can be expressed either as an informal high level description as pseudocode
or using a flowchart.
An algorithm is said to be efficient and fast, if it takes less time to execute and consumes less
memory space. The performance of an algorithm is measured on the basis of following
properties :
1. Time Complexity
2. Space Complexity
Space Complexity
Its the amount of memory space required by the algorithm, during the course of its execution.
Space complexity must be taken seriously for multi-user systems and in situations where limited
memory is available.
● Instruction Space : Its the space required to store the executable version of the
program. This space is fixed, but varies depending upon the number of lines of code
in the program.
● Data Space : Its the space required to store all the constants and variables value.
● Environment Space : Its the space required to store the environment information
needed to resume the suspended function.
STRUCTURED PROGRAMMING BY LARRY BETT
Time Complexity
Time Complexity is a way to represent the amount of time needed by the program to run to
completion. We will study this in details in our section.
Time Complexity is most commonly estimated by counting the number of elementary functions
performed by the algorithm. And since the algorithm's performance may vary with different
types of input data, hence for an algorithm we usually use the worst-case Time complexity of
an algorithm because that is the maximum time taken for any input size.
Now the most common metric for calculating time complexity is Big O notation. This removes
all constant factors so that the running time can be estimated in relation to N, as N approaches
infinity. In general you can think of it like this :
statement;
Above we have a single statement. Its Time Complexity will be Constant. The running time of
the statement will not change in relation to N.
The time complexity for the above algorithm will be Linear. The running time of the loop is
directly proportional to N. When N doubles, so does the running time.
This time, the time complexity for the above code will be Quadratic. The running time of the
two loops is proportional to the square of N. When N doubles, the running time increases by N *
N.
STRUCTURED PROGRAMMING BY LARRY BETT
This is an algorithm to break a set of numbers into halves, to search a particular field(we will
study this in detail later). Now, this algorithm will have a Logarithmic Time Complexity. The
running time of the algorithm is proportional to the number of times N can be divided by 2(N is
high-low here). This is because the algorithm divides the working area in half with each
iteration.
Taking the previous algorithm forward, above we have a small logic of Quick Sort(we will study
this in detail later). Now in Quick Sort, we divide the list into halves every time, but we repeat
the iteration N times(where N is the size of list). Hence time complexity will be N*log( N ). The
running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm
is a combination of linear and logarithmic.
NOTE : In general, doing something with every item in one dimension is linear, doing
something with every item in two dimensions is quadratic, and dividing the working area in half
is logarithmic.
O(expression) is the set of functions that grow slower than or at the same rate as expression.
Omega(expression) is the set of functions that grow faster than or at the same rate as expression.
STRUCTURED PROGRAMMING BY LARRY BETT
Theta(expression) consist of all the functions that lie in both O(expression) and
Omega(expression).
Since this polynomial grows at the same rate as n^2, then you could say that the function f lies in
the set Theta(n^2). (It also lies in the sets O(n^2) and Omega(n^2) for the same reason.)
The simplest explanation is, because Theta denotes the same as the expression. Hence, as f(n)
grows by a factor of n^2, the time complexity can be best represented as Theta(n^2).
Array
C Array is a collection of variables belongings to the same data type. You can store group of
data of same data type in an array.
Types of C arrays:
1. One-dimensional array
2. Multi-dimensional array
1. Two dimensional array
2. Three dimensional array, four dimensional array etc…
STRUCTURED PROGRAMMING BY LARRY BETT
Array
Array initialization Accessing
declaratio array
n
Syntax:
data_type arr_name
data_ type
[arr_size]=(value1, arr_name[index];
arr_name
value2, value3,….);
[arr_size];
char str*10+=,‘H’,‘a’,‘i’-;
( or)char str*0+ = str[0]; /*H is accessed*/str[1]; /*a is accessed*/str[2]; /* i is
char str[10];
‘H’;char str*1+ = ‘a’; accessed*/
#include<stdio.h>int main(){
int i;
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
STRUCTURED PROGRAMMING BY LARRY BETT
for (i=0;i<5;i++)
Output:
#include<stdio.h>int main(){
int i,j;
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
for (j=0;j<2;j++)
// Accessing variables
Output:
STRUCTURED PROGRAMMING BY LARRY BETT
Stack
Stack is a specialized data storage structure (Abstract data type). Unlike, arrays access of
elements in a stack is restricted. It has two main functions push and pop. Insertion in a stack is
done using push function and removal from a stack is done using pop function. Stack allows
access to only the last element inserted hence, an item can be inserted or removed from the
stack from one end called the top of the stack. It is therefore, also called Last-In-First-Out
(LIFO) list. Stack has three properties: capacity stands for the maximum number of elements
stack can hold, size stands for the current size of the stack and elements is the array of
elements.
STRUCTURED PROGRAMMING BY LARRY BETT
Algorithm:
Stack structure is defined with fields capacity, size and *elements (pointer to the array of
elements).
2. push function - This function takes the pointer to the top of the stack S and the item
(element) to be inserted as arguments. Check for the emptiness of stack
3. pop function - This function takes the pointer to the top of the stack S as an argument.
4. top function – This function takes the pointer to the top of the stack S as an argument
and returns the topmost element of the stack S.
Properties of stacks:
Array-based implementation – It is simple and efficient but the maximum size of the stack is
fixed.
Singly Linked List-based implementation – It’s complicated but there is no limit on the stack
size, it is subjected to the available memory.
{
printf("Stack is Empty\n");
return;
}
/* Removing an element is equivalent to reducing its size by one */
else
{
S->size--;
}
return;
}
int top(Stack *S)
{
if(S->size==0)
{
printf("Stack is Empty\n");
exit(0);
}
/* Return the topmost element */
return S->elements[S->size-1];
}
void push(Stack *S,int element)
{
/* If the stack is full, we cannot push an element into it as there
is no space for it.*/
if(S->size == S->capacity)
{
} printf("Stack is Full\n");
else
{
/* Push an element on
one*/
} the top of it and
return;
increase its size by
}
S->elements[S->size++]
= element;
int main()
{
Stack *S = createStack(5);
push(S,7);
push(S,5);
push(S,21);
push(S,-1);
printf("Top element is %d\n",top(S));
pop(S);
printf("Top element is %d\n",top(S));
pop(S);
printf("Top element is %d\n",top(S));
pop(S);
printf("Top element is %d\n",top(S));
}
STRUCTURED PROGRAMMING BY LARRY BETT
Queue
Queue is a specialized data storage structure (Abstract data type). Unlike, arrays
access of elements in a Queue is restricted. It has two main operations enqueue
and dequeue.
Insertion in a queue is done using enqueue function and removal from a queue is done
using dequeue function. An item can be inserted at the end (‘rear’) of the queue and
removed from the front (‘front’) of the queue. It is therefore, also called First-In-First-Out
(FIFO) list. Queue has five properties - capacity stands for the maximum number of
elements Queue can hold, size stands for the current size of the Queue, elements is the
array of elements, front is the index of first element (the index at which we remove the
element) and rear is the index of last element (the index at which we insert the element).
STRUCTURED PROGRAMMING BY LARRY BETT
Algorithm:
Queue structure is defined with fields capacity, size, *elements (pointer to the
array of elements), front and rear.
2. enqueue function - This function takes the pointer to the top of the
queue Q and the item (element) to be inserted as arguments. Check for the
emptiness of queue
3. dequeue function - This function takes the pointer to the top of the
stack S as an argument and will then dequeue an element.
4. front function – This function takes the pointer to the top of the
queue Q as an argument and returns the front element of the queue Q.
STRUCTURED PROGRAMMING BY LARRY BETT
Properties:
1. Each function runs in O(1) time.
2. It has two basic implementations
Array-based implementation – It’s simple and efficient but the maximum size of
the queue is fixed.
n a
t r
r ;
e int *elements;
/* crateQueue function takes argument the maximum number of elements the
Queue can hold, creates
a Queue according to it and returns a pointer to the Queue. */
Queue * createQueue(int maxElements)
{
/* Create a Queue */
Queue *Q;
Q = (Queue *)malloc(sizeof(Queue));
/* Initialise its properties */
Q->elements = (int *)malloc(sizeof(int)*maxElements);
Q->size = 0;
Q->capacity = maxElements;
Q->front = 0;
Q->rear = -1;
/* Return the pointer */
return Q;
}
void Dequeue(Queue *Q)
{
/* If Queue size is zero then it is empty. So we cannot pop
*/ if(Q->size==0)
{
printf("Queue is Empty\n");
STRUCTURED PROGRAMMING BY LARRY BETT
return;
}
/* Removing an element is equivalent to incrementing index of front
by one */
else
{
Q->size--;
Q->front++
;
/* As we fill elements in circular fashion
*/ if(Q->front==Q->capacity)
{
Q->front=0;
}
}
return;
}
int front(Queue *Q)
{
if(Q->size==0)
{
printf("Queue is Empty\n");
exit(0);
}
/* Return the element which is at the front*/
return Q->elements[Q->front];
}
void Enqueue(Queue *Q,int element)
{
/* If the Queue is full, we cannot push an element into it as there
is no space for it.*/
if(Q->size == Q->capacity)
{
printf("Queue is Full\n");
}
else
{
Q->size++;
Q->rear = Q->rear + 1;
/* As we fill the
queue in circular
fashion */
if(Q->rear ==
Q->capacity)
{
Q->rear = 0;
}
/* Insert the
element in its
} rear side */
return; Q->elements[Q->rea
} r] = element;
int main()
{
Queue *Q = createQueue(5);
Enqueue(Q,1);
Enqueue(Q,2);
Enqueue(Q,3);
Enqueue(Q,4);
STRUCTURED PROGRAMMING BY LARRY BETT
Dequeue(Q);
Enqueue(Q,6);
printf("Front element is %d\n",front(Q));
}
Linked Lists
A linked list is a sequence of data structures, which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to
another link. Linked list is the second most-used data structure after array. Following are the
important terms to understand the concept of Linked List.
● Link − Each link of a linked list can store a data called an element.
● Next − Each link of a linked list contains a link to the next link called Next.
● LinkedList − A Linked List contains the connection link to the first link called First.
As per the above illustration, following are the important points to be considered.
Basic Operations
Following are the basic operations supported by a list.
Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with
diagrams here. First, create a node using the same structure and find the location where it has to
be inserted.
Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C (RightNode).
Then point B.next to C −
Now, the next node at the left should point to the new node.
This will put the new node in the middle of the two. The new list should look like this −
Similar steps should be taken if the node is being inserted at the beginning of the list. While
inserting it at the end, the second last node of the list should point to the new node and the new
node will point to NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation. First,
locate the target node to be removed, by using searching algorithms.
The left (previous) node of the target node now should point to the next node of the target node −
This will remove the link that was pointing to the target node. Now, using the following code, we
will remove what the target node is pointing at.
STRUCTURED PROGRAMMING BY LARRY BETT
We need to use the deleted node. We can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.
Reverse Operation
This operation is a thorough one. We need to make the last node to be pointed by the head node
and reverse the whole linked list.
First, we traverse to the end of the list. It should be pointing to NULL. Now, we shall make it
point to its previous node −
We have to make sure that the last node is not the lost node. So we'll have some temp node,
which looks like the head node pointing to the last node. Now, we shall make all left side nodes
point to their previous nodes one by one.
STRUCTURED PROGRAMMING BY LARRY BETT
Except the node (first node) pointed by the head node, all nodes should point to their
predecessor, making them their new successor. The first node will point to NULL.
We'll make the head node point to the new first node by using the temp node.
● Link − Each link of a linked list can store a data called an element.
● Next − Each link of a linked list contains a link to the next link called Next.
● Prev − Each link of a linked list contains a link to the previous link called Prev.
● LinkedList − A Linked List contains the connection link to the first link called First
and to the last link called Last.
As per the above illustration, following are the important points to be considered.
● Doubly Linked List contains a link element called first and last.
● Each link carries a data field(s) and two link fields called next and prev.
● Each link is linked with its next link using its next link.
● Each link is linked with its previous link using its previous link.
STRUCTURED PROGRAMMING BY LARRY BETT
● The last link carries a link as null to mark the end of the list.
Basic Operations
Following are the basic operations supported by a list.
Insertion Operation
Following code demonstrates the insertion operation at the beginning of a doubly linked list.
Example
//insert link at the first location
void insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()) {
//make it the last link
last = link;
} else {
//update first prev link
head->prev = link;
}
Deletion Operation
Following code demonstrates the deletion operation at the beginning of a doubly linked list.
Example
//delete first item
struct node* deleteFirst() {
head = head->next;
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()) {
//make it the last link
last = link;
} else {
//make link a new last link
last->next = link;
In singly linked list, the next pointer of the last node points to the first node.
In doubly linked list, the next pointer of the last node points to the first node and the previous
pointer of the first node points to the last node making the circular in both directions.
As per the above illustration, following are the important points to be considered.
● The last link's next points to the first link of the list in both cases of singly as well
as doubly linked list.
● The first link's previous points to the last of the list in case of doubly linked list.
Basic Operations
Following are the important operations supported by a circular list.
Insertion Operation
Following code demonstrates the insertion operation in a circular linked list based on single
linked list.
Example
//insert link at the first location
void insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
STRUCTURED PROGRAMMING BY LARRY BETT
link->data= data;
if (isEmpty()) {
head = link;
head->next = head;
} else {
//point it to old first node
link->next = head;
Deletion Operation
Following code demonstrates the deletion operation in a circular linked list based on single
linked list.
//delete first item
struct node * deleteFirst() {
//save reference to first link
struct node *tempLink = head;
if(head->next == head) {
head = NULL;
return tempLink;
}
printf(" ]");
}
STRUCTURED PROGRAMMING BY LARRY BETT
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of edges,
connecting the pairs of vertices. Take a look at the following graph −
V = {a, b, c, d, e}
● Vertex − Each node of the graph is represented as a vertex. In the following example, the
labeled circle represents vertices. Thus, A to G are vertices. We can represent them using
an array as shown in the following image. Here A can be identified by index 0. B can be
identified using index 1 and so on.
● Edge − Edge represents a path between two vertices or a line between two vertices. In
the following example, the lines from A to B, B to C, and so on represents edges. We can
use a two-dimensional array to represent an array as shown in the following image. Here
AB can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on,
keeping other combinations as 0.
● Adjacency − Two node or vertices are adjacent if they are connected to each other
through an edge. In the following example, B is adjacent to A, C is adjacent to B, and
so on.
● Path − Path represents a sequence of edges between the two vertices. In the
following example, ABCD represents a path from A to D.
STRUCTURED PROGRAMMING BY LARRY BETT
Basic Operations
Graph Traversal
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack
to remember to get the next vertex to start a search, when a dead end occurs in any iteration.
STRUCTURED PROGRAMMING BY LARRY BETT
As in the example given above, DFS algorithm traverses from A to B to C to D first then to E,
then to F and lastly to G. It employs the following rules.
● Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a
stack.
● Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up
all the vertices from the stack, which do not have adjacent vertices.)
● Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
As C does not have any unvisited adjacent node so we keep popping the stack until we find a
node that has an unvisited adjacent node. In this case, there's none and we keep popping until the
stack is empty.
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a
queue to remember to get the next vertex to start a search, when a dead end occurs in any
iteration.
As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and
G lastly to D. It employs the following rules.
● Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a
queue.
● Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
● Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
STRUCTURED PROGRAMMING BY LARRY BETT
At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm we keep
on dequeuing in order to get all unvisited nodes. When the queue gets emptied, the program is
over.
Tree
Tree represents the nodes connected by edges. We will discuss binary tree or binary search tree
specifically.
Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special
condition that each node can have a maximum of two children. A binary tree has the benefits of
both an ordered array and a linked list as search is as quick as in a sorted array and insertion or
deletion operation are as fast as in linked list.
Important Terms
Following are the important terms with respect to tree.
● Path − Path refers to the sequence of nodes along the edges of a tree.
STRUCTURED PROGRAMMING BY LARRY BETT
● Root − The node at the top of the tree is called root. There is only one root per tree
and one path from the root node to any node.
● Parent − Any node except the root node has one edge upward to a node called parent.
● Child − The node below a given node connected by its edge downward is called its
child node.
● Leaf − The node which does not have any child node is called the leaf node.
● Subtree − Subtree represents the descendants of a node.
● Visiting − Visiting refers to checking the value of a node when control is on the node.
● Traversing − Traversing means passing through nodes in a specific order.
● Levels − Level of a node represents the generation of a node. If the root node is at
level 0, then its next child node is at level 1, its grandchild is at level 2, and so on.
● keys − Key represents a value of a node based on which a search operation is to be
carried out for a node.
We're going to implement tree using node object and connecting them through references.
Tree Node
The code to write a tree node would be similar to what is given below. It has a data part and
references to its left and right child nodes.
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
We shall learn creating (inserting into) a tree structure and searching a data item in a tree in this
chapter. We shall learn about tree traversing methods in the coming chapter.
Insert Operation
The very first insertion creates the tree. Afterwards, whenever an element is to be inserted, first
locate its proper location. Start searching from the root node, then if the data is less than the key
value, search for the empty location in the left subtree and insert the data. Otherwise, search for
the empty location in the right subtree and insert the data.
Algorithm
If root is NULL
then create root node
return
endwhile
insert data
end If
Implementation
The implementation of insert function should look like this −
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
while(1) {
parent = current;
Search Operation
Whenever an element is to be searched, start searching from the root node, then if the data is less
than the key value, search for the element in the left subtree. Otherwise, search for the element
in the right subtree. Follow the same algorithm for each node.
Algorithm
If root.data is equal to search.data
return root
else
while data not found
If data found
return node
endwhile
end if
STRUCTURED PROGRAMMING BY LARRY BETT
while(current->data != data) {
if(current != NULL)
printf("%d ",current->data);
//go to left tree
if(current->data > data) {
current = current->leftChild;
}
//else go to right tree
else {
current = current->rightChild;
}
//not found
if(current == NULL) {
return NULL;
}
return current;
}
}
Tree Traversal
Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all
nodes are connected via edges (links) we always start from the root (head) node. That is, we
cannot randomly access a node in a tree. There are three ways which we use to traverse a tree −
● In-order Traversal
● Pre-order Traversal
● Post-order Traversal
Generally, we traverse a tree to search or locate a given item or key in the tree or to print all the
values it contains.
In-order Traversal
In this traversal method, the left subtree is visited first, then the root and later the right sub-tree.
We should always remember that every node may represent a subtree itself.
If a binary tree is traversed in-order, the output will produce sorted key values in an ascending
order.
STRUCTURED PROGRAMMING BY LARRY BETT
We start from A, and following in-order traversal, we move to its left subtree B. B is also
traversed in-order. The process goes on until all the nodes are visited. The output of inorder
traversal of this tree will be −
D→B→E→A→F→C→G
Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.
Pre-order Traversal
In this traversal method, the root node is visited first, then the left subtree and finally the right
subtree.
STRUCTURED PROGRAMMING BY LARRY BETT
We start from A, and following pre-order traversal, we first visit A itself and then move to its left
subtree B. B is also traversed pre-order. The process goes on until all the nodes are visited. The
output of pre-order traversal of this tree will be −
A→B→D→E→C→F→G
Algorithm
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.
Post-order Traversal
In this traversal method, the root node is visited last, hence the name. First we traverse the left
subtree, then the right subtree and finally the root node.
STRUCTURED PROGRAMMING BY LARRY BETT
We start from A, and following pre-order traversal, we first visit the left subtree B. B is also
traversed post-order. The process goes on until all the nodes are visited. The output of post-order
traversal of this tree will be −
D→E→B→F→G→C→A
Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.
Types of trees
We have three basic types as listed below
● The left sub-tree of a node has a key less than or equal to its parent node's key.
● The right sub-tree of a node has a key greater than to its parent node's key.
STRUCTURED PROGRAMMING BY LARRY BETT
Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and
can be defined as −
Representation
BST is a collection of nodes arranged in a way where they maintain BST properties. Each node
has a key and an associated value. While searching, the desired key is compared to the keys in
BST and if found, the associated value is retrieved.
We observe that the root node key (27) has all less-valued keys on the left sub-tree and the
higher valued keys on the right sub-tree.
Basic Operations
Following are the basic operations of a tree −
Node
Define a node having some data, references to its left and right child nodes.
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
Search Operation
STRUCTURED PROGRAMMING BY LARRY BETT
Whenever an element is to be searched, start searching from the root node. Then if the data is
less than the key value, search for the element in the left subtree. Otherwise, search for the
element in the right subtree. Follow the same algorithm for each node.
Algorithm
if(current != NULL) {
printf("%d ",current->data);
//not found
if(current == NULL){
return NULL;
}
}
}
return current;
}
Insert Operation
Whenever an element is to be inserted, first locate its proper location. Start searching from the
root node, then if the data is less than the key value, search for the empty location in the left
subtree and insert the data. Otherwise, search for the empty location in the right subtree and
insert the data.
Algorithm
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
while(1) {
parent = current;
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
}//go to right of the tree
else {
current = current->rightChild;
AVL Trees
What if the input to binary search tree comes in a sorted (ascending or descending) manner? It
will then look like this −
STRUCTURED PROGRAMMING BY LARRY BETT
It is observed that BST's worst-case performance is closest to linear search algorithms, that is
Ο(n). In real-time data, we cannot predict data pattern and their frequencies. So, a need arises to
balance out the existing BST.
Named after their inventor Adelson, Velski & Landis, AVL trees are height balancing binary
search tree. AVL tree checks the height of the left and the right sub-trees and assures that the
difference is not more than 1. This difference is called the Balance Factor.
Here we see that the first tree is balanced and the next two trees are not balanced −
In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the
difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it is
0, and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1.
If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using
some rotation techniques.
AVL Rotations
To balance itself, an AVL tree may perform the following four kinds of rotations −
● Left rotation
● Right rotation
● Left-Right rotation
● Right-Left rotation
The first two rotations are single rotations and the next two rotations are double rotations. To
have an unbalanced tree, we at least need a tree of height 2. With this simple tree, let's
understand them one by one.
Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree of the right subtree,
then we perform a single left rotation −
STRUCTURED PROGRAMMING BY LARRY BETT
In our example, node A has become unbalanced as a node is inserted in the right subtree of A's
right subtree. We perform the left rotation by making A the left-subtree of B.
Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree. The
tree then needs a right rotation.
As depicted, the unbalanced node becomes the right child of its left child by performing a right
rotation.
Left-Right Rotation
Double rotations are slightly complex version of already explained versions of rotations. To
understand them better, we should take note of each action performed while rotation. Let's first
check how to perform Left-Right rotation. A left-right rotation is a combination of left rotation
followed by right rotation.
STRUCTURED PROGRAMMING BY LARRY BETT
State Action
A node has been inserted into the right subtree of the left
subtree. This makes C an unbalanced node. These scenarios
cause AVL tree to perform left-right rotation.
We shall now right-rotate the tree, making B the new root node
of this subtree. C now becomes the right subtree of its own left
subtree.
Right-Left Rotation
The second type of double rotation is Right-Left Rotation. It is a combination of right rotation
followed by left rotation.
State Action
A node has been inserted into the left subtree of the right
subtree. This makes A, an unbalanced node with balance factor
2.
Spanning Tree
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. Hence, a spanning tree does not have cycles and it cannot be
disconnected..
By this definition, we can draw a conclusion that every connected and undirected Graph G has at
least one spanning tree. A disconnected graph does not have any spanning tree, as it cannot be
spanned to all its vertices.
STRUCTURED PROGRAMMING BY LARRY BETT
We found three spanning trees off one complete graph. A complete undirected graph can have
maximum nn-2 number of spanning trees, where n is the number of nodes. In the above addressed
example, 33−2 = 3 spanning trees are possible.
Thus, we can conclude that spanning trees are a subset of connected Graph G and disconnected
graphs do not have spanning tree.
STRUCTURED PROGRAMMING BY LARRY BETT
Let us understand this through a small example. Consider, city network as a huge graph and now
plans to deploy telephone lines in such a way that in minimum lines we can connect to all city
nodes. This is where the spanning tree comes into picture.
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap. Based on
this criteria, a heap can be of two types −
For Input → 35 33 42 10 14 19 27 44 26 31
Min-Heap − Where the value of the root node is less than or equal to either of its children.
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
STRUCTURED PROGRAMMING BY LARRY BETT
Both trees are constructed using the same input and order of arrival.
We are going to derive an algorithm for max heap by inserting one element at a time. At any
point of time, heap must maintain its property. While insertion, we also assume that we are
inserting a node in an already heapified tree.
Note − In Min Heap construction algorithm, we expect the value of the parent node to be less
than that of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same input
sample that we used earlier.
STRUCTURED PROGRAMMING BY LARRY BETT
1. Searching
A common problem encountered in programming is the need to search an array in order
to find the location of the desired value. Suppose you are looking for a student with ID
995203 in a list of ID’s, then you search for this ID in the list from the beginning till you
find it or reach the end of the array and the ID is not there.
The searching algorithms we will use are the linear search and the binary search.
Linear search:
This is a general search strategy. Here, we search for the element from the beginning of
the array. If we find the target element in the array, we stop searching and return the
position of the element in the array; otherwise we continue till the end of the array. If we
reach the end of the array and did not find the target, the search returns –1 as an
indication that it is not in the array.
The following figure is an example of Linear search:
Suppose we wish to write a method that takes in a one-dimensional array and some value x, and
returns either the position (i.e., "index") of x in the array, or -1 if x does not appear in the array.
One option would be to use a linear search. In a linear search, we compare x (which we call the
"key") with each element in the array list, starting at one end and progressing to the other.
Graphically, we can imagine the following comparisons being made:
STRUCTURED PROGRAMMING BY LARRY BETT
int i;
if(key == a[i])
return i ;
return -1;
Binary search:
If the array we are searching is sorted and the sorting order is known, then we can use
a better strategy than linear search to look for the target element. The binary search
makes use of the fact that the elements are ordered and does not scan the whole array.
The steps of binary search, for an array that is sorted in increasing order, are:
1. if the middle element m is equal to the target, then return its position and we are
done.
2. else:
a. if the target < middle element, then search the first half of the array and
repeat step 1.
b. if the target > middle, then search second half of the array and repeat step1.
c. if the array is exhausted, then the target is not in the array and the search
returns -1.
In the implementation, we use two variables (first and last) that indicate the start
and the end of the sub-array being searched. Through first and last we can get
the middle element and specify the boundary of the array for the next pass if we do not
find the target in the current pass.
int middle;
if(last<first)
middle=(first+last)/2;
if(key==x[middle])
return middle;
else if (key<x[middle])
else
2. Sorting
Another interesting problem in programming is to sort the elements of an array in
increasing or decreasing order. The use of sorted arrays is very obvious. Having sorted
records makes it easier to locate a particular element. Also if you want the output of
these records (for example students ID’s along with their grades) to be displayed on
screen sorted, then using a sort strategy becomes necessary.
Sorting in general refers to various methods of arranging or ordering things based on criteria‘s
(numerical, chronological, alphabetical, hierarchical etc.). In Computer Science, due to obvious
reasons, Sorting (of data) is of immense importance and is one of the most extensively
researched subjects. It is one of the most fundamental algorithmic problems. So much so that it is
also fundamental to many other fundamental algorithmic problems such as search algorithms,
merge algorithms etc. It is estimated that around 25% of all CPU cycles are used to sort data.
There are many approaches to sorting data and each has its own merits and demerits. This article
discusses some of the common sorting algorithms.
In the discussion, we will discuss one sorting algorithm: Selection Sort.
Selection Sort:
Selection sort is a simple straightforward algorithm to sort an array of numbers and it
works as follows. First, we find the minimum element and store it in A[0]. Next, we find
the minimum of the remaining elements and store it in A[1]. We continue this way until
the second largest element is stored in A[size – 1]. The following figure explains the
process of selection sort:
STRUCTURED PROGRAMMING BY LARRY BETT
int k,j,minpos,temp;
minpos = j;
temp = x[minpos];
x[minpos] = x[k];
x[k] = temp;
}
STRUCTURED PROGRAMMING BY LARRY BETT
Bubble Sort
Bubble Sort is probably one of the oldest, most easiest, straight-forward, inefficient sorting
algorithms. It is the algorithm introduced as a sorting routine in most introductory courses on
Algorithms. Bubble Sort works by comparing each element of the list with the element next to it
and swapping them if required. With each pass, the largest of the list is "bubbled" to the end of
the list whereas the smaller values sink to the bottom. It is similar to selection sort although not
as straight forward. Instead of "selecting" maximum values, they are bubbled to a part of the list.
An implementation in C.
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
}
}
A single, complete "bubble step" is the step in which a maximum element is bubbled to its
correct position. This is handled by the inner for loop.
Examine the following table. (Note that each pass represents the status of the array after the
completion of the inner for loop, except for pass 0, which represents the array as it was passed
to the function for sorting)
8 6 10 3 1 2 5 4 } pass 0
6 8 3 1 2 5 4 10 } pass 1
6 3 1 2 5 4 8 10 } pass 2
3 1 2 5 4 6 8 10 } pass 3
1 2 3 4 5 6 8 10 } pass 4
1 2 3 4 5 6 8 10 } pass 5
1 2 3 4 5 6 8 10 } pass 6
1 2 3 4 5 6 8 10 } pass 7
The above tabulated clearly depicts how each bubble sort works. Note that each pass results in
one number being bubbled to the end of the list.
Selection Sort
The idea of Selection Sort is rather simple. It basically determines the minimum (or maximum)
of the list and swaps it with the element at the index where its supposed to be. The process is
repeated such that the nth minimum (or maximum) element is swapped with the element at the
n- 1th index of the list. The below is an implementation of the algorithm in C.
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
STRUCTURED PROGRAMMING BY LARRY BETT
Consider the following table. (Note that each pass represents the status of the array after the
completion of the inner for loop, except for pass 0, which represents the array as it was passed
to the function for sorting)
8 6 10 3 1 2 5 4 } pass 0
1 6 10 3 8 2 5 4 } pass 1
1 2 10 3 8 6 5 4 } pass 2
1 2 3 10 8 6 5 4 } pass 3
1 2 3 4 8 6 5 10 } pass 4
1 2 3 4 5 6 8 10 } pass 5
1 2 3 4 5 6 8 10 } pass 6
1 2 3 4 5 6 8 10 } pass 7
At pass 0, the list is unordered. Following that is pass 1, in which the minimum element 1 is
selected and swapped with the element 8, at the lowest index 0. In pass 2, however, only the
sublist is considered, excluding the element 1. So element 2, is swapped with element 6, in the
2nd lowest index position. This process continues till the sub list is narrowed down to just one
element at the highest index (which is its right position).
Insertion Sort
The Insertion Sort algorithm is a commonly used algorithm. Even if you haven't been a
programmer or a student of computer science, you may have used this algorithm. Try recalling
how you sort a deck of cards. You start from the begining, traverse through the cards and as you
find cards misplaced by precedence you remove them and insert them back into the right
position. Eventually what you have is a sorted deck of cards. The same idea is applied in the
Insertion Sort algorithm. The following is an implementation in C.
a[j] = index;
}
}
STRUCTURED PROGRAMMING BY LARRY BETT
Examine the following table. (Note that each pass represents the status of the array after the
completion of the inner for loop, except for pass 0, which represents the array as it was passed
to the function for sorting)
8 6 10 3 1 2 5 4 } pass 0
6 8 10 3 1 2 5 4 } pass 1
6 8 10 3 1 2 5 4 } pass 2
3 6 8 10 1 2 5 4 } pass 3
1 3 6 8 10 2 5 4 } pass 4
1 2 3 6 8 10 5 4 } pass 5
1 2 3 5 6 8 10 4 } pass 6
1 2 3 4 5 6 8 10 } pass 7
The pass 0 is only to show the state of the unsorted array before it is given to the loop for
sorting. Now try out the deck-of-cards-sorting algorithm with this list and see if it matches with
the tabulated data. For example, you start from 8 and the next card you see is 6. Hence you
remove 6 from its current position and "insert" it back to the top. That constitued pass 1. Repeat
the same process and you'll do the same thing for 3 which is inserted at the top. Observe in pass
5 that 2 is moved from position 5 to position 1 since its < (6,8,10) but > 1. As you carry on till
you reach the end of the list you'll find that the list has been sorted. It didn't take a course to tell
you how to sort a deck of cards, did it; you prolly figured it out on your own. Amazed at the
computer scientist in you ? ;)
Heap Sort
Heap sort algorithm, as the name suggests, is based on the concept of heaps. It begins by
constructing a special type of binary tree, called heap, out of the set of data which is to be sorted.
Note:
● A Heap by definition is a special type of binary tree in which each node is greater
than any of its descendants. It is a complete binary tree.
● A semi-heap is a binary tree in which all the nodes except the root possess the
heap property.
● If N be the number of a node, then its left child is 2*N and the right child 2*N+1.
The root node of a Heap, by definition, is the maximum of all the elements in the set of
data,
constituting the binary tree. Hence the sorting process basically consists of extracting the root
node and reheaping the remaining set of elements to obtain the next largest element till there are
no more elements left to heap. Elemetary implementations usually employ two arrays, one for
the heap and the other to store the sorted data. But it is possible to use the same array to heap the
unordered list and compile the sorted list. This is usually done by swapping the root of the heap
with the end of the array and then excluding that element from any subsequent reheaping.
Significance of a semi-heap - A Semi-Heap as mentioned above is a Heap except that the root
does not possess the property of a heap node. This type of a heap is significant in the discussion
of Heap Sorting, since after each "Heaping" of the set of data, the root is extracted and replaced
by an element from the list. This leaves us with a Semi-Heap. Reheaping a Semi-Heap is
STRUCTURED PROGRAMMING BY LARRY BETT
particularily easy since all other nodes have already been heaped and only the root node has to be
STRUCTURED PROGRAMMING BY LARRY BETT
shifted downwards to its right position. The following C function takes care of reheaping a set of
data or a part of it.
}
STRUCTURED PROGRAMMING BY LARRY BETT
root = maxchild;
}
}
In the above function, both root and bottom are indices into the array. Note that, theoretically
speaking, we generally express the indices of the nodes starting from 1 through size of the array.
But in C, we know that array indexing begins at 0; and so the left child is
child = root * 2 + 1
/* so, for eg., if root = 0, child = 1 (not 0) */
In the function, what basically happens is that, starting from root each loop performs a check for
the heap property of root and does whatever necessary to make it conform to it. If it does already
conform to it, the loop breaks and the function returns to caller. Note that the function assumes
that the tree constituted by the root and all its descendants is a Semi-Heap.
STRUCTURED PROGRAMMING BY LARRY BETT
Now that we have a downheaper, what we need is the actual sorting routine.
void heapsort(int a[], int array_size)
{
int i;
for (i = (array_size/2 -1); i >= 0; --i)
{
downHeap(a, i, array_size-1);
}
Note that, before the actual sorting of data takes place, the list is heaped in the for loop starting
from the mid element (which is the parent of the right most leaf of the tree) of the list.
Following this is the loop which actually performs the extraction of the root and creating the
sorted list. Notice the swapping of the ith element with the root followed by a reheaping of the
list.
The following are some snapshots of the array during the sorting process. The unodered list
- 8 6 10 3 1 2 5 4
After the initial heaping done by the first for loop.
10 6 8 4 1 2 5 3
STRUCTURED PROGRAMMING BY LARRY BETT
Heap sort is one of the preferred sorting algorithms when the number of data items is large. Its
efficiency in general is considered to be poorer than quick sort and merge sort.
Lab Work:
Question 1:
srand(time(NULL));
Ask the user to enter a target value (between 0 and 30) to check if
it is present in the array by using linear search. If present your
program should display its position, otherwise print a message saying
that the value is not in the array.
Question 2:
The binary search function shown above is recursive; rewrite the same
function using a loop instead of recursion. To test your iterative
binary search function repeat question 1 by using binary search
instead of linear search.
Question 3:
Fundamental of Subprograms
Subprograms include the following characteristics:
Basic Definitions
A subprogram definition describes the interface to and the actions of the
subprogram abstraction
A subprogram call is the explicit request that the subprogram be executed.
A subprogram is active if after having been called, it has begun execution but
has not yet completed that execution.
Two fundamental kinds of subprograms are procedures and functions.
A subprogram header, which is the first line of the definition, serves several
purposes. It specifies that the following syntactic unit is a subprogram definition. And it
provides the name for the subprogram. And, it may optionally specify list of
parameters.
The parameter profile of a subprogram is the number, order and types of its formal
parameters.
The protocol of a subprogram is its parameter profile plus, if it is a function, its return
types
Subprograms declarations are common in C programs where they are called prototypes.
STRUCTURED PROGRAMMING BY LARRY BETT
Parameters
Subprograms usually describe computations.
There are 2 ways that a subprogram can gain access to the data that is to process:
through direct access to nonlocal variables or through parameter passing.
Data passed through parameters are accessed through names that are local to the
subprogram. Parameter passing is more flexible than direct access to nonlocal
variables
The parameters in the subprogram header are called formal parameters
Subprograms call statements must include the name of the subprogram and a list of
parameters to be bound to the formal parameters of the subprogram. These parameters
are called actual parameters
STRUCTURED PROGRAMMING BY LARRY BETT
An overloaded subprogram is one that has the same name as another subprogram in
the same referencing environment.
A generic subprogram is one whose computation can be don on data of different
types with different calls
Another advantage is that some of the storage for local variables of all
subprograms can be shared
STRUCTURED PROGRAMMING BY LARRY BETT
o Cost of time required to allocate, initialize and de-allocate for each activation
o Accesses of stack dynamic local variables must be indirect, where accesses to
static can be direct
o Stack dynamic local variables, the subprograms cannot retain data values
of local variables between calls.
The primary advantage of static local variables is that they are very efficient
because of no indirection
STRUCTURED PROGRAMMING BY LARRY BETT
Parameter-Passing Methods
Parameter-passing methods are the ways in which parameters are transmitted to and /
or from called programs
Formal parameters are characterized by one of three semantics models:
Pass by Value
When a parameter is passed by value, the value of the actual parameter is used to
initialize the corresponding formal parameter, which then acts as a local variable in the
subprogram – this implements in-mode semantics.
additional storage is required for the formal parameter, either in the called subprogram or
in some area outside both the caller and the called subprogram.
STRUCTURED PROGRAMMING BY LARRY BETT
Pass by Result
Pass by result is an implementation model for out-mode parameters
When a parameter is passed by result, no value is transmitted to the subprogram
One problem with the pass by result is that there can be an actual parameter collision
such as the one created with the call
sub(p1, p2)
sub here assumes 2 formal parameters with different names, then whichever of
the 2 is assigned to their corresponding actual parameter last becomes the
value of p1.
The order in which the actual parameters are assigned determines their value.
Another problem with pass by result is that the implementer may be able to choose
between 2 different times to evaluate the addresses of the actual parameters: at the
time of the call or at the time of the return.
Pass by Reference
Pass by reference is a second implementation of in-out mode parameters
Rather than transmitting data values back and forth, as in pass by value result, the
pass by reference method transmits an access path, usually just an address, to the
called subprogram. This provides the access path to the cell storing the actual
parameter.
The advantage of pass by reference is efficiency in both time and space.
The disadvantages are:
o Access to formal parameters is slow
o Inadvertent and erroneous changes may be made to the actual parameter
o Aliases ca be created.
Pass by Name
Pass by name is an in-out mode parameter transmission method that does not
correspond to a single implementation model.
When parameters are passed by name, the actual parameter is textually substituted
for the corresponding formal parameter in all its occurrences in the subprogram.
STRUCTURED PROGRAMMING BY LARRY BETT
Global variables are those that are visible in all program units.
STRUCTURED PROGRAMMING BY LARRY BETT
Introduction to function
A large C program is divided into basic building blocks called C function. C function contains
set of instructions enclosed by ―{ }‖ which performs specific operation in a C
program. Actually, Collection of these functions creates a C program.
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
float m, n ;
STRUCTURED PROGRAMMING BY LARRY BETT
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
1. Call by value
2. Call by reference
1. Call by value:
● In call by value method, the value of the variable is passed to the function as
parameter.
● The value of the actual parameter can not be modified by formal parameter.
● Different Memory is allocated for both actual and formal parameters. Because,
value of actual parameter is copied to formal parameter.
Note:
● Actual parameter – This is the argument which is used in function call.
● Formal parameter – This is the argument which is used in function definition
● These values are copied to formal parameters “a” and “b” in swap function and
used.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
STRUCTURED PROGRAMMING BY LARRY BETT
Output:
2. Call by reference:
● In call by reference method, the address of the variable is passed to the function as
parameter.
● The value of the actual parameter can be modified by formal parameter.
● Same memory is used for both actual and formal parameters since only address is
used by both parameters.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}
Output:
To access members of structure with structure variable, we used the dot ― .” operator. But
when we have a pointer of structure type, we use arrow ―->” to access structure members.
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book b;
struct Book* ptr = &b;
ptr->name = "Dan Brown"; //Accessing Structure
Members ptr->price = 500;
}
STRUCTURED PROGRAMMING BY LARRY BETT
● When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
● If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the
file using few commands in C.
● You can easily move your data from one computer to another without any changes.
Access to a record for reading it is the essential operation on data. There are two types of access:
1. Sequential access - is performed when records are accessed in the order they are
stored. Sequential access is the main access mode only in batch systems, where files are
used and updated at regular intervals.
2. Direct access - on-line processing requires direct access, whereby a record can be
accessed without accessing the records between it and the beginning of the file. The primary
key serves to identify the needed record.
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and
takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than
text files.
STRUCTURED PROGRAMMING BY LARRY BETT
File Operations
In C, you can perform four major operations on the file, either text or binary:
ptr = fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
● Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The
first function creates a new file named newprogram.txt and opens it for writing as per
the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
● Now let's suppose the second binary file oldprogram.bin exists in the location
E:\cprogram. The second function opens the existing file for reading in binary
mode 'rb'. The reading mode only allows you to read the file, you cannot write into
the file.
File
Meaning of Mode During Inexistence of file
Mode
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
File
Meaning of Mode During Inexistence of file
Mode
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing If the file exists, its contents are overwritten. If
wb+
in binary mode. the file does not exist, it will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.
Open for both reading and
ab+ If the file does not exists, it will be created.
appending in binary mode.
Closing a File
The file (both text and binary) should be closed after reading/writing.
They are just the file versions of printf() and scanf(). The only difference is that, fprint and
fscanf expects a pointer to the structure FILE.
STRUCTURED PROGRAMMING BY LARRY BETT
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num)
; fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive
of your computer. When you open the file, you can see the integer you entered.
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
return 0; }
STRUCTURED PROGRAMMING BY LARRY BETT
This program reads the integer present in the program.txt file and prints it onto the screen.
If you succesfully created the file from Example 1, running this program will get you the integer
you entered.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
STRUCTURED PROGRAMMING BY LARRY BETT
We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the
main function as num.
Now, inside the for loop, we store the value into the file using fwrite.
The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.
Since, we're only inserting one instance of num, the third parameter is 1. And, the last parameter
*fptr points to the file we're storing the
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
STRUCTURED PROGRAMMING BY LARRY BETT
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr
into the structure num.
This will waste a lot of memory and operation time. An easier way to get to the required data can
be achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
The first parameter stream is the pointer to the file. The second parameter is the position of the
record to be found, and the third parameter specifies the location where the offset starts.
Whence Meaning
Example of fseek()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
STRUCTURED PROGRAMMING BY LARRY BETT
FILE *fptr;
return 0;
}
This program will start reading the records from the file program.bin in the reverse order (last to
first) and prints it.
Write a C program to read name and marks of n number of students from user and store
them in a file
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
STRUCTURED PROGRAMMING BY LARRY BETT
Write a C program to read name and marks of n number of students from user and store
them in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Write a C program to write all the members of an array of strcures to a file using fwrite().
Read the array from the file and display on the screen.
#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
STRUCTURED PROGRAMMING BY LARRY BETT
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}
STRUCTURED PROGRAMMING BY LARRY BETT
CHAPTER 9: PROGRAM
DOCUMENTATION
Define program documentation
In computer hardware and software product development, documentation is the
information that describes the product to its users. It consists of the product technical
manuals and online information (including online versions of the technical manuals and
help facility descriptions). The term is also sometimes used to mean the source
information about the product contained in design documents, detailed code
comments, white papers, and blackboard session notes.
qualities of a system. This is the foundation for what will be or has been implemented.
2. Architecture/Design – Overview of software. Includes relations to an
environment and construction principles to be used in design of software
components.
STRUCTURED PROGRAMMING BY LARRY BETT
User Documentation
Also known as software manuals, user documentation is intended for end users and aims to help
them use software properly. It is usually arranged in a book-style and typically also features table
of contents, index and of course, the body which can be arranged in different ways, depending on
whom the software is intended for. For example, if the software is intended for beginners, it
usually uses a tutorial approach and guides the user step-by-step. Software manuals which are
intended for intermediate users, on the other hand, are typically arranged thematically, while
manuals for advanced users follow reference style.
Besides printed version, user documentation can also be available in an online version or PDF
format. Often, it is also accompanied by additional documentation such as video tutorials,
knowledge based articles, videos, etc.
Requirements Documentation
Requirements documentation, also referred to simply as requirements explains what a software
does and shall be able to do. Several types of requirements exist which may or may not be
included in documentation, depending on purpose and complexity of the system. For example,
applications that don‘t have any safety implications and aren‘t intended to be used for a longer
period of time may be accompanied by little or no requirements documentation at all. Those that
can affect human safety or/and are created to be used over a longer period of time, on the other
hand, come with an exhausting documentation.
Architecture Documentation
Also referred to as software architecture description, architecture documentation either analyses
software architectures or communicates the results of the latter (work product). It mainly deals
with technical issues including online marketing and seo services but it also covers non-technical
issues in order to provide guidance to system developers, maintenance technicians and others
involved in the development or use of architecture including end users. Architecture
documentation is usually arranged into architectural models which in turn may be organized into
different views, each of which deals with specific issues.
Technical Documentation
Technical documentation is a very important part of software documentation and many
programmers use both terms interchangeably despite the fact that technical documentation is
only one of several types of software documentation. It describes codes but it also addresses
algorithms, interfaces and other technical aspects of software development and application.
Technical documentation is usually created by the programmers with the aid of auto-generating
tools.
STRUCTURED PROGRAMMING BY LARRY BETT
It emerged in the late 1950s with the appearance of the ALGOL 58 and ALGOL 60
programming languages, with the latter including support for block structures. Contributing
factors to its popularity and widespread acceptance, at first in academia and later among
practitioners, include the discovery of what is now known as the structured program theorem in
1966, and the publication of the influential "Go To Statement Considered Harmful" open letter in
1968 by Dutch computer scientist Edsger W. Dijkstra, who coined the term "structured
programming".
Structured programming is most frequently used with deviations that allow for clearer programs
in some particular cases, such as when exception handling has to be performed.