Structured Programming Notes
Structured Programming Notes
WITH C
Page 1
TABLE OF CONTENT
1.0 Programming concepts ...................................................................... 5
1.1 Programming concepts ......................................................................................5
1.2 Generation of programming languages ....................................................................6
2.0 Programming approaches ................................................................... 8
2.1 Programming approaches .....................................................................................8
3.0 Program development ...................................................................... 10
3.1 Definition........................................................................................................ 10
3.2 Program specification ........................................................................................ 10
3.2 Program development cycle ................................................................................ 10
4.0 Program design ............................................................................... 13
4.1 Define program design ...................................................................................... 14
4.2 Design approaches ............................................................................................ 14
4.3 Design tools .................................................................................................... 15
5.0 Introduction to structured programming using c language ......................... 24
5.1 C concepts ...................................................................................................... 24
5.2 C programming environment .............................................................................. 25
5.3 C program format ............................................................................................. 26
6.0 Fundamentals of c programming ......................................................... 28
6.1 C fundamentals ................................................................................................ 28
6.2 Control structures ............................................................................................. 52
6.2 Concepts of sub programs .................................................................................. 69
Passing Arguments to main() ................................................................................... 72
7.0: Pointers and data structures............................................................... 82
7.1 Pointers .......................................................................................................... 82
7.2 Implementing pointers ....................................................................................... 83
7.3 Data structures ................................................................................................. 89
8.0: sorting and searching..................................................................... 100
8.1 Searching ...................................................................................................... 100
8.2 Sorting techniques. ......................................................................................... 102
9.0: File handling. .............................................................................. 112
9.1 File concepts.................................................................................................. 112
9.2 Types of files. ................................................................................................ 112
9.3 Writing, opening, appending and closing files ...................................................... 113
10: Program documentation .................................................................. 117
10.1 Uses of program documentation ....................................................................... 118
10.2 Types of Program Documentation .................................................................... 118
11.0: Emerging trends in programming ................................................... 119
11.1 Emerging trends in programming. .................................................................... 119
11.2 Challenges of Emerging Trends in Structured Programming .................................. 121
12.0 References ................................................................................. 123
Page 2
MODULE UNIT SUMMARY
INTRODUCTION TO C concepts 4 4 8
STRUCTURED PROGRAMMING C programming environment
USING C LANGUAGE C program format
Page 3
EMERGING TRENDS IN Identification of emerging 6 0 6
STRUCTURAL PROGRAMMING trends
Challenges of emerging
trends
Coping with the challenges
of emerging tends
Page 4
1.0 Programming concepts
Program -A computer program is a set of instructions that performs a specific task when
executed by a computer. A computer requires programs to function.
Programming- is the process of creating a set of instructions that tell a computer how to
perform a task. Programming can be done using a variety of computer "languages," such as
SQL, Java, Python, and C++.
Compiler - a program that converts instructions into a machine-code or lower-level form so that
they can be read and executed by a computer.
A text editor is a computer program that lets a user enter, change, store, and usually print text .
A linker or link editor is a computer utility program that takes one or more object files
generated by a compiler and combines them into a single executable file, library file, or another
'object' file.
Loader: A program which loads the executable file to the primary memory of the machine.
Computer hardware - refers to the physical parts of a computer and related devices. Internal
hardware devices include motherboards, hard drives, and RAM. External hardware devices
include monitors, keyboards, mice, printers, and scanners.
The internal hardware parts of a computer are often referred to as components, while external
hardware devices are usually called peripherals. Together, they all fall under the category of
computer hardware. Software, on the other hand, consists of the programs and applications that
run on computers. Because software runs on computer hardware, software programs often have
system requirements that list the minimum hardware required for the software to run.
Software - refers to the set of electronic program instructions or data a computer processor
reads in order to perform a task or operation. In contrast, the term 'hardware' refers to the
physical components that you can see and touch, such as the computer hard drive, mouse, and
keyboard. Software can be categorized according to what it is designed to accomplish. There are
two main types of software: systems software and application software.
Page 5
Systems Software-System software is a type of computer program that is designed to run a
computer's hardware and application programs. If we think of the computersystem as a layered
model, the system software is the interface between the hardware and user applications.
Applications Software-Application software, or simply applications, are often called
productivity programs or end-user programs because they enable the user to complete tasks,
such as creating documents, spreadsheets, databases and publications, doing online research,
sending email, designing graphics, running businesses, and even playing games! Application
software is specific to the task it is designed for and can be as simple as a calculator application
or as complex as a word processing application.
Program-This is a complete set of step-by-step instructions that control and direct the computer
hardware in carrying out a given task. Tasks may vary from very simple e.g. computing
surface area to complex ones like statistical analysis.
Programs are usually written to solve user problems on a computer.
A program can be written in a variety of programming languages. The languages can broadly be
classified into two categories:
Low-level language – which refers to the machine language and assembly language.
High-Level languages: - which refers to languages such as COBOL, FORTRAN, BASIC
Machine code or object code, machine language is a collection of binary digits or bits that the
computer reads and interprets. Machine language is the only language a computer is capable of
understanding.
Advantages
Program translation was fast because no conversion was required.
The program could directly address and control the internal circuitry meaning that these
programs were more effective in hardware usage and control.
Disadvantages
Writing programs was time consuming
Tracing errors in a program was extremely difficult.
Page 6
Difficult to learn and use.
Program modification was cumbersome.
They were machine dependent i.e. a program created for one type of machine would not work
on a different type of machine.
To write an effective program the programmer had to have expert knowledge on the computer’s
internal workings.
This language was more user oriented than machine language. Instructions are represented using
mnemonic code and symbolic addresses. Words like add, sum etc could be used in programs. An
assembler translated these codes into machine language.
Advantages
Much easier to learn compared to machine language.
Coding took less time than coding using machine language.
Error correction was less cumbersome.
Disadvantages
Were also machine specific
Execution took longer than machine language programs due to the translation process.
These languages are user friendly and problem oriented compared to the low level languages.
Programs written in high level languages are shorter than the machine language programs.
Program instructions are written using familiar English-like statements and mathematical statements.
A single high-level language program is translated into multiple machine code instructions.
Advantages
They are portable i.e. they can be used on more than one type of machine.
Creating program and error correction takes less time.
Are relatively easy to learn and use.
The programmer does not have to be an expert on the internal workings of the machine.
Disadvantages
Program execution takes more time due to the translation process.
They do not address the internal circuitry of computers as effectively as the low level languages.
A translated program will occupy more space.
Page 7
Third generation/Procedural languages
They require the programmer to specify step-by-step how the computer will accomplish a specific task.
Program execution follows the exact sequence laid down by the programmer during coding. Examples
include FORTRAN, C, BASIC,
They allow the programmer to specify the desired result without having to specify the detailed
procedure needed to achieve the result.
They are more user oriented and allow programmers to develop programs with fewer commands
compared with 3rd generation languages. They are called non procedural because programmers can
write programs that need only tell the computer what they want done, not all the procedures of doing it.
Fifth-generation languages are used mainly in artificial intelligence research. OPS5 and Mercury are
examples of fifth-generation languages. These types of languages were also built upon Lisp, many
originating on the Lisp machine, such as ICAD. Then, there are many frame languages, such as KL-
ONE
Programming paradigms are a way to classify programming languages according to the style of
computer programming. Features of various programming languages determine which programming
approaches they belong to; as a result, some languages fall into only one approach, while others fall
into multiple paradigms. Some paradigms are concerned mainly with implications for the execution
model of the language, such as allowing side effects, or whether the sequence of operations is defined
by the execution model.
Unstructured programming.
An unstructured program is a procedural program – the statements are executed in sequence as written.
But this type of programming uses the go to statement. A go to statement allows control to be passed to
any other place in the program. When a go to statement is executed, the sequence continues from the
target of the go to. Thus to understand how a program works, you have to pretend to execute it. This
Page 8
means that it is often difficult to understand the logic of such a program. Some program compilers
cross-index where a goto connects to, making it practical to rapidly navigate the source code. However,
it was a common practice in some programming languages to use a variable in association with where
the goto goes, making automated indexing impractical. There are similar problems in some structured
programming languages, such as how foreign language views are implemented, to permit many people
to view the same computer data, in their human language.
Structured programming
A procedural language is a type of computer programming language that specifies a series of well-
structured steps and procedures within its programming context to compose a program. It contains a
systematic order of statements, functions and commands to complete a computational task or program.
Event-driven programming
Is a programming approach in which the flow of the program is determined by events such as user
actions (mouse clicks, key presses), sensor outputs, or messages from other programs or threads. Event-
driven programming is the dominant paradigm used in graphical user interfaces and other applications
(e.g., JavaScript web applications) that are centered on performing certain actions in response to user
input. This is also true of programming for device drivers (e.g., P in USB device driver stacks)
Visual Programming
In computing, a visual programming language (VPL) is any programming language that lets users
create programs by manipulating program elements graphically rather than by specifying them
textually. A VPL allows programming with visual expressions, spatial arrangements of text and graphic
symbols, used either as elements of syntax or secondary notation. For example, many VPLs (known as
dataflow or diagrammatic programming) are based on the idea of "boxes and arrows", where boxes or
other screen objects are treated as entities, connected by arrows, lines or arcs which represent relations.
refers to the writing, markup and coding involved in Web development, which includes Web content,
Web client and server scripting and network security. The most common languages used for
Web programming are XML, HTML, JavaScript, Perl 5 and PHP.
Page 9
Factors to consider when choosing a programming language
Popularity. You are more likely to find people to collaborate with if you use a popular language.
You are also more likely to find reference material and other help. Unfortunately, the most popular
language globally may not be a good match for your problem domain.
Language-domain match. Choose one that matches your problem domain. You can do this by
looking at what other people in your field are using (after adjusting for popularity, so don't think the
match with Java is good simply because a lot of people are using Java) or by looking at some code
that solves problems you are likely to have and seeing how natural the mapping is.
Availability of libraries. Some would argue that this is the same as the point above, but I don't
think so. If there's a library that solves your problem well, you'll put up with some ugly calling
conventions or hassle in the language.
Efficiency. Languages aren't fast - compilers are efficient. Look at the efficiency of compilers or
interpreters for your language. Be aware that interpreted code will run an order of magnitude slower
than compiled code as a rule of thumb.
Expressiveness. The number of lines of code you create per hour is not a strong function of
language, so favor languages that are expressive or powerful
Project-size. Do you want to be programming in the large or programming in the small? Choose a
language that supports your use case.
Tool support. Popularity usually buys tool support (and some languages are easier to write tools
for). If you are a tool-oriented user, choose a language with good tool support.
3.1 Definition
Software development is the process of computer programming, documenting, testing, and bug fixing
involved in creating and maintaining a software product.
Software development is a process of writing and maintaining the source code, but in a broader sense, it
includes all that is involved between the conception of the desired software through to the final
manifestation of the software, sometimes in a planned and structured process. Therefore, software
development may include research, new development, prototyping, modification, reuse, re-engineering,
maintenance, or any other activities that result in software products.
Program Development Life Cycle (PDLC) is a systematic way of developing quality software. It
provides an organized plan for breaking down the task of program development into manageable
chunks, each of which must be successfully completed before moving on to the next phase.
The following steps are used in sequence for developing an efficient program:
Specifying the problem statement
Designing an algorithm
Page 10
Coding
Debugging
Testing and Validating
Documentation and Maintenance.
Specifying the Problem:
The Problem which has to be implemented into a program must be thoroughly understood
before the program is written. Problem must be analyzed to determine the input and output
requirements of the program. A problem is created with these specifications.
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.
Debugging:
There is a possibility of occurrence of errors in programs. These errors must be removed to
ensure proper working of programs. Hence error check is made. This process is known as
“Debugging”.
Types of errors that may occur in the program are:
Syntactic Errors: These errors occur due to the usage of wrong syntax for the statements.
Syntax means rules of writing the program.
Example: x=z*/b;
There is syntax error in this statement. The rules of binary operators state that there cannot be more
than one operator between two operands.
Runtime Errors: These Errors are determined at the execution time of the program.
Example: Divide by zero
Range out of bounds
Square root of a negative number
Logical Errors: These Errors occur due to incorrect usage of the instruction in the program.
These errors are neither displayed during compilation or execution nor cause any obstruction to
the program execution. They only cause incorrect outputs. Logical Errors are determined by
analyzing the outputs for different possible inputs that can be applied to the program. By this
way the program is validated.
Testing and Validating:
Testing and Validation is performed to check whether the program is producing correct results
or not for different values of input.
Page 11
For writing up the instructions as a program in the way that a computer can understand, we use
programming languages.
Problem Definition- In this phase, we define the problem statement and we decide the boundaries
of the problem. In this phase we need to understand the problem statement, what is our requirement,
what should be the output of the problem solution. These are defined in this first phase of the
program development life cycle.
Problem Analysis- In phase 2, we determine the requirements like variables, functions, etc. to
solve the problem. That means we gather the required resources to solve the problem defined in the
problem definition phase. We also determine the bounds of the solution.
Algorithm Development- During this phase, we develop a step by step procedure to solve the
problem using the specification given in the previous phase. This phase is very important for
program development. That means we write the solution in step by step statements.
Coding & Documentation- This phase uses a programming language to write or implement actual
programming instructions for the steps defined in the previous phase. In this phase, we construct
actual program. That means we write the program to solve the given problem using programming
languages like C, C++, Java etc.
Testing & Debugging- During this phase, we check whether the code written in previous step is
solving the specified problem or not. That means we test the program whether it is solving the
problem for various input data values or not. We also test that whether it is providing the desired
output or not.
Maintenance- During this phase, the program is actively used by the users. If any enhancements
found in this phase, all the phases are to be repeated again to make the enhancements. That means
in this phase, the solution (program) is used by the end user. If the user encounters any problem or
wants any enhancement, then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.
Page 12
Page 13
4.0 Program design
Program design: The activity of progressing from a specification of some required program to a
description of the program itself.
Top-Down Approach
Top-down design takes the whole software system as one entity and then decomposes it to achieve
more than one sub-system or component based on some characteristics. Each sub-system or
component is then treated as a system and decomposed further. This process keeps on running until
the lowest level of system in the top-down hierarchy is achieved.
Top-down design starts with a generalized model of system and keeps on defining the more specific
part of it. When all components are composed the whole system comes into existence.
Top-down design is more suitable when the software solution needs to be designed from scratch
and specific details are unknown.
Bottom-up Approach
The bottom up design model starts with most specific and basic components. It proceeds with
composing higher level of components by using basic or lower level components. It keeps creating
higher level components until the desired system is not evolved as one single component. With each
higher level, the amount of abstraction is increased.
Bottom-up strategy is more suitable when a system needs to be created from some existing system,
where the basic primitives can be used in the newer system.
Both, top-down and bottom-up approaches are not practical individually. Instead, a good
combination of both is used.
Modular Programming
This is a technique that involves breaking down the entire problem into smaller, more manageable
units.
Features
Each module within the application carries out a singular task.
Each module runs independently of the other modules.
Since each module is independent, a breakdown in any module does not greatly affect the
running of the application.
Debugging is easier since errors can be traces to individual modules.
Page 14
Advantages of modular programming
Data driven programming is a programming model where the data itself controls the flow of
the program and not the program logic. It is a model where you control the flow by offering
different data sets to the program where the program logic is some generic form of flow or of state-
changes.
Algorithm
An algorithm is a sequence of steps which results to a plan or strategy on how to go about solving a
problem.
Algorithms
In programming, algorithm is a set of well defined instructions in sequence to solve the problem.
Step 1: Start
Step 2: Declare variables n,factorial and i.
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i=n
5.1: factorial←factorial*i
5.2: i←i+1
Step 6: Display factorial
Step 7: Stop
Page 15
To find whether a number is odd or even
Algorithm
START
Step 1 → Take integer variable A
Step 2 → Assign value to the variable
Step 3 → Perform A modulo 2 and check result if output is 0
Step 4 → If true print A is even
Step 5 → If false print A is odd
STOP
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
1) Start.
2) Accept Number one.
3) Accept Number two.
4) Add both the numbers.
5) Print the result.
6) End
Step 1: Start
Step 4: Exit
Pseudocode
Pseudocode is the statement in plain English which may be translated later into a programming
language (program).
This is a case where an algorithm is expressed in English like statements (descriptions). For example
the following pseudocode calculates the pay amount for five employees.
BEGIN
NUMBER s1, s2, sum
OUTPUT("Input number1:")
INPUT s1
OUTPUT("Input number2:")
INPUT s2
sum=s1+s2
OUTPUT sum
END
1. START
2. DISPLAY "Enter the Number - "
3. READ number
4. IF number MOD 2 = 0 THEN
DISPLAY "Number is Even"
ELSE
DISPLAY "Number is Odd"
END IF
5. STOP
Area of a triangle
begin
numeric nBase, nHigh, nArea
display "ENTER THE BASE OF TRIANGLE : "
accept nBase
display "ENTER THE HEIGHT OF TRIANGLE : "
accept nHigh
nArea=nBase*nHigh
display "AREA OF TRIANGLE : " nArea
end
begin
numeric nSide,nPeri
Page 17
display "ENTER THE SIDE OF SQUARE : "
accept nSide
nPeri=nSide*nSide
display "AREA OF SQUARE : " nPeri
end
begin
numeric nRad, nAre
display "ENTER THE RADIUS OF CIRCLE : "
accept nRad
nAre = nRad*nRad*22/7
display "AREA OF CIRCLE : " nAre
end
begin
numeric nRad,nCir
display "ENTER THE RADIUS OF CIRCLE : "
accept nRad
nCir=2*nRad*22/7
display "CIRCUMFERENCE OF CIRCLE : " nCir
end
begin
numeric nLen,nBrd,nAre
display "ENTER THE LENGTH OF RECGTANGLE : "
accept nLen
display "ENTER THE BREADTH OF RECTANGLE : "
accept nBrd
nAre=2*(nLen+nBrd)
display "PERIMETER OF RECTANGLE : " nAre
end
Flow Chart
This is a symbolic representation of an algorithm sequence. A flow chart uses predefined symbols to
represent the various actions in an algorithm. The arrangement of the symbols indicates the flow of
logic in the algorithm.
Page 18
Symbol Purpose Description
Page 19
Draw flowchart to find the largest among three different numbers entered by user.
Page 20
Find the sum of the first 50 numbers
Decision tables are a concise visual representation for specifying which actions to perform depending
on given conditions.
All programmers may not be familiar with Decision Tables and therefore flow charts are more
common
Flowcharts can better represent a simple logic of the system rather than a decision table.
The decision tables do not express the total sequence of the events needed to solve the problem.
Total sequence - The total sequence is not clearly shown, i.e., no overall picture is given by
decision tables as presented by flowcharts.
Logic - Where the logic of a system is simple, flowcharts nearly always serve the purpose
better than a decision table.
Page 22
Decision Tree
A decision tree is a graph that uses a branching method to illustrate every possible outcome of a
decision
Example
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.
Page 23
Example of Decision tree
Advantages
Are simple to understand and interpret. People are able to understand decision tree models after
a brief explanation.
Have value even with little hard data. Important insights can be generated based on experts
describing a situation (its alternatives, probabilities, and costs) and their preferences for
outcomes.
Help determine worst, best and expected values for different scenarios.
Use a white box model. If a given result is provided by a model.
Can be combined with other decision techniques.
Disadvantages of decision trees:
They are unstable, meaning that a small change in the data can lead to a large change in the
structure of the optimal decision tree.
They are often relatively inaccurate. Many other predictors perform better with similar data.
This can be remedied by replacing a single decision tree with a random forest of decision trees,
but a random forest is not as easy to interpret as a single decision tree.
For data including categorical variables with different number of levels, information gain in
decision trees is biased in favor of those attributes with more levels.
Calculations can get very complex, particularly if many values are uncertain and/or if many
outcomes are linked.
5.1 C concepts
C is a general purpose programming language, unlike other languages such as C and FORTRAN
developed for some specific uses. C is designed to work with both software and hardware. C has in
fact been used to develop a variety of software such as:
Operating systems: Unix and Windows.
Application packages: WordPerfect and Dbase.
It was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs.
C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan
and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX applications programs
have been written in C. The C has now become a widely used professional language for various
reasons.
Easy to learn
Structured language
It produces efficient programs.
Page 24
It can handle low-level activities.
It can be compiled on a variety of computer platforms.
Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language, which was introduced around 1970.
The language was formalized in 1988 by the American National Standard Institute. (ANSI).
The UNIX OS was totally written in C by 1973.
Today, C is the most widely used and popular System Programming Language.
Most of the state-of-the-art softwares have been implemented using C.
Today's most popular Linux OS and RBDMS MySQL have been written in C.
Why to use C?
C was initially used for system development work, in particular the programs that make up the
operating system. C was adopted as a system development language because it produces code that runs
nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems Modern Programs
Databases Text Editors
Language Interpreters Language Compilers
Utilities
MERITS OF C LANGUAGE
Page 25
This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit
command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example, Notepad
will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX.
The files you create with your editor are called the source files and they contain the program source
codes. The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, compile it and finally execute it.
The C Compiler
The source code written in source file is the human readable source for your program. It needs to be
"compiled", into machine language so that your CPU can actually execute the program as per the
instructions given.
The compiler compiles the source codes into final executable programs. The most frequently used and
free available compiler is the GNU C/C++ compiler; otherwise you can have compilers either from HP
or Solaris if you have the respective operating systems.
Preprocessor directives
Preprocessor directives are lines included in a program that begin with the character #, which make
them different from a typical source code text. They are invoked by the compiler to process some
programs before compilation.
#define- the #define directive allows the definition of macros within your source code.
#include- Inserts a particular header from another file.
#undef- Undefines a preprocessor macro.
#ifdef- Returns true if this macro is defined.
#ifndef- Returns true if this macro is not defined.
#if- Tests if a compile time condition is true.
#else- The alternative for #if.
#elif- #else and #if in one statement.
#endif- Ends preprocessor conditional.
#error-Prints error message on stderr.
#pragma- Issues special commands to the compiler, using a standardized method.
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
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.
Page 26
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. Check Builtin functionsection for
more detail.
You will learn how to write your own functions and use them in Using Function session.
Variables: are used to hold numbers, strings and complex data for manipulation. You will learn in
detail about variables in C Variable Types.
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.
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Explanation:
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.
The next line int main() is the main function where the program execution begins.
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.
The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.
Page 27
6.0 Fundamentals of c programming
6.1 C fundamentals
An operator is a component of any expression that joins individual constants, variables, array elements
and function references.
An operand is a data item that is acted upon by an operator. Some operators act upon two operands
(binary operators) while others act upon only one operand (unary operators).
Examples
x + y ; x, y are operands, + is an addition operator.
3 * 5; 3, 5 are constant operands, * is a multiplication operator.
x % 2.5; x, 5 are operands, % is a modulus (remainder) operator.
sizeof (int); sizeof is an operator (unary), int is an operand.
Arithmetic Operators
Note:
There exists no exponential operators in C.
The operands acted upon by arithmetic operators must represent numeric values, that is operands may
be integers, floating point quantities or characters (since character constants represent integer values).
The % (remainder operator) requires that both operands be integers.
Thus;
5%3
int x = 8;
int y = 6 ; x % y are valid while;
8.5 % 2.0 and
float p = 6.3, int w = 7 ; 5 %p , p % w are invalid.
Division of one integer quantity by another is known as an integer division. If the quotient (result of
division) has a decimal part, it is truncated.
Dividing a floating point number with another floating point number, or a floating point number with
an integer results to a floating point quotient .
Page 28
Exercise
Suppose a = 10, b = 3, v1 = 12.5, v2 = 2.0, c1 =’P’, c2 = ‘T’. Compute the result of the following
expressions.
a+b v1 * v2
a-b v1 / v2
a*b c1
a/b c1 + c2 +5
a%b c1 + c2 +’9’
Note:
c1 and c2 are character constants
ASCII codes for 9 is 57, P = 80,T = 84.
If one or both operands represent negative values, then the addition, subtraction, multiplication, and
division operators will result in values whose signs are determined by their usual rules of algebra. Thus
if a b, and c are 11, -3 and –11 respectively, then
a+b =8
a – b = 14
a * b = -33
a / b = -3
a % b = -2
c % b = -2
c/b=3
Note:
If both operands are floating point types whose precision differ (e.g. a float and a double) the lower
precision operand will be converted to the precision of the other operand, and the result will be
expressed in this higher precision. (Thus if an expression has a float and a double operand, the result
will be a double).
If one operand is a floating-point type (e.g. float, double or long double) and the other is a character or
integer (including short or long integer), the character or integer will be converted to the floating point
type and the result will be expressed as such.
If neither operand is a floating-point type but one is long integer, the other will be converted to long
integer and the result is expressed as such. (Thus between an int and a long int, the long int will be
taken).
If neither operand is a floating type or long int, then both operands will be converted to int (if
necessary) and the result will be int (compare short int and long int)
Page 29
i+f
i+c
i + c-‘w’
( i + c) - ( 2 * f / 5)
Note: Whichever type of result an expression evaluates to, a programmer can convert the result to a
different data type if desired. The general syntax of doing this is:
Operator Precedence
The order of executing the various operations makes a significant difference in the result. C assigns
each operator a precedence level. The rules are;
Multiplication and division have a higher precedence than addition and subtraction, so they are
performed first.
If operators of equal precedence; (*, /), (+, -) share an operand, they are executed in the order in which
they occur in the statement. For most operators, the order (associativity) is from left to right with the
exception of the assignment ( = ) operator.
Note that it is possible for the programmer to set his or her own order of evaluation by putting, say,
parenthesis. Whatever is enclosed in parenthesis is evaluated first.
Page 30
Example: Use of operators and their precedence
/* Program to demonstrate use of operators and their precedence */
include<stdio.h >
main()
{
int score,top;
score = 30;
top = score - (2*5) + 6 * (4+3) + (2+3);
printf (“top = %d \ n” , top);
system(“pause”);
return 0;
}
Try changing the order of evaluation by shifting the parenthesis and note the change in the top score.
sizeof returns the size in bytes, of its operand. The operand can be a data type e.g. sizeof (int), or a
specific data object e.g. sizeof n.
If it is a name type such as int, float etc. The operand should be enclosed in parenthesis.
Page 31
The Assignment operator ( = ) is a value assigning operator. There are several other assignment
operators in C. All of them assign the value of an expression to an identifier.
Assignment expressions that make use of the assignment operator (=) take the form;
identifier = expression;
where identifier generally represents a variable, constant or a larger expression.
Examples of assignment;
a=3;
x=y;
pi = 3.14;
sum = a + b ;
area_circle = pi * radius * radius;
Note
You cannot assign a variable to a constant such as 3 = a ;
The assignment operator = and equality operator (= =) are distinctively different. The = operator
assigns a value to an identifier. The equality operator (= =) tests whether two expressions have the
same value.
Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5 to both a and b.
Assignment can be combined with +, -, /, *, and %
evaluate expression1. If expression1 evaluates to true ( value is 1 or non zero) then evaluate
expression 2, otherwise (i.e. if expression 1 is false or zero ) , evaluate expression3.
Assuming i is an integer, the expression (i < 0) is evaluated and if it is true, then the result of the entire
conditional expression is zero (0), otherwise, the result will be 100.
Unary Operators
These are operators that act on a single operand to produce a value. The operators may precede the
operand or are after an operand.
Examples
Unary minus e.g. - 700 or –x
Incrementation operator e.g. c++
Decrementation operator e.g. f - -
sizeof operator e.g. sizeof( float)
Page 32
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
Relational Operators
A logical expression represents conditions that are either true (represented by integer 1) or false
(represented by 0).
Example
Consider a, b, c to be integers with values 1, 2,3 respectively. Note their results with relational
operators below.
Expression Result
a<b 1 (true)
(a+ b) > = c 1 (true)
(b + c) > (a+5) 0 (false)
C != 3 0(false)
b==2 1 (true)
Logical operators
The two operators act upon operands that are themselves logical expressions to produce more complex
conditions that are either true or false.
Page 33
Example
Suppose i is an integer whose value is 7, f is a floating point variable whose value is 5.5 and C is a
character that represents the character ‘w’, then;
Revision Exercises
Further suppose that c1, c2, c3 are character-type variables assigned the values E, 5 and ? respectively.
Data Types
In computer programming, a data type or simply type is a classification of data which tells the compiler
or interpreter how the programmer intends to use the data. Most programming languages support
various types of data, for example: real, integer or Boolean. A Data type provides a set of values from
which an expression (i.e. variable, function ...) may take its values. The type defines the operations that
can be done on the data, the meaning of the data, and the way values of that type can be stored.
Page 34
It is a type specifier used to declare integer variables. For example, to declare count as an integer you
would write:
int count;
Integer variables may hold signed whole numbers (numbers with no fractional part). Typically, an
integer variable may hold values in the range –32,768 to 32,767 and are 2 bytes long.
I/O Instructions –
C programming has several in-built library functions to perform input and output tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard) whereas
the printf() function sends formatted output to the standard output (screen).
Page 35
Example 1: C Output
#include <stdio.h> // Including header file to run printf() function.
int main()
{
printf("C Programming"); // Displays the content inside quotation
return 0;
}
Output
C Programming
All valid C program must contain the main() function. The code execution begins from the start
of main() function.
The printf() is a library function to send formatted output to the screen.
The printf()function is declared in "stdio.h" header file.
Here, stdio.h is a header file (standard input output header file) and #include is a
preprocessor directive to paste the code from the header file when necessary. When the
compiler encounters printf() function and doesn't find stdio.h header file, compiler shows
error.
The return 0; statement is the "Exit status" of the program.
Output
Page 36
Number = 5
Inside the quotation of printf() function, there is a format string "%d" (for integer). If the
format string matches the argument ( testInteger in this case), it is displayed on the screen.
Output
Enter an integer: 4
Number = 4
Keywords - These are reserved words that have special meaning in a language. The compiler
recognizes a keyword as part of the language’s built – in syntax and therefore it cannot be used for any
other purpose such as a variable or a function name. C keywords must be used in lowercase otherwise
they will not be recognized.
Examples of keywords
auto break case else int void
default do double if sizeof long
float for goto signed unsignedError! Bookmark not defined.
register return short union continue
struct switch typedef const extern
Page 37
volatile while char enum static
Handling Errors
Logic Errors
These occur from the incorrect use of control structures, incorrect calculation, or omission of a
procedure. Examples include: An indefinite loop in a program, generation of negative values instead of
positive values. The compiler will not detect such errors since it has no way of knowing your
intentions. The programmer must try to run the program so that he/she can compare the program’s
results with already known results.
Semantic Errors
They are caused by illegal expressions that the computer cannot make meaning of. Usually no results
will come out of them and the programmer will find it difficult to debug such errors. Examples include
a data overflow caused by an attempt to assign a value to a field or memory space smaller than the
value requires division by zero.
Syntax errors
These are errors in the code you write so that the compiler cannot understand your code and the code
will not compile. They include missing colon, semicolon and parenthesis.
Syntaxerrors occur when a program does not conform to the grammar of a programming language,
and the compiler cannot compile the source file. Logic errors occur when a program does not do what
the programmer expects it to do.
Coding - Computer programming (often shortened to programming) is a process that leads from an
original formulation of a computing problem to executable computer programs. Programming involves
activities such as analysis, developing understanding, generating algorithms, verification of
requirements of algorithms including their correctness and resources consumption, and implementation
(commonly referred to as coding) of algorithms in a target programming language. Source code is
written in one or more programming languages. The purpose of programming is to find a sequence of
instructions that will automate performing a specific task or solving a given problem. The process of
programming thus often requires expertise in many different subjects, including knowledge of the
application domain, specialized algorithms, and formal logic.
Compiling - A compiler is a computer program (or a set of programs) that transforms source code
written in a programming language (the source language) into another computer language (the target
language), with the latter often having a binary form known as object code. The most common reason
for converting source code is to create an executable program. The name "compiler" is primarily used
Page 38
for programs that translate source code from a high-level programming language to a lower level
language (e.g., assembly language or machine code). If the compiled program can run on a computer
whose CPU or operating system is different from the one on which the compiler runs, the compiler is
known as a cross-compiler. More generally, compilers are a specific type of translator.
Debugging - Debugging is the routine process of locating and removing computer program bugs, errors
or abnormalities, which is methodically handled by software programmers via debugging tools.
Debugging checks, detects and corrects errors or bugs to allow proper program operation according to
set specifications. Developing software programs undergo heavy testing, updating, troubleshooting and
maintenance. Normally, software contains errors and bugs, which are routinely removed. In the
debugging process, complete software programs are regularly compiled and executed to identify and
rectify issues. Large software programs, which contain millions of source code lines, are divided into
small components.
Testing - testing is finding out how well something works. In terms of human beings, testing tells what
level of knowledge or skill has been acquired. In computer hardware and software development, testing
is used at key checkpoints in the overall process to determine whether objectives are being met. For
example, in software development, product objectives are sometimes tested by product user
representatives. When the design is complete, coding follows and the finished code is then tested at the
unit or module level by each programmer; at the component level by the group of programmers
involved; and at the system level when all components are combined together. At early or late stages, a
product or service may also be tested for usability.
Language Translators- These are programs that translate programs written in a language other than
machine language into machine language programs for execution. Programs written in assembly or
high level languages are called source programs or source code before they undergo translation. After
the translation the machine language version of the same program is called object program or object
code. Language translators can be classified into
Assemblers
Compilers
Interpreters
Assembler- This is a program that translates a source program written in assembly language into its
equivalent machine code (object code).
Compiler- During compilation both the high level source program and the compiler are loaded into the
RAM. The compiler reads through the source program statement by statement, converting each correct
statement into multiple machine code instructions. The process continues until the compiler has read
through the entire source program or it encounters an error. An erroneous statement is not translated
but is placed on the source program error listing, which will be displayed to the programmer at the end
of the translation process. Where there are no errors the compiler will generate a machine code object
program which is stored for subsequent execution.
Interpreter
It Is similar to the compiler in that it translates high level language programs into machine code for
execution but no object code is generated. An interpreter translates the program one statement at a time
and if it is error free it executes the statement. This continues till the last statement in the program has
Page 39
translated and executed. Thus an interpreter translates and executes a statement before it goes to the
next statement. When it encounters an error it will immediately stop the execution of the program.
Interpreter Compiler
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower. comparatively faster.
Continues translating the program until the It generates the error message only after
first error is met, in which case it stops. scanning the whole program. Hence
Hence debugging is easy. debugging is comparatively hard.
Programming language like Python, Ruby Programming language like C, C++ use
use interpreters. compilers.
Examples of compiler
gcc
clang
javac
go (compiler)
Some compiler runs before the program first run, but there are some case that compiler run after
program started that called JIT (just in time).
Interpreter is program that executes source code or byte code, for example:
ruby (interpreter)
python (interpreter)
php (interpreter)
Page 40
Compiling – The compiler converts the source code to produce the intermediate object code.
An object file is a file containing object code, meaning relocatable format machine code that is usually
not directly executable. There are various formats for object files, and the same object code can be
packaged in different object files. An object file may also work like a shared library.
The linker combines the intermediate code with other code to produce the executable file. C does
this in a modular manner.
Every C file must be saved with a .c file extension.
Linker: it is a system software which combines One or more object files and possible some library
code into either some executable some library or a list of error.
Loader: A program which loads the executable file to the primary memory of the machine.
Comments
Comments are non – executable program statements meant to enhance program readability and allow easier
program maintenance, i.e. they document the program.
Types
Multiline Comments
Multiline comments have one or more lines of narrative within a set of comment delimiters. These
comment delimiters are the begin comment /* and end comment */ markers. Anything between these
two markers is considered a comment. The compiler ignores comments when reading the source code.
Lines 1 through 4 of Listing 1 show a multiline comment. For convenience, Lines 1 through 4 of
Listing 1 are repeated here.
1: /*
2: * FileName: HowdyParner.cs
3: * Author: Joe Mayo
4: */
Some languages allow embedded multiline comments, but C# does not. Consider the following
example:
1: /*
2: Filename: HowdyPartner.cs
3: Author: Joe Mayo
4: /*
5: Initial Implementation: 04/01/01
6: Change 1: 05/15/01
7: Change 2: 06/10/01
8: */
9: */
Page 41
The begin comment on Line 1 starts a multiline comment. The second begin comment on line 4 is
ignored in C# as just a couple characters within the comment. The end comment on Line 8 matches
with the begin comment on line 1. Finally, the end comment on Line 9 causes the compiler to report a
syntax error because it doesn't match a begin comment.
Single-Line Comments
Single-line comments allow narrative on only one line at a time. They begin with the double forward
slash marker, //. The single-line comment can begin in any column of a given line. It ends at a new line
or carriage return. Lines 6, 9, and 12 of Listing 1 show single-line comments. These lines are repeated
here for convenience.
Declaration statements
In C, all variables must be declared before they are used. Variable declarations ensure that appropriate
memory space is reserved for the variables, depending on the data types of the variables. Line 6 is a
declaration for an integer variable called num.
An assignment statement uses the assignment operator “=” to give a variable on the operator’s left side
the value to the operator’s right or the result of the expression on the right. The statement num =1;
(Line 6) is an assignment statement.
Escape sequences
Escape sequences (also called back slash codes) are character combinations that begin with a backslash
symbol (\) used to format output and represent difficult-to-type characters.
One of the most important escape sequences is \n, which is often referred to as the new line character.
When the C compiler encounters \n, it translates it into a carriage return.
For example, this program:
#include<stdio.h>
main()
Page 42
{
printf(“This is line one \n”);
printf(“This is line two \n”);
printf(“This is line three”);
system(pause);
return 0;
}
displays the following output on the screen.
Special character in C
, Comma * Asterisk ' Apostrophe ( Left Parenthesis
& .Ampersand : Colon < Opening Angle(Less than sign) | Vertical Bar
.
. Period - .Minus Sign " Quotation Marks ) Right Parenthesis
; Semicolon ? Question > Closing Angle(Greater than sign) / Slash
Mark
^ Caret + .Plus Sign ! Exclamation Mark [ Left Bracket
\ Backslash ~ Tilde % Percentage Sign $ Dollar Sign
Variables
A variable is a memory location whose value can change during program execution. In C, a variable
must be declared before it can be used. Variables can be declared at the start of any block of code.
A declaration begins with the type, followed by the name of one or more variables. For example,
int high, low, results[20];
Page 43
Types of Variables
There are two places where variables are declared: inside a function or outside all functions.
Variables declared outside all functions are called global variables and they may be accessed by any
function in your program. Global variables exist the entire time your program is executing.
Variables declared inside a function are called local variables. A local variable is known to and may be
accessed by only the function in which it is declared. You need to be aware of two important points
about local variables.
The local variables in one function have no relationship to the local variables in another function. That
is, if a variable called count is declared in one function, another variable called count may also be
declared in a second function – the two variables are completely separate from and unrelated to one
another.
Local variables are created when a function is called, and they are destroyed when the function is
exited. Therefore local variables do not maintain their values between function calls.
Constants
A constant is a value that does not change during program execution. In other words, constants are
fixed values that may not be altered by the program.
Integer constants are specified as numbers without fractional components. For example –10, 1000 are
integer constants.
Floating - point constants require the use of the decimal point followed by the number’s fractional
component. For example, 11.123 is a floating point constant. C allows you to use scientific notation for
floating point numbers. Constants using scientific notation must follow this general form:
number E sign exponent
The number is optional. Although the general form is shown with spaces between the component parts
for clarity, there may be no spaces between parts in an actual number . For example, the following
defines the value 1234.56 using scientific notation.
123.456E1
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'.
ch = ‘z’;
Note:
There is nothing in C that prevents you from assigning a character variable a value using a numeric
constant. For example the ASCII Code for ‘A ‘ is 65. Therefore, these two assignments are equivalent.
char ch;
ch = “A’;
ch = 65;
Page 44
Types of Constants
Constants can be used in C expressions in two ways:
Directly
Here the constant value is inserted in the expression, as it should typically be.
For example:
Area = 3.14 * Radius * Radius;
The value 3.14 is used directly to represent the value of PI which never requires changes in the
computation of the area of a circle
This process is generally referred to as macro substitution. The general form of the #define statement
is;
Notice that this line does not end in a semi colon. Each time the macro - name is encountered in the
program, the associated string is substituted for it. For example, consider the following program.
Page 45
Declarations can be spread out, allowing space for an explanatory comment. Variables can also be
initialised when they are declared. This is done by adding an equals sign and the required value after
the declaration.
Scope of variables
Scope of variable refers to the visibility of a variable in a program. Meaning which parts of your
program can see or use it.
A scope is a region of the program and broadly speaking there are three places, where variables can be
declared −
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
Local Variables
Are variables declared inside a given procedure and can be accessed or used only in a procedure in
which they are declared. These types of variables are only meaningful inside the procedure. No
statements outside the procedure may reference local variables .A local variable is a variable that is
given local scope. Local variable references in the function or block in which it is declared override the
same variable name in the larger scope. In programming languages with only two levels of visibility,
local variables are contrasted with global variables.
2) Global Variables
Variables declared for the entire program. Global variables can be utilized anywhere within the
program block, whether inside of or external to the procedure. a global variable is a variable with global
scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed.
Variable Names
Every variable has a name and a value. The name identifies the variable and the value stores data.
There is a limitation on what these names can be. Every variable name in C must start with a letter; the
rest of the name can consist of letters, numbers and underscore characters.
C recognizes upper and lower case characters as being different (C is case- sensitive). Finally, you
cannot use any of C's keywords like main, while, switch etc as variable names.
Page 46
Examples of legal variable names
x result outfile bestyet
x1 x2 out_file best_yet
You can use printf( ) to display values of characters, integers and floating - point values. To do so,
however, requires that you know more about the printf( ) function.
For example:
printf(“This prints the number %d ”, 99);
displays This prints the number 99 on the screen. As you can see, this call to the printf( ) function
contains two arguments. The first one is the quoted string and the other is the constant 99. Notice that
the arguments are separated from each other by a comma.
In general, when there is more than one argument to a function, the arguments are separated from each
other by commas. The first argument is a quoted string that may contain either normal characters or
formal specifiers that begin with a percent (%) sign.
Normal characters are simply displayed as is on the screen in the order in which they are encountered in
the string (reading left to right). A format specifier, on the other hand informs printf( ) that a different
type item is being displayed. In this case, the %d, means that an integer, is to be output in decimal
format. The value to be displayed is to be found in the second argument. This value is then output at the
position at which the format specifier is found on the string.
If you want to specify a character value, the format specifier is %c. To specify a floating-point value,
use %f. The %f works for both float and double. Keep in mind that the values matched with the format
specifier need not be constants, they may be variables too.
Code Format
%c Character
%d Signed decimal integers
%i Signed decimal integers
%e Scientific notation (lowercase ‘e’)
%E Scientific notation (lowercase ‘E’)
%f Decimal floating point
%s String of characters
%u Unsigned decimal integers
%x Unsigned hexadecimal (lowercase letters)
%X Unsigned hexadecimal (Uppercase letters)
Examples
1. The program shown below illustrates the above concepts. First, it declares a variable called num.
Second, it assigns this variable the value 100. Finally, it uses printf( ) to display the value is 100 on
the screen. Examine it closely.
Page 47
#include <stdio.h>
main()
{
int num;
num = 100;
printf(“ The value is %d “, num);
system(“pause”);
return 0;
}
This program creates variables of types char, float, and double assigns each a value and outputs these
values to the screen.
#include<stdio.h>
main()
{
char ch;
float f;
double d;
ch = ‘X’;
f = 100.123;
d = 123.009;
printf(“ ch is %c “, ch);
printf(“ f is %f “, f);
printf(“ d is %f “, d);
system(“pause”);
return 0;
}
There are several ways to input values through the keyboard. One of the easiest is to use another of C’s
standard library functions called scanf( ).
To use scanf( ) to read an integer value from the keyboard, call it using the general form:
scanf(“%d”, &int-var-name);
Where int-var-name is the name of the integer variable you wish to receive the value. The first
argument to scanf( ) is a string that determines how the second argument will be treated. In this case
the %d specifies that the second argument will be receiving an integer value entered in decimal format.
The fragment below, for example, reads an integer entered from the keyboard.
int num;
scanf(“%d”, &num);
The & preceding the variable name means ‘address of’. The values you enter are put into variables
using the variables’ location in memory. It allows the function to place a value into one of its
arguments.
Page 48
When you enter a number at the keyboard, you are simply typing a string of digits. The scanf( )
function waits until you have pressed <ENTER> before it converts the string into the internal format
used by the computer.
The table below shows format specifiers or codes used in the scanf () function and their meaning.
Code Meaning
%c Read a single character
%d Read a decimal integer
%i Read a decimal integer
%e Read a floating point number
%f Read a floating point number
%lf Read a double
%s Read a string
%u Reads an unsigned integer
Examples
1. This program asks you to input an integer and a floating-point number and displays the value.
#include<stdio.h>
main()
{
int num;
float f;
printf(“ \nEnter an integer: “);
scanf( “%d “, &num);
printf(“\n Enter a floating point number: “);
scanf( “%f “, &f);
printf( “%d ”, num);
printf( “\n %f ”, f);
system(“pause”);
return 0;
}
2. This program computes the area of a rectangle, given its dimensions. It first prompts the user for the
length and width of the rectangle and then displays the area.
#include<stdio.h>
main()
{
int len, width;
printf(“\n Enter length: “);
Page 49
scanf (“%d “, &len);
printf(“\n Enter width : ” );
scanf( “ %d “, &width);
printf(“\n The area is %d “, len * width);
system(“pause”);
return 0;
}
Exercises
#include <stdio.h>
#define PI 3.14
main()
{
float radius, area;
printf(“Enter the radius of the circle \n”);
scanf(“%f”, &radius);
area = PI * radius * radius; /* PI is a symbolic constant */
printf(“Area is %.2f cm squared “,area);
system(“pause”);
return 0;
}
Note:
At the time of the substitution, the text such as 3.14 is simply a string of characters composed of 3, ., 1
and 4. The preprocessor does not convert a number into any sort of internal format. This is left to the
compiler.
Revision Exercises
Discuss four fundamental data types supported by C, stating how each type is stored in memory.
Distinguish between a variable and a constant.
Suggest, with examples two ways in which constant values can be used in C expression statements.
Give the meaning of the following declarations;
(i) char name[20];
(ii) int num_emp;
(iii) double tax, basicpay;
(iv) char response;
Page 50
What is the difference between a local and a global variable?
Write a program that will prompt you to enter the radius a cylinder. The code then calculates the
volume of the cylinder.
C PROGRAM EXAMPLES.
A C code that calculates the average of 3 integers.
#include<stdio.h>
main()
{
int x,y,z;
float average,sum=0.0;
printf("Enter x ");
scanf("%d", &x);
printf("Enter y ");
scanf("%d", &y);
printf("Enter z ");
scanf("%d", &z);
sum=x+y+z;
average = sum/3;
printf("\n The average is %f \n", average);
system("pause");
return 0;
}
#include <stdio.h>
#include <math.h>
int main()
{
float radius;
float surface_area, volume;
printf("Enter radius of the sphere : \n");
scanf("%f", &radius);
surface_area = 4 * (22/7) * radius * radius;
volume = (4.0/3) * (22/7) * radius * radius * radius;
printf("Surface area of sphere is: %.3f", surface_area);
printf("\n Volume of sphere is : %.3f", volume);
system("pause");
return 0;
Page 51
6.2 Control structures
Control structures represent the forms by which statements in a program are executed. A control
structure is a block of programming that analyzes variables and chooses a direction in which to go
based on given parameters. The term flow control details the direction the program takes (which way
program control "flows"). Hence it is the basic decision-making process in computing; flow control
determines how a computer will respond when given certain conditions and parameters.
This is the simplest control structure. It dictates the order of execution from one statement to the next
within the program. In the absence of repetition or branching, the program instructions will be
executed in the order in which they were coded.
Basically, program statements are executed in the sequence in which they appear in the program. The
sequence control structure is the default or overriding structure.
The sequence structure indicates instructions are to be executed one statement at a time in the order
they occur from top down unless a different control structure dictates otherwise.
The structure is used for decision making within a program. It allows alternative actions to be taken
according to conditions that exist at particular stages within a program.
The structure uses a test condition statement, which upon evaluation by the computer gives rise to
certain conditions which may evaluate to a Boolean true or false. Based on the outcome of the test
condition, the computer may execute one or more statements.
The if statement
The if statement provides a junction at which the program has to select which path to follow.
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 */
}
Page 52
If expression is true (i.e. non zero) , the statement is executed, otherwise it is skipped. Normally the
expression is a relational expression that compares the magnitude of two quantities ( For example x > y
or c = = 6)
Examples
(i) if (x<y)
Printf (“x is less that y”);
Flow diagram.
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
system(“pause”);
return 0;
}
if - else statement
The if else statement lets the programmer choose between two statements as opposed to the simple if
statement which gives you the choice of executing a statement (possibly compound) or skipping it.
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 */
}
Page 53
else
{
/* statement(s) will execute if the boolean expression is false */
}
If expression is true, statement1 is executed. If expression is false, the single statement following the
else (statement2) is executed. The statements can be simple or compound.
Flow diagram
Example
#include <stdio.h>
main()
{
int i;
printf("Enter a value \n");
scanf("%d",&i);
if (i%2 == 0)
printf("%d - is Even \n", i);
else
printf("%d - is Odd \n", i);
system("pause");
return 0;
}
This is a control structure that is used when more than two choices have to be made. It involves having
IF structure inside another IF structure either in the true or false part.
if (expression 1)
statement 1;
else if (expression 2)
statement 2;
else if (expression 3)
Page 54
statement 3;
-------------
else
statement n;
Flow diagram
(Braces still apply for block statements) In this structure expression 2 is only tested if condition one is
false. Explain how execution of the statements occurs.
Example 1:
/* Program to find roots of a quadratic equation when coefficients are entered by user. */
/* Library function sqrt() computes the square root. */
#include <stdio.h>
#include <math.h> /* This is needed to use sqrt() function.*/
int main()
{
float a, b, c, determinant, r1,r2, real, imag;
printf("Enter coefficients a, b and c:\n");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
}
else if (determinant==0)
{
Page 55
r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
}
else
{
real= -b/(2*a);
imag = sqrt(-determinant)/(2*a);
/* printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag);*/
printf("Roots are: %.2f and %.2f \n", real, imag, real, imag);
}
system("pause");
return 0;
}
Example 2:
#include<stdio.h >
int main()
{
int marks;
printf (" Enter the students marks \n");
scanf( "%d",&marks );
if ( marks >=75 && marks <=100)
{
printf("The grade is A");
}
else if( marks >= 60 && marks < 75 )
{
printf("The grade is B");
}
else if(marks>=50 && marks<60)
{
printf("The grade is C");
}
else if(marks>=40 && marks<50)
{
printf("The grade is D");
}
else if (marks>=0 && marks<40)
{
printf ("The grade is E");
}
else
{
printf("The mark is impossible!" );
}
system ("pause");
return 0;
}
Page 56
The ‘switch’ and ‘break’ statements
The switch - break statements can be used in place of the if - else statements when there are several
choices to be made. The switch structure is used to test if a variable equals some constant values then
executes the equivalent statement.
default: (optional)
statement; (optional)
}
# include <stdio.h>
int main()
{
char o;
float num1,num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
Page 57
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
system("pause");
return 0;
}
Page 58
printf("Day 6 is Friday.\n");
break;
case '7':
printf("Day 7 is Saturday.\n");
break;
default:
printf("The digit is not within the range of 1 to 7.\n");
break;
}
system("pause");
return 0;
}
In many programming problems a sequence of statements or in some cases the entire program may
need to be executed repeatedly a definite or indefinite number of times. The repetition or iteration
control structure is used to control this. In a finite loop the number of iterations is determined and set
by the programmer. In an infinite loop the number of repetitions is dictated by a user or other factors.
The while statement is used to carry out looping instructions where a group of instructions executed
repeatedly until some conditions are satisfied. This is a pretest loop in that the test condition is placed
before the statement block that is to be repeatedly executed. The computer evaluates the test condition
statement and as long as it returns the Boolean value of true the statement block is executed then
control returns to the test condition statement for re-evaluation. Repetition will terminate when the test
condition statement returns false.
Syntax
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Page 59
Example: Calculating the average of n numbers using a ‘while’ loop
Algorithm:
(i) Initialise an integer count variable to 1. It will be used as a loop counter.
(ii) Assign a value of 0 to the floating-point sum.
(iii) Read in the variable for n (number of values)
(iv) Carry out the following repeatedly (as long as the count is less or equal to n).
(v) Read in a number, say x.
(vi) Add the value of x to current value of sum.
(vii) Increase the value of count by 1.
(viii) Calculate the average: Divide the value of sum by n.
(ix) Write out the calculated value of average.
Solution
Page 60
system(“pause”);
return 0;
}
Example 2:
/* counter.c */
/* Displays the digits 1 through 9 */
main()
{
int digit=0, sum=0; /* Initialisation */
while (digit<=9)
{
if (digit %2==0)
{
printf("%d \n", digit);
sum+=digit;
}
digit++;
}
printf("Th sum is %d \n", sum);
system("pause");
return 0;
}
In this structure the test condition is placed after the block of code that is to be repeatedly executed.
The computer first executes the block of code then evaluates the test condition statement.
Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );
Page 61
Example 1:
/* Displays the digits 1 through 9 */
main()
{
int digit=0; /* Initialisation */
do
{
printf(“%d \n”, digit);
digit++;
} while (digit<=9);
system(“pause”);
return 0;
}
Example 2:
#include <stdio.h>
main()
{
int value =0;
do
{ if (value %2 != 0)
{
printf("Value is %d\n", value);
}
value++;
}while(value<=30);
system("pause");
return 0;
}
For loop
Page 62
Syntax
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}
expression1 is used to initialize some parameter (called an index). The index controls the loop action. It
is usually an assignment operator.
expression2 is a test expression, usually comparing the initialised index in expression1 to some
maximum or minimum value.
expression3 is used to alter the value of the parameter index initially assigned by expression and is
usually a unary expression or assignment operator);
Page 63
Example: Averaging a set of numbers using a ‘for’ loop
/* average.c */
/* To add numbers and compute the average */
#include<stdio.h>
main()
{
int n, count;
float x, average, sum=0.0;.
Page 64
{
printf(“x = “);
scanf(“%f”, &x);
sum+=x;
} /* End of inner loop */
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
} /*End of outer loop */
system(“pause”);
return 0;
}
Example: The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<100; i++) {
for(j=2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
system(“pause”);
return 0; }
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.
C supports the following control statements.
Page 65
program.
Break statement
1. When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the case statement.
If you are using nested loops (i.e., one loop inside another loop), 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 1 Break.
Page 66
c = getc(stdin);
if (c=='x')
break;
}
printf("Break the infinite while loop. Bye!\n");
system("pause");
return 0;
}
Continue statement.
The continue statement in C works somewhat like the break statement. Instead of forcing termination,
however, continue forces the next iteration of the loop to take place, skipping any code in between. For
the for-do loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while-do and repeat...until loops, continue statement causes the program control to
pass to the conditional tests.
Syntax:continue;
Flow Diagram
Example 1 Continue.
#include <stdio.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
/* The continue statement is encountered when
* the value of j is equal to 4.
*/
continue;
}
Page 67
/* This print statement would not execute for the
* loop iteration where j ==4 because in that case
* this statement would be skipped.
*/
printf("%d ", j);
}
return 0;
}
Goto statement
A goto statement in C 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 so that it doesn't need the goto.
Syntax
goto label;
...
...
label: statement;
Flow Diagram.
Example 1 Go To Statement.
#include <stdio.h>
int main ()
{
Page 68
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
Revision Exercises
1. A retail shop offers discounts to its customers according to the following rules:
Purchase Amount >= Ksh. 10,000 - Give 10% discount on the amount.
Ksh. 5, 000 <= Purchase Amount < Ksh. 10,000 - Give 5% discount on the amount.
Ksh. 3, 000 <= Purchase Amount < Ksh. 5,000 - Give 3% discount on the amount.
0 > Purchase Amount < Ksh. 3,000 - Pay full amount.
1. Write a program that asks for the customer’s purchase amount, then uses if statements to
recommend the appropriate payable amount. The program should cater for negative purchase
amounts and display the payable amount in each case.
2. In what circumstance is the continue statement used in a C program?
3. Using a nested if statement, write a program that prompts the user for a number and then reports if
the number is positive, zero or negative.
4. Write a while loop that will calculate the sum of every fourth integer, beginning with the integer 3
(that is calculate the sum 3 + 7 +11 + 15 + ...) for all integers that are less than 30.
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design.' A subprogram can be
invoked by a subprogram/program, which is called the calling program.
C provides two kinds of subprograms:
Page 69
Basic Difference Between a function and a procedure.
Function must return a value but in Stored Procedure it is optional( Procedure can return zero
or n values).
Functions can have only input parameters for it whereas Procedures can have input/output
parameters.
Advantages of functions:
1. Program development made easy : Work can be divided among project members thus
implementation can be completed in parallel.
2. Program testing becomes easy : Easy to locate and isolate a faulty function for further
investigation
3. Code sharing becomes possible : A function may be used later by many other programs this
means that a c programmer can use function written by others, instead of starting over from
scratch.
4. Code re-usability increases : A function can be used to keep away from rewriting the same
block of codes which we are going use two or more locations in a program. This is especially
useful if the code involved is long or complicated.
5. Increases program readability : It makes possible top down modular programming. In this
style of programming, the high level logic of the overall problem is solved first while the details
of each lower level functions is addressed later. The length of the source program can be
reduced by using functions at appropriate places.
6. Function facilitates procedural abstraction : Once a function is written, it serves as a black
box. All that a programmer would have to know to invoke a function would be to know its
name, and the parameters that it expects
7. Functions facilitate the factoring of code : Every C program consists of one main( ) function
typically invoking other functions, each having a well-defined functionality.
Scope of variables
Scope of variable refers to the visibility of a variable in a program. A scope is a region of the program
and broadly speaking there are three places, where variables can be declared − Inside a function or a
block which is called local variables, In the definition of function parameters which is called formal
parameters. Outside of all functions which is called global variables.
Local Variables
Are variables declared inside a given procedure and can be accessed or used only in a procedure in
which they are declared. These types of variables are only meaningful inside the procedure. No
statements outside the procedure may reference local variables. A local variable is a variable which is
either a variable declared within the function or is an argument passed to a function. As you may have
encountered in your programming, if we declare variables in a function then we can only use them
within that function.
Page 70
Global Variables
Are variables declared for the entire program. Global variables can be utilized anywhere within the
program block, whether inside of or external to the procedure. Global variable is a variable with global
scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set
of all global variables is known as the global environment or global state. In some languages, all
variables are global, or global by default, while in most modern languages variables have limited scope,
generally lexical scope, though global variables are often available by declaring a variable at the top
level of the program. In other languages, however, global variables do not exist; these are generally
modular programming languages that enforce a module structure, or class-based object-oriented
programming languages that enforce a class structure.
Parameters
A parameter is like a placeholder. A parameter is a special kind of variable, used in a function to refer
to one of the pieces of data provided as input to the subroutine. ... These pieces of data are called
arguments. a parameter or "argument" is a value that is passed into a function. Most modern
programming languages allow functions to have multiple parameters. While the syntax of a function
declaration varies between programming languages, a typical function with two parameters may look
something like this:
function graphXY(x, y)
{
...
}
Types of parameters
Actual parameter - When a function is invoked, you pass a value to the parameter. This value
is referred to as actual parameter or argument. The list of variables or constants after the
procedure name is known as actual parameter.
Formal parameter - The argument(s) that establish the linkage between the calling program
and the function identifiers are called the formal parameters.
Parameter passing
Parameters can either be passed by value or by reference.
a) Pass by Value (Value Parameters).
b) Pass by Reference (Reference/Variable Parameters)
Value parameters – These are ‘one-way’ parameter i.e they can be used to supply information
to a procedure but they cannot be used to get information out of a procedure.This method copies
the actual value of an argument into the formal parameter of the subprogram. In this case,
changes made to the parameter inside the subprogram have no effect on the argument ( Call by
value)
Variable parameter – Are used in applications where information must be transferred in both
directions between the procedure and the procedure reference.This method copies the address of
an argument into the formal parameter. Inside the subprogram, the address is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
argument. (Call by reference)
Page 71
Passing Arguments to main()
main() is passed two arguments from the shell: an integer and a pointer to an array of strings.
Traditionally these are declared as follows:
#include <stdio.h>
#include <stdlib.h> /* for atoi() */
Functions in C
A function is a self-contained program segment that carries out some specific well - defined task.
Every A Function is a group of self-contained statements that can be used to perform a particular
activity or a specific task similar to a procedure. It is used to return a value to the procedure or program
which calls it.
Characteristics of a function
Advantages of Functions
Page 72
Functions can be used repeatedly within a given program.
The function can be used to keep away the tendency to re-write the same block of code in
different program locations.
Types of Functions
User defined
InBuilt.
Inbuilt Functions.
Are functions that have been written and exist as library codes. They can be directly interpreted
by the compiler. The inbuilt functions are normally embodied in certain header files e.g math.h
Examples include sqrt(x), sin(x), cos(x) and pow(x) these to write programs
ABS
– The ABSolute Function returns the absolute value either an integer or real e.g. ABS (-34) returns 34
COS
– The COSine Function returns the cosine value, in radians, of an argumente.g. COS (0) returns 1.0
SIN
– The Sine Function returns the sine value, in radians, of an argument e.g.SIN (60) returns 0.8660
SQRT
– This function returns the square root of a number e.g. SQRT (25) returns5
#include <stdio.h>
int main()
{
int num1,num2,SQUAREROOT;
printf("Enter any number to find the square root\n");
scanf("%d",&num1);
SQUAREROOT=sqrt(num1); //function call
printf("square root is =%d\n",SQUAREROOT);
system("pause");
return 0;
}
C supports a wide range of functions that manipulate null-terminated strings:
Page 73
3 strlen(s1); Returns the length of
string s1.
4 strcmp(s1, s2); Returns 0 if s1
and s2 are the same; less than 0 if
s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch); Returns a pointer
to the first occurrence of
character ch in string s1.
6 strstr(s1, s2); Returns a pointer
to the first occurrence of string s2
in string s1.
Eg1
#include<stdio.h>
#include<string.h>
main()
{
char a[10],dif;
printf("enter your name:");
scanf("%s",&a);
strrev(a);
printf("your name is correct %s\n",a);
system("pause");
return 0;
}
Eg2
#include<stdio.h>
#include<string.h>
main()
{
char str1[80],str2[80],str3[80];
int len;
printf( " Enter a string (less than 80 characters): \n");
gets(str1);
len=strlen(str1);
printf("The length of your name is %d\n",len);
system ("Pause");
return 0;
}
Eg3
#include<stdio.h>
#include<string.h>
#define name "george"
main()
{
Page 74
char str1[10],dif;
printf("enter your name:");
gets(str1);
//scanf("%s",&a);
/*printf("confirm your name:");
scanf("%s",&b);*/
dif = strcmp(str1,name);
if(dif == 0)
printf("your name is correct = %s\n",name);
system("pause");
return 0;
}
Eg4
#include<stdio.h>
#include<string.h>
main()
{
char a[10];
printf("enter your name:");
scanf("%s",&a);
strupr(a);
printf("your name is correct %s\n",a);
system("pause");
return 0;
}
Eg5
#include<stdio.h>
#include<string.h>
main()
{
char a[10],dif;
printf("enter your name:");
scanf("%s",&a);
strlwr(a);
printf("your name is correct %s\n",a);
system("pause");
return 0;
}
Page 75
Suppose, you need to create a circle and color it depending upon the radius and color. You can create
two functions to solve this problem:
createCircle() function
color() function
Defining A Function
Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this case,
the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the function
does.
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
Function declaration is required when you define a function in one source file and you call that function
in another file. In such case you should declare the function at the top of the file calling the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you
will have to call that function to perform the defined task.
Page 76
When a program calls a function, program control is transferred to the called function. A called
function performs defined task, and when its return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
system(“pause”);
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While running final
executable, it would produce the following result:
The following program determines the largest of three integers quantities. The program makes use of a
function that determines the larger of two integer quantities. The overall strategy is to determine the
larger of the first two quantities and then compare the value with the third quantity. The largest quantity
is then displayed by the main part of the program.
Page 77
z = (x > = y )? x : y;
return(z);
}
main()
{
int a , b , c ,d;
/*read the integer quantities*/
printf(“\n a = ”);
scanf(“%d”, &a);
printf(“\n b = ” );
scanf(“%d”, &b);
printf(“\n c = ”);
scanf(“%d”, &c);
/* Calculate and display the maximum value */
d = maximum (a, b);
printf (“\n \n maximum = % d ”, maximum (c ,d));
system(“pause”);
return 0;
}
Function Prototypes
In the previous function examples, the programmer -defined function has always preceded main. Thus
when the programs are compiled, the programmer-defined function will have been defined before the
first function access. However many programmers prefer a top down approach in which main appears
ahead of the programmer-defined function definition. In such a situation, the function access (within
main) will precede the function definition. This can be confusing to the compiler unless the compiler is
first alerted to the fact that the function being accessed will be defined later in the program. A function
prototype is used for this purpose
Function prototypes are usually written at the beginning of a program ahead of any programmer-
defined function (including main) .
The general form of a function prototype is;
Where data_type represents the type of the item that is returned by the function, function_name
represents the name of the function, type 1, type 2, … …., type n represent the types of the arguments 1
to n.
Note that a function prototype resembles the first line of a function definition (although a definition
prototype ends with a semicolon).
Function prototypes are not a must but are desirable however because they further facilitate error
checking between the calls to a function and the corresponding function definition.
The names of the argument within the function prototype need not be declared else where in the
program since these are “dummy” argument names that are recognised only within the prototype. In
Page 78
fact, the argument names can be omitted (though it is not a good idea to do so). However the arguments
data types are essential.
Function prototypes are not mandatory in C. They are desirable however because they further facilitate
error checking between the calls to a function and the corresponding function definition.
E.g 1.
E.g 2
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int cube(int a); //function prototype(declaration)
int main()
{
int num1,num2,sum;
printf("Enter any number to find the cube\n");
scanf("%d",&num1);
sum=cube(num1); //function call
printf("cube of %d = %d\n", num1, sum);
system("pause");
return 0;
}
int cube(int a) //function declarator
{
/* Start of function definition. */
Page 79
int cube;
cube=a*a*a;
return cube; //return statement of function
/* End of function definition. */
}
Recursion is the process by which a function calls itself repeatedly until a special condition is
satisfied.To use recursion, two conditions must be satisfied:
(i) The problem must be written in a recursive form.
(ii) There must be a stopping case (terminating condition).
#include <stdio.h>
int factorial( int i) //unsigned
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{ int i;
printf("Enter an positive integer: ");
scanf("%d",&i);
printf("Factorial of %d is %d\n", i, factorial(i));
system("pause");
return 0;
}
Fibonacci Series
Following is another example, which generates Fibonacci series for a given number using a recursive
function:
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
Page 80
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t", fibonaci(i));
}
system("pause");
return 0; }
The passing by value guarantees that the procedure will not change the value of the parameter.
Generally we use call by value mechanism if we don’t need the changes made in calling function to
reflect in called function. E.g.
#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
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
system("pause");
return 0;
}
Each variable has some fixed address which remains constant throughout execution of program in
memory. Using this address of variable, it is also possible to access and modify the value of variable by
using pointer. But if we required the changes to reflect in called function we use call by reference
mechanism.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
Page 81
int main()
{
7.1 Pointers
A pointer is a secondary data type (also known as derived data type) in C. It is built from one
of the primary data types available in C language. Basically pointer contains memory address
of other variable or function as their value. As pointer deals with memory address, it can be
used to access and manipulate data stored in memory.
A pointer is a variable that holds the memory address of another variable. For example, if a variable
called p contains the address of another variable called q, then p is said to point to q.
Therefore if q were at location 100 in memory, then p would have the value 100.
Pointer is one of the most exciting features of C language and it has added power and
flexibility to the language. Pointer is in C language because it offers following benefits to the
programmers:
Page 82
5. Pointer is an efficient tool for manipulating structures, linked lists, queues stacks etc.
Pointer Declaration
Here, type is the base type of the pointer. The base type specifies the type of the object that the pointer
can point to. Notice that an asterisk precedes the variable name. This tells the computer that a pointer
variable is being created. For example, the following statement creates a pointer to an integer.
int *p;
Pointer Operators
C contains two special pointer operators: * and &. The operator returns the address of the variable it
precedes. The * operator returns the value stored at the address that it precedes. The * pointer operator
has no relationship to the multiplication operator, which uses the same symbol). For example, examine
this short program.
#include<stdio.h>
main()
{
int *p, q;
q = 100; /* assign q 100 */
p = &q; /* assign p the address of q*/
printf(“%d”, *p);/* display q’s value using pointer*/
return 0;
}
First, the line int *p, q; defines two variables: p, which is declared as an integer pointer, and q, which
is an integer. Next, q is assigned the value 100.
In the next line, p is assigned the address of q. You can verbalize the & operator as “address of.“
Therefore, this line can be read as: assign p the address of q. Finally, the value is displayed using the *
operator applied to p. The * operator can be verbalized as “at address”.
Therefore the printf( ) statement can be read as “print the value at address q,” which is 100.
When a variable value is referenced through a pointer, the process is called indirection. It is possible to
use the * operator on the left side of an assignment statement in order to assign a variable a new value
using a pointer to it. For example, this program assigns a value q indirectly using the pointer p.
#include<stdio.h>
Page 83
main()
{
int *p, q;
p = &q; /* get q’s address */
*p = 199; /* assign q a value using a pointer */
printf(“q’s value is %d”, q);
return 0;
}
Note: The type of the variable and type of pointer must match.
(a) Assignment
One can assign an address to a pointer by:
(i) Using an array name or
(ii) Using the address operator
From the previous example, p1 is assigned the address of the beginning of the array which is
cell 234.
Program that uses a for loop that counts from 0 to 9. It puts in the numbers using a pointer.
#include<stdio.h>
main()
{
int i,*p;
p = &i;
for ( i =0; i <10; i++)
printf (“ %d ”, *p);
return 0;
}
Example : Further demonstration of pointers
#include<stdio.h>
main()
{
Page 84
int u1, u2;
int v = 3;
int *pv;
u1 = 2 * ( v + 5 );
pv = &v;
u2 = 2 * (*pv + 5 );
printf(“ \n u1 = %d u2 = %d ”, u1, u2);
return 0;
}
Output
u1 = 16, u2 = 16.
Note
Never use a pointer of one type to point to an object of a different type.
For example:
int q;
float *fp;
fp = &q; /* pointer fp assigned the address of an integer */
fp = 100.23; / address used for assignment */
Do not use a pointer before it has been assigned the address of a variable. May cause program to
crash.
For example:
main()
{
int *p;
*p =10; */Incorrect since p is not pointing to anything */
…
}
#include <stdio.h>
int main()
{
const int a=10; //declare and assign constant integer
int *p; //declare integer pointer
p=&a; //assign address into pointer p
Page 85
return 0;
}
Structures
Suppose you want to write a program that keeps tracks of students [Name, Marks] i.e. a variety of
information to be stored about each student. This requires;
An array of strings (for the Names).
Marks in an array of integers.
Keeping track of many related arrays can be problematic, for example in operations such as sorting all
of the arrays using a certain format.
A data form or type containing both the strings and integers and somehow keep the information
separate is required. Such a data type is called a structure.
What Is A Structure?
A structure is an aggregate data type that is composed of two or more related elements. If we are using
C structure then we are combining different related data types in one group so that we can use and
manage those variables easily.
Unlike arrays, each element of a structure can have its own type, which may differ from the types of
any other elements.
Setting Up A Structure
struct student
{
char name[SIZE];
int marks;
};
The above describes a structure made up of a character array name, and int variable marks.
Explanation
The keyword struct announces to the computer that what follows is a structure data type template.
The tag follows: which is a shorthand label that can be used later to refer to this structure. In the
above example, the tag name is student.
A list of structure members enclosed in a pair of braces. Each member is described by its own
Page 86
declaration. For example; the name portion is a character array of SIZE elements.
Note: Members of a structure can be any data types including other structures.
The structure template doesn’t tell the computer how to represent the data. Having set up the template
we can declare a structure variable as follows;
The computer creates a variable mystudent following the structure template. It allocates space for a
character array of SIZE elements and for an integer variable.
One can declare as many variables of type student as possible. For example,
struct student mystudent, student1, x, y, z; etc.
Note: One can combine the process of defining the structure template and the process of defining
a structure variable as follows;
struct student
{
char name;
int marks;
}mystudent;
Initializing A Structure
Page 87
A structure can be initialized like any other variable - external, static or automatic. This will depend on
where the structure is defined.
Example
static struct student mystudent =
{
“Fred Otieno”,25;
};
Each member is given its own line of initialization and a comma separator, one member initialization
from the next.
Individual structure members are accessed using a period (.) - structure member operator.
For example mystudent.marks which means the marks portion of struct mystudent.
Note: You can use mystudent.marks exactly the way you use other integer variables.
For example, you can use gets(mystudent.name);
or
scanf(“%d”, &mystudent.marks);
Note: Although mystudent is a structure, mystudent.marks is an int type and is like any other integer
variable. Therefore;
The use of scanf(“%d”.........) requires the address of an integer and that is what
&mystudent.marks does.
struct student stud1;, then it is possible to read the name and marks into the variable using the
statements;
gets(stud1.name)
scanf(“%d”, &stud1.marks);
#include<stdio.h>
#define SIZE 40
struct student
{
char name[SIZE];
int marks;
Page 88
};
main()
{
struct student mystudent; /* declare mystudent as a student type */
printf(“Please enter the name of the student \n”);
scanf(“%s”, mystudent.name);
printf(“Enter the marks obtained \n”);
scanf(“%d”, &mystudent.marks);
printf(“%s: got %d “, mystudent.name, mystudent.marks);
system(“pause”);
return 0;
}
Use of Structures
The immediate application that comes to mind is database management. For example, to maintain data
about employees in an organization, books in a library, items in a store, financial transactions in a
company. Their use however, stretches beyond database management. They can be used for a variety of
applications like:
Checking the memory size of the computer.
Hiding a file from a directory
Displaying the directory of a disk.
Interacting with the mouse
Formatting a floppy
Drawing any graphics shape on the screen.
Introduction
Data structure refers to methods of organizing units of data within larger data sets. Achieving
and maintaining specific data structures help improve data access and value. Data structures
also help programmers implement various programming tasks.
A data structure is a format of storing, organizing, transforming and retrieving data in a
computer so that it can be used efficiently.
There are two major categories of data structures:
Arrays
Page 89
Is a kind of data structure that can store a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type.
One-dimensional array
Conceptually you can think of a one-dimensional array as a row, where elements are stored one after
another. One-dimensional array
int num[100];
float temp[20];
char ch[50];
num is an array of type int, which can only store 100 elements of type int.
temp is an array of type float, which can only store 20 elements of type float.
ch is an array of type char, which can only store 50 elements of type char.
The following program uses for loop to take input and print elements of a 1-D array.
1 #include<stdio.h>
2
3 int main()
4 {
5 int arr[5], i;
6
7 for(i = 0; i < 5; i++)
8 {
9 printf("Enter a[%d]: ", i);
10 scanf("%d", &arr[i]);
11 }
12
Page 90
13 printf("\nPrinting elements of the array: \n\n");
14
15 for(i = 0; i < 5; i++)
16 {
17 printf("%d ", arr[i]);
18 }
19
20 // signal to operating system program ran fine
21 return 0;
22 }
Expected Output:
1 Enter a[0]: 11
2 Enter a[1]: 22
3 Enter a[2]: 34
4 Enter a[3]: 4
5 Enter a[4]: 34
6
7 Printing elements of the array:
8
9 11 22 34 4 34
Example 2:
#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
Example 3:
Page 91
C program to find average of N numbers using array
1 #include<stdio.h>
2 main()
3 {
4 int i,j,sum=0,num;
5 float avg;
6 printf("Enter number\n");
7 scanf("%d",&num);
8 int array[num];
9 printf("Enter %d numbers\n",num);
10 for(i=0;i<num;i++)
11 {
12 scanf("%d",&array[i]);
13 sum+=array[i];
14 }
15 avg=(float)sum/num;
16 printf("Average of %d numbers is %f\n",num,avg);
17 }
Example 4:
#include <stdio.h>
int main()
{
int Arr[100], n, i, sum = 0;
return 0;
}
Page 92
1. Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
2. Pop: Removes an item from the stack. The items are popped in the reversed order in which they
are pushed. If the stack is empty, then it is said to be an Underflow condition.
3. Peek or Top: Returns top element of stack.
4. isEmpty: Returns true if stack is empty, else false.
Applications of stack:
Balancing of symbols
Infix to Postfix /Prefix conversion
Redo-undo features at many places like editors, photoshop.
Forward and backward feature in web browsers
Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram
problem.
Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen
problem and sudoku solver
In Graph Algorithms like Topological Sorting and Strongly Connected Components
Implementation:
There are two ways to implement a stack:
Using array
Using linked list
Basic Operations
Page 93
Queue operations may involve initializing or defining the queue, utilizing it, and then completely
erasing it from the memory. Here we shall try to understand the basic operations associated with
queues
Few more functions are required to make the above-mentioned queue operation efficient. These are −
peek() − Gets the element at the front of the queue without removing it.
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or
storing) data in the queue we take help of rear pointer.
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively
difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Page 94
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing and
remove the data after access. The following steps are taken to perform dequeue operation −
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Page 95
Terms
Binary tree
In computer science, a binary tree is a tree data structure in which each node has at most two
children, which are referred to as the left child and the right child.
The basic operations that can be performed on a binary search tree data structure, are the
following −
Page 96
Traversals
A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear data structure,
there is no unique traversal. We will consider several traversal algorithms with we group in the
following two kinds
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one
logical way to traverse them, trees can be traversed in different ways. Following are the
generally used ways for traversing trees.
Example Tree
PreOrder traversal - visit the parent first and then left and right children;
InOrder traversal - visit the left child, then the parent and the right child;
PostOrder traversal - visit left child, then the right child and then the parent;
Page 97
As an example consider the following tree and its
four traversals:
List 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.
Linked List Representation
Linked list can be visualized as a chain of nodes, where every node points to the next node.
As per the above illustration, following are the important points to be considered.
Each link carries a data field(s) and a link field called next.
Each link is linked with its next link using its next link.
Last link carries a link as null to mark the end of the list.
Page 98
Types of Linked List
Following are the various types of linked list.
A doubly linked list is a list that has two references, one to the next node and another to
previous node.
Circular linked list is a linked list where all nodes are connected to form a circle. There is no
NULL at the end. A circular linked list can be a singly circular linked list or doubly circular
linked list.
Basic Operations
Following are the basic operations supported by a list.
Page 99
8.0: sorting and searching
8.1 Searching
Searching is an operation or a technique that helps finds the place of a given element or value in the
list. Any search is said to be successful or unsuccessful depending upon whether the element that is
being searched is found or not. Some of the standard searching technique that is being followed in the
data structure is listed below:
Example:
The list given below is the list of elements in an unsorted array. The array contains ten elements.
Suppose the element to be searched is '46', so 46 is compared with all the elements starting from the
0th element, and the searching process ends where 46 is found, or the list ends.
The performance of the linear search can be measured by counting the comparisons done to find out an
element. The number of comparison is 0(n).
Page 100
algorithm Seqnl_Search(list, item)
Pre: list != ;
Post: return the index of the item if found, otherwise: 1
index <- fi
while index < list.Cnt and list[index] != item //cnt: counter variable
index <- index + 1
end while
if index < list.Cnt and list[index] = item
return index
end if
return: 1
end Seqnl_Search
Binary Search
Binary search is a very fast and efficient searching technique. It requires the list to be in sorted order. In
this method, to search an element you can compare it with the present element at the center of the list.
If it matches, then the search is successful otherwise the list is divided into two halves: one from the
0th element to the middle element which is the center element (first half) another from the center
element to the last element (which is the 2nd half) where all values are greater than the center element.
The searching mechanism proceeds from either of the two halves depending upon whether the target
element is greater or smaller than the central element. If the element is smaller than the central element,
then searching is done in the first half, otherwise searching is done in the second half.
Page 101
8.2 Sorting techniques.
Sorting is the process of arranging data items in a specified order. For example, arranging names of
students in a class in an alphabetical order. The basic operation in Sorting techniques is to compare the
data items of the array with other data items of the array and swap the position of these data items of
the array in a specified order i.e. ascending or descending. Sorting techniques can be implemented
using any programming language, such as C. The following sorting techniques can used to arrange data
items in a specified order:
a) Bubble Sort
b) Insertion Sort
c) Selection Sort
d) Quick Sort
e) Shell Sort
f) Merge Sort etc.
BUBBLE SORT
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Page 102
Implementing Bubble Sort Algorithm
Following are the steps involved in bubble sort(for sorting a given array in ascending order):
1. Starting with the first element(index = 0), compare the current element with the next element of
the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element.
4. Repeat Step 1.
Example
Selection sort is conceptually the simplest sorting algorithm. This algorithm will first find
the smallest element in the array and swap it with the element in the first position, then it will find
the second smallest element and swap it with the element in the second position, and it will keep on
doing this until the entire array is sorted.
Page 103
It is called selection sort because it repeatedly selects the next-smallest element and swaps it into the
right place.
How it Works
Following are the steps involved in selection sort(for sorting a given array in ascending order):
1. Starting from the first element, we search the smallest element in the array, and replace it with
the element in the first position.
2. We then move on to the second position, and look for smallest element present in the subarray,
starting from index 1, till the last index.
3. We replace the element at the second position in the original array, or we can say at the first
position in the subarray, with the second smallest element.
4. This is repeated, until the array is completely sorted.
Example
Let's consider an array with values {3, 6, 1, 8, 4, 5}
Below, we have a pictorial representation of how selection sort will sort the given array.
In the first pass, the smallest element will be 1, so it will be placed at the first position.
Then leaving the first element, next smallest element will be searched, from the remaining elements.
We will get 3 as the smallest, so it will be then placed at the second position.
Page 104
Then leaving 1 and 3(because they are at the correct position), we will search for the next smallest
element from the rest of the elements and put it at third position and keep doing this until array is
sorted.
Insertion Sort Algorithm
Consider you have 10 cards out of a deck of cards in your hand. And they are sorted, or arranged in the
ascending order of their numbers.
If I give you another card, and ask you to insert the card in just the right position, so that the cards in
your hand are still sorted. What will you do?
Well, you will have to go through each card from the starting or the back and find the right position for
the new card, comparing it's value with each card. Once you find the right position, you will insert the
card there.
Similarly, if more new cards are provided to you, you can easily repeat the same process and insert the
new cards and keep the cards sorted too.
This is exactly how insertion sort works. It starts from the index 1(not 0), and each index starting from
index 1 is like a new card, that you have to place at the right position in the sorted subarray on the left.
1. It is efficient for smaller data sets, but very inefficient for larger lists.
2. Insertion Sort is adaptive, that means it reduces its total number of steps if a partially sorted
array is provided as input, making it efficient.
3. It is better than Selection Sort and Bubble Sort algorithms.
4. Its space complexity is less. Like bubble Sort, insertion sort also requires a single additional
memory space.
5. It is a stable sorting technique, as it does not change the relative order of elements which are
equal.
Page 105
How it Work
1. We start by making the second element of the given array, i.e. element at index 1, the key.
The key element here is the new card that we need to add to our existing sorted set of
cards(remember the example with cards above).
2. We compare the key element with the element(s) before it, in this case, element at index 0:
a. If the key element is less than the first element, we insert the key element before the first
element.
b. If the key element is greater than the first element, then we insert it after the first
element.
3. Then, we make the third element of the array as key and will compare it with elements to it's left
and insert it at the right position.
4. And we go on repeating this, until the array is sorted.
Example
Let's consider an array with values {5, 1, 6, 2, 4, 3}
Below, we have a pictorial representation of how bubble sort will sort the given array.
Page 106
As you can see in the diagram above, after picking a key, we start iterating over the elements to the left
of the key.
We continue to move towards left if the elements are greater than the key element and stop when we
find the element which is less than the key element.
And, insert the key element after the element which is less than the key element.
Merge Sort
If we can break a single big problem into smaller sub-problems, solve the smaller sub-problems and
combine their solutions to find the solution for the original big problem, it becomes easier to solve the
whole problem.
Let's take an example, Divide and Rule.
When Britishers came to India, they saw a country with different religions living in harmony, hard
working but naive citizens, unity in diversity, and found it difficult to establish their empire. So, they
adopted the policy of Divide and Rule. Where the population of India was collectively a one big
problem for them, they divided the problem into smaller problems, by instigating rivalries between
local kings, making them stand against each other, and this worked very well for them.
Well that was history, and a socio-political policy (Divide and Rule), but the idea here is, if we can
somehow divide a problem into smaller sub-problems, it becomes easier to eventually solve the whole
problem.
In Merge Sort, the given unsorted array with n elements, is divided into n sub arrays, each
having one element, because a single element is always sorted in itself. Then, it repeatedly merges
these sub arrays, to produce new sorted sub arrays, and in the end, one complete sorted array is
produced.
The concept of Divide and Conquer involves three steps:
Page 107
1. Divide the problem into multiple small problems.
2. Conquer the subproblems by solving them. The idea is to break down the problem into atomic
subproblems, where they are actually solved.
3. Combine the solutions of the subproblems to find the solution of the actual problem.
As we have already discussed that merge sort utilizes divide-and-conquer rule to break the problem into
sub-problems, the problem in this case being, sorting a given array.
In merge sort, we break the given array midway, for example if the original array had 6 elements, then
merge sort will break it down into two subarrays with 3 elements each.
But breaking the orignal array into 2 smaller subarrays is not helping us in sorting the array.
So we will break these subarrays into even smaller subarrays, until we have multiple subarrays
with single element in them. Now, the idea here is that an array with a single element is already sorted,
so once we break the original array into subarrays which has only a single element, we have
successfully broken down our problem into base problems.
And then we have to merge all these sorted subarrays, step by step to form one single sorted array.
Let's consider an array with values {14, 7, 3, 12, 9, 11, 6, 12}
Below, we have a pictorial representation of how merge sort will sort the given array.
Page 108
In merge sort we follow the following steps:
1. We take a variable p and store the starting index of our array in this. And we take another
variable r and store the last index of array in it.
2. Then we find the middle of the array using the formula (p + r)/2 and mark the middle index
as q, and break the array into two subarrays, from p to q and from q + 1 to r index.
3. Then we divide these 2 subarrays again, just like we divided our main array and this continues.
4. Once we have divided the main array into subarrays with single elements, then we start merging
the subarrays.
Page 109
1. Elements less than the Pivot element
2. Pivot element(Central element)
3. Elements greater than the pivot element
Pivot element can be any element from the array, it can be the first element, the last element or any
random element. In this tutorial, we will take the rightmost element or the last element as pivot.
For example: In the array {52, 37, 63, 14, 17, 8, 6, 25}, we take 25 as pivot. So after the first pass, the
list will be changed like this.
{6 8 17 14 25 63 37 52}
Hence after the first pass, pivot will be set at its position, with all the elements smaller to it on its left
and all the elements larger than to its right. Now 6 8 17 14 and 63 37 52 are considered as two separate
sunarrays, and same recursive logic will be applied on them, and we will keep doing this until the
complete array is sorted.
How it Work
1. After selecting an element as pivot, which is the last index of the array in our case, we divide
the array for the first time.
2. In quick sort, we call this partitioning. It is not simple breaking down of array into 2 subarrays,
but in case of partitioning, the array elements are so positioned that all the elements smaller than
the pivot will be on the left side of the pivot and all the elements greater than the pivot will be
on the right side of it.
3. And the pivot element will be at its final sorted position.
4. The elements to the left and right, may not be sorted.
5. Then we pick subarrays, elements on the left of pivot and elements on the right of pivot, and we
perform partitioning on them by choosing a pivot in the subarrays.
Example
consider an array with values {9, 7, 5, 11, 12, 2, 14, 3, 10, 6}
Below, we have a pictorial representation of how quick sort will sort the given array.
Page 110
In step 1, we select the last element as the pivot, which is 6 in this case, and call for partitioning, hence
re-arranging the array in such a way that 6 will be placed in its final position and to its left will be all
the elements less than it and to its right, we will have all the elements greater than it.
Then we pick the subarray on the left and the subarray on the right and select a pivot for them, in the
above diagram, we chose 3 as pivot for the left subarray and 11 as pivot for the right subarray.
And we again call for partitioning.
Page 111
9.0: File handling.
File
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming
language provides access on high level functions as well as low level (OS level) calls to handle file on
your storage devices. It is a collection of bytes stored on a secondary storage device, which is generally
a disk of some kind.
The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and
pages from a textual document; fields and records belonging to a database; or pixels from a graphical
image.
The meaning attached to a particular file is determined entirely by the data structures and operations
used by a program to process the file. It is conceivable (and it sometimes happens) that a graphics file
will be read and displayed by a program designed to process textual data.
The result is that no meaningful output occurs (probably) and this is to be expected.
A file is simply a machine decipherable storage media where programs and data are stored for machine
usage.
It meets the data management needs and requirements of the user, which include
storage of data and the ability to perform the aforementioned operations.
It guarantee, to the extent possible, that the data in the file are valid.
Optimize performance, both from the system point of view in terms of overall
throughput and from the user’s point of view in terms of response time.
It provide I/O support for a variety of storage device types.
It minimize or eliminate the potential for lost or destroyed data.
It provide a standardized set of I/O interface routines to user processes.
It provide I/O support for multiple users, in the case of multiple-user systems
Text files
A text file is a sequence of characters organized into lines. A text file can be a stream of characters that
a computer can process sequentially. It is not only processed sequentially but only in forward direction.
For this reason a text file is usually opened for only one kind of operation (reading, writing, or
appending) at any given time.
Binary files
A binary file is a file stored in binary format. A binary file is computer-readable but not human-
readable. All executable programs are stored in binary files, as are most numeric data files. In contrast,
text files are stored in a form (usually ASCII) that is human-readable.
1. Input and output are much faster using binary data.
Page 112
2. A binary file is usually very much smaller than a text file that contains an equivalent amount of
data.
Binary files can be either processed sequentially or, depending on the needs of the application, they can
be processed using random access techniques. In C Programming Language, processing a file using
random access techniques involves moving the current file position to an appropriate place in the file
before reading or writing data. This indicates a second characteristic of binary files.
They a generally processed using read and write operations simultaneously.
For example, a database file will be created and processed as a binary file. A record update operation
will involve locating the appropriate record, reading the record into memory, modifying it in some way,
and finally writing the record back to disk at its appropriate location in the file. These kinds of
operations are common to many binary files, but are rarely found in applications that process text files.
A source file
Is a sequence of procedures and functions. source code is any collection of computer instructions,
possibly with comments, written using a human-readable programming language, usually as ordinary
text. The source code of a program is specially designed to facilitate the work of computer
programmers, who specify the actions to be performed by a computer mostly by writing source code.
The source code is often transformed by an assembler or compiler into binary machine code understood
by the computer. The machine code might then be stored for execution at a later time. Alternatively,
source code may be interpreted and thus immediately executed.
An object file
is a sequence of bytes organized into blocks that are understandable by the machine. An object file is a
file containing object code, meaning re locatable format machine code that is usually not directly
executable. There are various formats for object files, and the same object code can be packaged in
different object files. An object file may also work like a shared library.
In addition to the object code itself, object files may contain metadata used for linking or debugging,
including: information to resolve symbolic cross-references between different modules, relocation
information, stack unwinding information, comments, program symbols, debugging or profiling
information.
1. FILE *fp;
2. //fp is the name of the file pointer
Page 113
Opening, Creating, Closing
C language provides a number of functions to perform file handling. fopen() is used to create a new file or
open an existing file. The syntax is as follows:
fp is the file pointer that holds the reference to the file, the filename is the name of the file to be opened or
created, and mode specifies the purpose of opening a file such as for reading or writing. FILE is an object
type used for storing information about the file stream.
A file can be opened in different modes. Below are some of the most commonly used modes for opening or
creating a file.
Page 114
3 fscanf() reads data from the file
Example
Page 115
Here is a program that reads a file and displays its contents on screen.
When a file is opened for writing, it will be created if it does not already exist and it will be reset if it
does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to
be a text file.
Here is the program to create a file and write some data into the file.
#include <stdio.h>
int main()
{
FILE *fp;
file = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;
printf("Enter a sentence:\n");
Page 116
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}
Appending (a)
When a file is opened for appending, it will be created if it does not already exist and it will be initially
empty. If it does exist, the data input point will be positioned at the end of the present data so that any
new data will be added to any data that already exists in the file. Using the a indicates that the file is
assumed to be a text file.
Here is a program that will add text to a file which already exists and there is some text in the file.
#include <stdio.h>
int main()
{
FILE *fp
file = fopen("file.txt","a");
fprintf(fp,"%s","This is just an example :)"); /*append some text*/
fclose(fp);
return 0;
}
Outputting to the file
The job of actually outputting to the file is nearly identical to the outputting we have already done to
the standard output device. The only real differences are the new function names and the addition of the
file pointer as one of the function arguments. In the example program, fprintf replaces our familiar
printf function name, and the file pointer defined earlier is the first argument within the parentheses.
The remainder of the statement looks like, and in fact is identical to, the printf statement.
Closing a file
To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in
this simple program, it is not necessary to close the file because the system will close all open files
before returning to DOS, but it is good programming practice for you to close all files in spite of the
fact that they will be closed automatically, because that would act as a reminder to you of what files are
open at the end of each program.
Page 117
10.1 Uses of program documentation
Having this information readily available is invaluable when setting up new environments for an
application and/or maintaining existing ones for development, testing and production. This
documentation should state all the information desired for each environment to include the application
name/version, server name, IP, actual server location if necessary, directory path for the code, URL to
access the application, operating system, user account information, and a point of contact.
Troubleshooting
Having documentation also helps when troubleshooting production issues. An FAQ document can
speed resolution for data issues that come up over and over with previously identified solutions or
workarounds. Most technical issues have error codes that can help with troubleshooting but data errors
sometimes need additional clues as to why something may not be working properly. This is another
type of knowledge gained through time working on an application, but having these documented can
speed up the troubleshooting process, especially for a new developer working on an ongoing project.
Application Installation
Installation and configuration documents are useful for when developers need to set up new or
additional application environments. If possible, the steps should be detailed and easy to follow and can
include screenshots if necessary. Anyone should be able to follow the steps and successfully install an
application. Having the steps identified will help the installer prevent problems because of missing
parts of an application. Details such as necessary software, libraries, and application server versions,
can be included to ensure the environment will be compatible and set up as intended.
Others include
They act as a communication medium between members of the development team in a case where
system re-engineering may be needed.
They are a system information repository to be used by maintenance engineers.
They provide information for management to help them plan, budget and schedule the software
development process.
Some of the documentation should tell users how to use and administer the system.
It describes how to get started and how end-users might make use of the common system facilities.
Page 118
a. Author(s) name, the course name/number, assignment name/number, instructor’s name, and
due date.
b. Detailed description of the problem the program was written to solve, including the
algorithm used to solve the problem.
c. The program’s operational requirements, such as the programming language, special
compilation information, and the input information.
d. Required features of the assignment that author(s) were not able to complete, and/or
information about the existing bugs.
-External documentation would be things like flow charts, UML diagrams, requirements documents,
design documents etc.
E.g. external documentation for a software product might include some of the following
User manual
Online help
Technical addendum
Installation manual
Marketing material
Release Note/Readme
Licensing agreements/Legal docs
Internal Documentation (or in-program documentation): The details of the program are explained
by comments and placed within the code. The internal documentation should minimally include the
following:
a. A ‘block comment’ which should be placed at the head of every method (also known as the
function or subprogram). This will include the method name; the purpose of the method; the
method’s pre– and post–conditions; the method’s return value (if any); and a list of all
parameters, including direction of information transfer (into this method, out from the method
back to the calling method, or both), and their purposes.
b. Meaningful identifier names. Traditionally, simple loop variables may have single letter variable
names, but all others should be meaningful. Never use nonstandard abbreviations. If the
programming language has a naming convention for variables, methods, classes, etc., then those
conventions should be used.
c. Each variable and constant must have a brief comment immediately after its declaration that
explains its purpose. This applies to all variables, as well as to fields of structure declarations.
d. Complex sections of the program that need some more explanations should have comments just
before or embedded in those program sections.
Programming languages have always been heavily influenced by programming paradigms, which in
turn have been characterized by general computing trends.
Programming languages have always been heavily influenced by programming paradigms, which in
turn have been characterized by general computing trends. The cumbersomeness of low-level
machine code yielded imperative programming languages. These languages take advantage of
compilers or interpreters in order to generate low-level machine code based on easier to handle
Page 119
higher-level languages. As a result of increasing complexity and scale of programs, there was a
need for finer granularity and encapsulation of code, which led to new modularization concepts.
This has been later complemented and extended by the object-oriented paradigm, which introduced
new concepts like polymorphism and inheritance. The object-oriented paradigm promotes the
design and implementation of large, but manageable, software systems and thus addresses the
requirements of large-scale applications
Apart from the object-oriented paradigm, there are several less common paradigms such as
declarative or functional programming that focus on high expressiveness. Programming languages
following these paradigms have been considered as esoteric and academic languages by the industry
for a long time. As functional languages favor immutability and side-effect free programming, they
are by design easier to execute concurrently. They also adapt other techniques for handling mutable
state and explicit concurrency.
The gap between imperative, object-oriented languages and purely functional languages has been
bridged by another tendency: multi-paradigm programming languages. By incorporating multiple
paradigms, programming languages allow the developer to pick the right concepts and techniques
for their problems, without committing themselves to a single paradigm. Multi-paradigm languages
often provide support for objects, inheritance and imperative code, but incorporate higher-order
functions, closures and restricted mutability at the same time. Although these languages are not
pure in terms of original paradigms, they propose a pragmatic toolkit for different problems with
high expressiveness and manageable complexity at the same time.
Domain-specific languages allow to specify and express domain objects and idioms as part of a
higher-level language for programming. By providing a higher level of abstraction, domain-specific
languages allow to focus on the application or business domain while concealing details of the
programming language or platform. Several frameworks for web development can be considered as
domain-specific languages for the domain of web applications.
JavaScript has not just become the lingua franca of the web, but also the most widespread
programming language in general. Every browser, even mobile ones, act as an execution
environment for JavaScript applications, thus JavaScript is available on virtually all computing
devices. But JavaScript is also increasingly popular outside the web browser, thanks to projects like
node.js. Microsoft uses JavaScript as the main programming language for Metro applications in the
upcoming Windows 8 release. JavaScript is a multi-paradigm language that incorporates prototypal
object inheritance combined with many functional aspects of Scheme.
Page 120
When Google was dissatisfied with the progress on new JavaScript specifications and was
reasoning about the future of web programming, they identified the need for a general-purpose web
programming language for both clients and servers, independent of JavaScript. This need was
shortly after addressed by Google's new Dart [Tea12] programming language. Dart is derived from
JavaScript, but incorporates several concepts from Java and other languages. It is class-based, like
Java, and supports interfaces, abstract classes and generics. Dart is dynamically typed, but
annotations can be used to enforce static typing. A core library provides common data structures
and operations, and a DOM library supports HTML5 DOM. For server applications, Dart includes
an I/O library with an asynchronous, non-blocking programming model and an event loop. Dart
also ships with an HTTP library as a foundation for web servers. Concerning concurrency in Dart,
the specification disallows shared-state concurrency.
Dart and node.js demonstrate the possibility of natively using the same programming language for
client-side and server-side web application development. Some node.js web framworks already
support the usage of the same functions both for browsers and the server. For example, the same
template rendering functions can be used, both for complete page generation on the server and for
partial updates in the browser. Also RPC-like frameworks have emerged that allow the client-side
application to execute remote operations on the server, entirely using JavaScript.
Other frameworks like the Google Web Toolkit or Vaadin address the desire for a single
programming language by implementing web applications in Java, then generating client-side code
automatically.
Opa is a dedicated approach which takes this idea one step further. Opa combines a new OCaml-
inspired programming language, a web application framework and a runtime platform consisting of
a web server, a database and a distributed execution engine. All parts of a web application can thus
be implemented entirely in Opa, using a single language and a single programming model. For
deployment, the code is automatically sliced into different compiled components: JavaScript code
for the browser, native code for the platform and generated database queries/scripts. The Opa
language focuses on a strong and static type system in order to provide security and to prevent
traditional web security flaws such as SQL injections or cross-site scripting. The platform claims to
provide a scalable architecture based on an event-driven, non-blocking concept and messaging
mechanisms similar to Erlang. Opa also supports distribution by using multiple machines.
The idea is to accept eventual consistency whenever possible, but identify locations where the lack of
strong consistency results in unacceptable consistency bugs. Therefore, they introduce the notion of
consistency as logical monotonicity. Based on the theory of relational databases and logic
Page 121
programming, a program can be defined as monotonic or non-monotonic. A monotonic program
incrementally produces output elements, never revoking them at a later time due to further procressing.
For instance, a projection on a set is a monotonic operation. Instead, non-monotonic operations require
the entire processing to be completed in order to produce outputs. Hence, non-monotonic operations are
blocking operations. Aggregation or negation operations on sets are examples for non-monotonic
operations.
Applied to distributed computing, we can also differentiate monotonic and non-monotonic distributed
operations. Monotonic operations do not rely on message ordering and can tolerate partial delays of
messages. Instead, non-monotonic operations require coordination mechanisms such as sequence
numbers or consensus protocols. For instance, everything that involves distributed counting is a non-
monotonic operation with the need for coordination and waiting. Hellerstein et al. further show that
monotonic operations guarantee eventual consistency, independent of the order of messages, while non-
monotonic operations require coordination principles in order to assure consistency. Based on a
declarative language, consistency behaviors can be analyzed and non-monotonic locations can be
identified automatically. These locations are so-called points of order, that need to be made consistent
by adding coordination logic.
Declarative dataflow programming provides a concurrency model with inherent coordination, entirely
hidden from the developer. Massively parallel data-centric computing frameworks such as
MapReduce [Dea08] have shown the strong points of dataflow programming. However, programming
abstractions like MapReduce heavily constrain the expressiveness compared to pure, non-distributed
dataflow languages. Thus, only a small amount of existing algorithms can be applied for MapReduce-
based computations. Combining an expressive programming model including dataflow concurrency
with a scalable and fault-tolerant distributed execution engine represents a sweet spot for programming
in the large.
Page 122
Complexity of software.
12.0 References
20/01/2019
Page 123