Structured Programming C
Structured Programming C
SYLLABUS
Code Sub-Module Content Total
Theory Practice Total
Unit
1.0 Introduction to -Structured 8 8
structured programming
programming -Types of structured
programming
languages
-History of
programming
languages
-Programming
paradigms
-Hardware and
Software
considerations for
structured
programming.
2.0 Program -Program development 24 24
development and design
-Program development
cycle
-Structured
programming concepts
-Program design tools
3.0 Program -Program Structure 8 8
structure -Format of Structured
programming concepts
-Operators
-Data types.
4.0 Program -Writing a program in 4 28 32
writing C and Pascal
-Error handling
5.0 Control -Control structure 8 24 32
Structure -Importance of Control
Structure
-Types of Control
Structured programming – a technique for organizing and coding computer programs in which a
hierarchy of modules are used, each having a single entry and a single exit point, and in which
control is passed downward through the structure without unconditional branches to higher levels
of the structure.
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.
Systems Software
Systems software includes the programs that are dedicated to managing the computer itself, such as
the operating system, file management utilities, and disk operating system (or DOS). The operating
system manages the computer hardware resources in addition to applications and data. Without
systems software installed in our computers we would have to type the instructions for everything
we wanted the computer to do.
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. When
you begin creating a document, the word processing software has already set the margins, font style
and size, and the line spacing for you. But you can change these settings, and you have many more
formatting options available. For example, the word processor application makes it easy to add
color, headings, and pictures or delete, copy, move, and change the document's appearance to suit
your needs.
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.
Programming Language
Syntax
These are the rules of a language that govern the ways in which words, symbols, expressions and
statements may be formed and combined in that language.
Semantics
These are the rules of language that govern meaning of statements in any language.
Programmer
This is a person who is trained and/or specializes in the technique of creating, maintaining and
modifying computer programs.
Programming Languages
A programming language is a tool for developing executable models for a class of problem domains.
Programming languages provide the basic building block for all software. They are the means by
which people can tell the computer how to carry out a task.
Pascal - A high-level programming language developed by Niklaus Wirth in the late 1960s. The
language is named after Blaise Pascal, a seventeenth-century French mathematician who constructed
one of the first mechanical adding machines. Pascal is best known for its affinity to structured
programming techniques. The nature of the language forces programmers to design programs
methodically and carefully. For this reason, it is a popular teaching language.
Despite its success in academia, Pascal has had only modest success in the business world. Part of
the resistance to Pascal by professional programmers stems from its inflexibility and lack of tools for
developing large applications. To address some of these criticisms, Wirth designed a new language
called Modula-2. Modula-2 is similar to Pascal in many respects, but it contains additional features.
Fortran - Fortran is a programming language mainly used by the scientific community. Its name is a
contraction of FORmula TRANslation, and its aim is to provide a way to tell computers to calculate
complicated mathematical expressions, with more ease than assembly language. FORTRAN is one
of the earliest programming languages. The original versions used punched cards to write programs
with. FORTRAN's age is both a strength and a weakness. On one hand, FORTRAN has a huge
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
Advantages
Program translation was fast because no conversion was required.
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.
They have an extensive vocabulary of words and symbols therefore 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.
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, PASCAL, 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.
An object can be considered a "thing" that can perform a set of related activities. The set of
activities that the object performs defines the object's behavior. For example, the hand can grip
something or a Student (object) can give the name or address.
In essence, the programming language is used to denote the properties, or logic, of a solution, rather
than how it is reached. Most constraint-based and logic programming languages are 5GLs. A
common misconception about 5GLs pertains to the practice of some 4GL vendors to denote their
products as 5GLs, when in essence the products are evolved and enhanced 4GL tools.
PROGRAMMING PARADIGMS.
Programming paradigms are a way to classify programming languages according to the style of
computer programming. Features of various programming languages determine which programming
paradigms they belong to; as a result, some languages fall into only one paradigm, 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. Other paradigms are concerned mainly with the way that code is
organized, such as grouping code into units along with the state that is modified by the code. Yet
others are concerned mainly with the style of syntax and grammar. A programming paradigm is an
approach to solving programming problems.
1) Un structured programming.
2) Structured programming
Structured programming (sometimes known as modular programming) is a subset of procedural
programming that enforces a logical structure on the program being written to make it more
efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBASE are
designed with features that encourage or enforce a logical program structure.
A technique for organizing and coding computer programs in which a hierarchy of modules is used,
each having a single entry and a single exit point, and in which control is passed downward through
the structure without unconditional branches to higher levels of the structure. Three types of control
flow are used: sequential, test, and iteration.
4) 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.
Web programming 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. Web
programming is different from just programming, which requires interdisciplinary knowledge on the
application area, client and server scripting, and database technology.
Web programming can be briefly categorized into client and server coding. The client side needs
programming related to accessing data from users and providing information. It also needs to ensure
there are enough plug ins to enrich user experience in a graphic user interface, including security
measures.
To improve user experience and related functionalities on the client side, JavaScript is usually used.
It is an excellent client-side platform for designing and implementing Web applications.
HTML5 and CSS3 supports most of the client-side functionality provided by other application
frameworks.
- Structured programs written for one system can be run with little or no modification on other
systems.
- There are several Pascal compilers and interpreters available for general use. Among these are:
Turbo Pascal: provides an IDE and compiler for running Pascal programs on CP/M, CP/M-86,
DOS, Windows and Macintosh.
Delphi: provides compilers for running Object Pascal and generates native code for 32- and 64-
bit Windows operating systems, as well as 32-bit Mac OS X and iOS. Embarcadero is planning to
build support for the Linux and Android operating system.
Free Pascal: it is a free compiler for running Pascal and Object Pascal programs. Free Pascal
compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux,
Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms.
- The source code written in source file is the human readable source for your program. It needs to
be "compiled", to turn into machine language so that your CPU can actually execute the program as
per instructions given.
This C programming language compiler will be used to compile your source code into final
executable program. Most frequently used and free available compiler is GNU C/C++ compiler.
Hardware requirements.
Architecture
All computer operating systems are designed for a particular computer architecture. Most software
applications are limited to particular operating systems running on particular architectures. Although
architecture-independent operating systems and applications exist, most need to be recompiled to
run on a new architecture.
Processing power
The power of the central processing unit (CPU) is a fundamental system requirement for any
software. Most software running on x86 architecture define processing power as the model and the
clock speed of the CPU. Many other features of a CPU that influence its speed and power, like bus
speed, cache, and MIPS are often ignored. This definition of power is often erroneous, as AMD
Athlon and Intel Pentium CPUs at similar clock speed often have different throughput speeds. Intel
Pentium CPUs have enjoyed a considerable degree of popularity, and are often mentioned in this
category.
Memory
All software, when run, resides in the random access memory (RAM) of a computer. Memory
requirements are defined after considering demands of the application, operating system, supporting
software and files, and other running processes. Optimal performance of other unrelated software
running on a multi-tasking computer system is also considered when defining this requirement.
Secondary storage
Hard-disk requirements vary, depending on the size of software installation, temporary files created
and maintained while installing or running the software, and possible use of swap space (if RAM is
insufficient).
Display adapter
Software requiring a better than average computer graphics display, like graphics editors and high-
end games, often define high-end display adapters in the system requirements.
Peripherals
Some software applications need to make extensive and/or special use of some peripherals,
demanding the higher performance or functionality of such peripherals. Such peripherals include
CD-ROM drives, keyboards, pointing devices, network devices, etc.
Software requirements
Software development is the process of computer programming, documenting, testing, and bug
fixing involved in creating and maintaining applications and frameworks resulting in 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 Design
Software design is the process by which an agent creates a specification of a software artifact,
intended to accomplish goals, using a set of primitive components and subject to constraints.
Software design may refer to either all the activity involved in conceptualizing, framing,
implementing, commissioning, and ultimately modifying complex systems or the activity following
requirements specification and before programming, as a stylized software engineering process.
Software design usually involves problem solving and planning a software solution. This includes
both a low-level component and algorithm design and a high-level, architecture design.
Cohesion
• Cohesion is the indication of the relationship within module.
• Cohesion shows the module’s relative functional strength.
• Cohesion is a degree (quality) to which a component / module focuses on the single thing.
• While designing you should strive for high cohesion i.e. a cohesive component/ module
focus on a single task (i.e., single-mindedness) with little interaction with other modules of the
system.
• Cohesion is the kind of natural extension of data hiding for example, class having all
members visible with a package having default visibility. Cohesion is Intra – Module Concept.
Coupling
• Coupling is the indication of the relationships between modules.
• Coupling shows the relative dependence/interdependence among the modules.
• Coupling is a degree to which a component / module is connected to the other modules.
• While designing you should strive for low coupling i.e. dependency between modules should
be less
• Making private fields, private methods and non public classes provides loose coupling.
• Coupling is Inter -Module Concept.
2. Design program
The programmer decides how the program will go about its implementation, what should the user
interface be like, how should the program be organized, how to represent the data and what
methods to use during processing. At this point, you should also be thinking generally although
some of your decisions may be based on some general characteristics of the C language.
Types of Testing:-
1. Unit Testing
It focuses on smallest unit of software design. In this we test an individual unit or group of inter
related units. It is often done by programmer by using sample input and observing its corresponding
outputs.
Example:
a) In a program we are checking if loop, method or
function is working fine
b) Misunderstood or incorrect, arithmetic precedence.
c) Incorrect initialization
2. Integration Testing
The objective is to take unit tested components and build a program structure that has been dictated
by design. Integration testing is testing in which a group of components are combined to produce
output.
Integration testing are of two types: (i) Top down (ii) Bottom up
Example
(a) Black Box testing:- It is used for validation.
In this we ignores internal working mechanism and
focuses on what is the output?.
3. Regression Testing
Every time new module is added leads to changes in program. This type of testing make sure that
whole component works properly even after adding components to the complete program.
Example
In school record suppose we have module staff, students and finance combining these modules and
checking if on integration these module works fine is regression testing.
4. Smoke Testing
5. Alpha Testing
This is a type of validation testing.It is a type of acceptance testing which is done before the product
is released to customers. It is typically done by QA people.
Example:
When software testing is performed internally within the organization
6. Beta Testing
The beta test is conducted at one or more customer sites by the end-user of the software. This
version is released for the limited number of users for testing in real time environment
Example:
When software testing is performed for the limited number of people
7. System Testing
In this software is tested such that it works fine for different operating system. It is covered under
the black box testing technique. In this we just focus on required input and output without focusing
on internal working.
In this we have security testing, recovery testing , stress testing and performance testing
Example:
This include functional as well as non functional testing
8. Stress Testing
In this we gives unfavorable conditions to the system and check how they perform in those
condition. Stress testing refers to the testing of software or hardware to determine whether its
performance is satisfactory under any extreme and unfavorable conditions, which may occur as a
result of heavy network traffic, process loading, underclocking, overclocking and maximum requests
for resource utilization.
Example:
(a) Test cases that require maximum memory or other resources are executed
(b) Test cases that may cause thrashing in a virtual operating system
(c) Test cases that may cause excessive disk requirement
9. Performance Testing
It is designed to test the run-time performance of software within the context of an integrated
system. It is used to test speed and effectiveness of program.
Example:
Checking number of processor cycles.
Verification
Verification is the process to make sure the product satisfies the conditions imposed at the start of
the development phase. In other words, to make sure the product behaves the way we want it to.
Validation
Validation is the process to make sure the product satisfies the specified requirements at the end of
the development phase. In other words, to make sure the product is built as per customer
requirements.
Blackbox Testing
Black box testing is a testing technique that ignores the internal mechanism of the system and
focuses on the output generated against any input and execution of the system. It is also called
functional testing.
Whitebox Testing
White box testing is a testing technique that takes into account the internal mechanism of a system.
It is also called structural testing and glass box testing.
Black box testing is often used for validation and white box testing is often used for verification.
Unit Testing
Unit testing is the testing of an individual unit or group of related units. It falls under the class of
white box testing. It is often done by the programmer to test that the unit he/she has implemented
is producing expected output against given input.
Integration Testing
Integration testing is testing in which a group of components are combined to produce output. Also,
the interaction between software and hardware is tested in integration testing if software and
hardware components have any relation. It may fall under both white box testing and black box
testing.
Functional Testing
Functional testing is the testing to ensure that the specified functionality required in the system
requirements works. It falls under the class of black box testing.
Stress Testing
Stress testing is the testing to evaluate how system behaves under unfavorable conditions. Testing is
conducted at beyond limits of the specifications. It falls under the class of black box testing.
Performance Testing
Performance testing is the testing to assess the speed and effectiveness of the system and to make
sure it is generating results within a specified time as in performance requirements. It falls under the
class of black box testing.
Usability Testing
Usability testing is performed to the perspective of the client, to evaluate how the GUI is user-
friendly? How easily can the client learn? After learning how to use, how proficiently can the client
perform? How pleasing is it to use its design? This falls under the class of black box testing.
Acceptance Testing
Acceptance testing is often done by the customer to ensure that the delivered product meets the
requirements and works as the customer expected. It falls under the class of black box testing.
Regression Testing
Regression testing is the testing after modification of a system, component, or a group of related
units to ensure that the modification is working correctly and is not damaging or imposing other
modules to produce unexpected results. It falls under the class of black box testing.
Beta Testing
Beta testing is the testing which is done by end users, a team outside development, or publicly
releasing full pre-version of the product which is known as beta version. The aim of beta testing is
to cover unexpected errors. It falls under the class of black box testing.
Alpha testing
A type of acceptance testing; performed to identify all possible issues/bugs before releasing the
product to everyday users or public. The focus of this testing is to simulate real users by using
blackbox and whitebox techniques. The aim is to carry out the tasks that a typical user might
perform. Alpha testing is carried out in a lab environment and usually the testers are internal
employees of the organization. To put it as simple as possible, this kind of testing is called alpha only
because it is done early on, near the end of the development of the software, and before beta testing.
Top-Down Approach
In this approach an outline program is designed first, showing the main tasks and components of
the program, and the order in which they are to be executed. Each main component is then reduced
to a number of smaller, simple and more manageable components and this process continues at
each level until there is sufficient detail to allow the coding stage to proceed.
The process of reducing components into sequences of smaller components is often referred to a
stepwise refinement and forms the basis of structured programming.
In this design approach, the application is developed starting at the bottom of the hierarchy i.e. the
single task modules. As each category of programs is completed on the hierarchy, the controlling
program for that category is created. It's a long-standing principle of programming style that the
functional elements of a program should not be too large. If some component of a program grows
beyond the stage where it's readily comprehensible, it becomes a mass of complexity which conceals
errors as easily as a big city conceals fugitives. Such software will be hard to read, hard to test, and
hard to debug.
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.
Monolithic programming.
Indicates the program which contains a single function for the large program i.e. monolithic
programming will not divide the program and it is a single thread of execution. When the program
size increases it becomes difficult to maintain. This design approach is highly discouraged due to the
following reasons.
Difficult to check errors on large programs.
Code can be specific to a particular problem i.e. it cannot be re-used.
Algorithms
A programming algorithm is a computer procedure that is a lot like a recipe (called a procedure) and
tells your computer precisely what steps to take to solve a problem or reach a goal. The ingredients
are called inputs, while the results are called the outputs.
An algorithm is a sequence of steps which results to a plan or strategy on how to go about solving a
problem. There are different ways of presenting an algorithm. Some common ways include:-
Pseudocode
Flow charts
Pseudocode
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.
Start
Initialize counter to 1
Enter employee details
Computer pay amount
Print the pay amount
Flowchart In Programming
Different symbols are used for different states in flowchart, For example: Input/Output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart
• Communication: Flowcharts are better way of communicating the logic of a system to all
concerned or involved.
• Effective analysis: With the help of flowchart, problem can be analyzed in more effective way
therefore reducing cost and wastage of time.
• Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy. This will become a pain for the user, resulting in a waste of time and money
trying to correct the problem
• Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely. This will usually waste valuable time.
• Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.
• The main disadvantages are that it does not provide a visual representation of the
programming logic.
• There are no accepted standards for writing the pseudo code. Programmers use their own
styles of writing pseudo code.
• The pseudo code cannot be compiled nor executed and there is no real formative of a syntax
of rules. It is simply one step, an important one, in producing the final code.
Decision Tables
Decision table is a brief visual representation for specifying which actions to perform depending
on given conditions. The information represented in decision tables can also be represented as
decision trees or in a programming language using if-then-else and switch-case statements.
A decision table is a good way to settle with different combination inputs with their corresponding
outputs and also called cause-effect table. Reason to call cause-effect table is a related logical
diagramming technique called cause-effect graphing that is basically used to obtain the decision
table.
Conditions =
(
Printer does not print |Y|Y|Y|Y|N|N|N|N|
A red light is flashing |Y|Y|N|N|Y|Y|N|N|
Printer is unrecognized |Y|N|Y|N|Y|N|Y|N|
)
Actions=
(
Check the power cable | | |x| | | | | |
Check the printer-computer cable |x| |x| | | | | |
Ensure printer software is installed |x| |x| |x| |x| |
Check/replace ink |x|x| | |x|x| | |
Check for paper jam | |x| |x| | | | |
)
Program Structure
The overall form of a program, with particular emphasis on the individual components of the
program and the interrelationships between these components. Programs are frequently referred to
as either well structured or poorly structured. With a well-structured program the division into
components follows some recognized principle such as information hiding, and the interfaces
between components are explicit and simple. By contrast, with a poorly structured program the
division into components is largely arbitrary (or even nonexistent), and interfaces are implicit and
complex.
Operators
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.
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 .
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
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)
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
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.
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.
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
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)
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.
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.
() Functional call
[] Array element reference
-> Indirect member selection
. Direct member selection Left to right
! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion) Right to left
* Multiply
/ Divide
% Remainder Left to right
+ Binary plus(Addition)
- Binary minus(subtraction) Left to right
== Equal to
!= Not equal to Left to right
Simple assignment
= Assign product
*= Assign quotient
/= Assign remainder
%= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift Right to left
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.
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.
Largely known as Record, Struct or Structure in most programming languages, it is the GeneXus
object which allows defining complex data structures. An SDT represents data whose structure is
made up of several elements like a Customer struct. The SDT makes it easy to transfer parameters
(more specifically, they allow providing/using structured information when using web services), it
simplifies XML automatic reading and writing and makes it possible to manage variable-length lists
of elements.
Is a data type that derived from an existing data type. You can use UDTs to extend the built-in types
already available and create your own customized data types.
A structured type is a user-defined data type that has a structure that is defined in the database. It
contains a sequence of named attributes, each of which has a data type. A structured type also
includes a set of method specifications.
I/O Instructions - A statement is a command given to the computer that instructs the computer to
take a specific action, such as display to the screen, or collect input. A computer program is made up
of a series of statements. All C programs are made up of a sequence of instructions. In C,
instructions are also called statements. In the English language, a statement is terminated by a
period, a question mark or an exclamation point. Note that in C language, a statement is terminated
by a semicolon. In the example program above, there is only one statement -- the printf() statement.
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
volatile while char enum static
A typical C program is made of the following components:
Preprocessor directives
Functions
C is a general purpose programming language, unlike other languages such as PASCAL 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.
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.
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
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.
This is an error that occurs during the execution of a program. In contrast, compile-time errors
occur while a program is being compiled. Runtime errors indicate bugs in the program or problems
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.
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 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.
Execution and Program Development - Execution in computer and software engineering is the
process by which a computer or a virtual machine performs the instructions of a computer program.
The instructions in the program trigger sequences of simple actions on the executing machine.
Those actions produce effects according to the semantics of the instructions in the program.
Programs for a computer may execute in a batch process without human interaction, or a user may
type commands in an interactive session of an interpreter. In this case the "commands" are simply
programs, whose execution is chained together. Program development the coding of an individual
software program or to the creation on an entire information system and all related software
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.
The first two stages of compilation are carried out by a part of the compiler known as the parser and
can be referred to as parsing.
The optimized code is then used to generate the object program which is stored on media such as
disk to await 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 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.
Example 1: A simple code that would print the words "Hello World":
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
system(“pause”);
return 0;
}
1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C
compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.
4. The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen. \n creates a new line.
5.System (“pause”) causes the output window remain displayed until the user presses any key. You
can still use getch();
6. The next line return 0; terminates main()function and returns the value 0.
System ("pause") or getch() - Allows the program to stay open long enough for you to see/interact
with it. The program closes immediately upon executing it and thus some compilers need you to add
that statement before return 0 ;
Sample Program 2
This program will print out the message: This is a C program.
#include<stdio.h>
main()
main() declares the start of the function, while the two curly brackets show the start and finish of the
function. Curly brackets in C are used to group statements together as in a function, or in the body
of a loop. Such a grouping is known as a compound statement or a block.
printf("This is a C program \n"); prints the words on the screen. The text to be printed is enclosed
in double quotes. The \n at the end of the text tells the program to print a new line as part of the
output.
Most C programs are in lower case letters. You will usually find upper case letters used in
preprocessor definitions (which will be discussed later) or inside quotes as parts of character strings.
Functions
All C programs consist of one or more functions, each of which contains one or more statements.
In C, a function is a named subroutine that can be called by other parts of the program. Functions
are the building blocks of C.
A statement specifies an action to be performed by the program. In other words, statements are
parts of your program that actually perform operations.
All C statements must end with a semicolon. C does not recognize the end of a line as a terminator.
This means that there are no constraints on the position of statements within a line. Also you may
place two or more statements on one line.
Although a C program may contain several functions, the only function that it must have is main ().
The main( ) function is the point at which execution of your program begins. That is, when your
program begins running, it starts executing the statements inside the main( ) function, beginning
with the first statement after the opening curly brace. Execution of your program terminates when
the closing brace is reached.
One of the most common library functions is called printf( ). This is C’s general purpose output
function. Its simplest form is
printf(“string – to – output”);
The printf( ) outputs the characters that are contained between the beginning and ending double
quotes.
For example, printf(“ This is a C program “);
Note:
Since the main function does not return any value, line 3 can alternatively be written as : void main( )
– void means valueless. In this case, the statement return 0; is not necessary.
While omitting the keyword int to imply the return type of the main( ) function does not disqualify
the fact that an integer is returned (since int is default), you should explicitly write it in other
functions, especially if another value other than zero is to be returned by the function.
A preprocessor directive performs various manipulations on your source file before it is actually
compiled. Preprocessor directives are not actually part of the C language, but rather instructions
from you to the compiler
The preprocessor directive #include is an instruction to read in the contents of another file and
include it within your program. This is generally used to read in header files for library functions.
Header files contain details of functions and types used within the library. They must be included
before the program can make use of the library functions.
Library header file names are enclosed in angle brackets, < >. These tell the preprocessor to look for
the header file in the standard location for library definitions.
Comments
Comments are non – executable program statements meant to enhance program readability and
allow easier program maintenance, i.e. they document the program. They can be used in the same
line as the material they explain (see lines 4, 6, 7 in sample program).
A long comment can be put on its own line or even spread on more than one line. Comments are
however optional in a program. The need to use too many comments can be avoided by good
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()
{
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.
Variables in programming.
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];
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
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;
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
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.
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.
1) 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.
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
#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);
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.
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.
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;
}
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;
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;
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.
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
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.
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.
(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)
{
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 >
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.
# 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);
You can specify a range of consecutive values in a single case label, like this:
case low ... high:
It can be used for ranges of ASCII character codes like this:
case 'A' ... 'Z':
You need to Write spaces around the ellipses … . For example, write this:
// Correct - case 1 ... 5:
// Wrong - case 1...5:
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.
Algorithm:
Initialise an integer count variable to 1. It will be used as a loop counter.
Assign a value of 0 to the floating-point sum.
Read in the variable for n (number of values)
Carry out the following repeatedly (as long as the count is less or equal to n).
Read in a number, say x.
Add the value of x to current value of sum.
Increase the value of count by 1.
Calculate the average: Divide the value of sum by n.
Write out the calculated value of average.
Solution
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 );
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;
}
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);
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; }
CONTROL STATEMENTS:
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.
Pascal supports the following control statements.
1) Break 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.
2) 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.
main()
{
int i, sum;
sum = 0;
for (i=1; i<8; i++){
if ((i==3) || (i==5))
continue;
sum += i;
}
printf("The sum of 1, 2, 4, 6, and 7 is: %d\n", sum);
system("pause");
return 0;
}
3) 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;
...
In C programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier.
When, the control of program reaches to goto statement, the control of the program will jump to
the label: and executes the code below it.
Flow Diagram.
#include <stdio.h>
int main ()
{
/* 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;
}
Note:
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced
as much as possible in a program.
• Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled.
• In modern programming, goto statement is considered a harmful construct and a bad
programming practice.
• The goto statement can be replaced in most of C program with the use of break and
continue statements.
• In fact, any program in C programming can be perfectly written without the use of goto
statement.
• All programmer should try to avoid goto statement as possible as they can.
When we use break, continue and goto statements, we must follow the following...
Pattern programs in C
Pattern programs in C language, showing how to create various patterns of numbers
and stars. The programs require nested loops (a loop inside another loop). A design of
numerals, stars, or characters is a way of arranging these in some logical manner, or
they may form a sequence. Some of these are triangles that have particular importance
in mathematics. Some patterns are symmetrical, while others are not. See the complete
page for all of them.
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
#include <stdio.h>
int main() {
int i, j;
char input, alphabet = 'A';
printf("Enter an uppercase character you want to print in the last row: ");
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i) {
for (j = 1; j <= i; ++j) {
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
#include <stdio.h>
#include <stdio.h>
int main() {
int rows, i, j, number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
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.
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.
In what circumstance is the continue statement used in a C program?
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.
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.
Data structure
A data structure is a particular way of organizing data in a computer so that it can be used efficiently.
Different kinds of data structures are suited to different kinds of applications, and some are highly
specialized to specific tasks. Data structures can implement one or more particular abstract data
types (ADT), which specify the operations that can be performed on a data structure and the
computational complexity of those operations. In comparison, a data structure is a concrete
implementation of the specification provided by an ADT.
Different kinds of data structures are suited to different kinds of applications, and some are highly
specialized to specific tasks. For example, relational databases commonly use B-tree indexes for data
retrieval, while compiler implementations usually use hash tables to look up identifiers
Data structure is a way to organize a data in computer so that it can be used efficiently.
In computer science, Data Structure is classified into two categories :
Linear Data Structure
Non Linear Data Structure
Non Linear Data Structures: The data structure where data items are not organized sequentially is
called non linear data structure. In other words, A data elements of the non linear data structure
could be connected to more than one elements to reflect a special relationship among them. All the
data elements in non linear data structure can not be traversed in single run.
Examples of non linear data structures are Trees and Graphs, Decision Trees
A tree is collection of nodes where these nodes are arranged hierarchically and form a parent child
relationships. A Graph is a collection of a finite number of vertices and an edges that connect these
vertices. Edges represent relationships among vertices that stores data elements.
Every item is related to its previous and next Every item is attached with many other
item. items.
Data items can be traversed in a single run. Data can not be traversed in a single run.
Homogeneous data: Homogeneous data structures are those data structures that contain only similar
type of data e.g. like a data structure containing only integer or float values. The simplest example of
such type of data structures is an Array.
Heterogeneous Data: Heterogeneous Data Structures are those data structures that contains a variety
or dissimilar type of data, for e.g. a data structure that can contain various data of different data
types like integer, float and character. The examples of such data structures include structures,
union.
1)BINARY TREE
A tree is a non-linear data structure that consists of a root node and potentially many levels of
additional nodes that form a hierarchy. A tree can be empty with no nodes called the null or empty
tree or a tree is a structure consisting of one node called the root and one or more subtrees.
A binary tree is a tree data structure in which each node has at most two children (referred to as the
left child and the right child). In a binary tree, the degree of each node can be at most two.
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Uses of Inorder
In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get
nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder itraversal s
reversed, can be used.
Example: Inorder traversal for the above given figure is 4 2 5 1 3.
Preorder Traversal: Pre - Order Traversal ( root - leftChild - rightChild )
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Besides the parent-child relationship, we can think of tree nodes having ancestors and
descendants. An ancestor of a node is any other node on the path from the node to the root. •
A descendant is the inverse relationship of ancestor: A node p is a descendant of a node q if and
only if q is an ancestor of p.
Forest is a collection of disjoint trees. In other words, we can also say that forest is a collection of an
acyclic graph which is not connected. Here is a pictorial representation of a forest.
A set (usually ordered) of 0 or more disjoint trees, or equivalently: the nodes of a tree excluding the
root.
The number of sub trees of a node is called the degree of the node. In a binary tree, all nodes
have degree 0, 1, or 2. A node of degree zero is called a terminal node or leaf node. A non-leaf
node is often called a branch node.
A level is the number of parent nodes corresponding to a given a node of the tree. It is basically
the number of ancestors from that node until the root node. So, for the root node (topmost
node), it's level is 0, since it has no parents.
2) RECORD
A record is a data structure that contains other values, typically in fixed number and sequence and
typically indexed by names. The elements of records are usually called fields or members.Records are
2 or more variables of different types in one.
program Types;
Type StudentRecord = Record Number: Integer;
Name: String;
end;
var Student: StudentRecord;
begin
Student.Number := 12345;
Student.Name := 'John Smith';
end.
3) LINKED LIST
A linked list is a linear data structure where each element is a separate object. Each element (we will
call it a node) of a list is comprising of two items - the data and a reference to the next node. The
last node has a reference to null. The entry point into a linked list is called the head of the list.
As per the above illustration, following are the important points to be considered.
Linked List contains a link element called first.
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.
Types of Linked List
Following are the various types of linked list.
Simple Linked List − Item navigation is forward only.
Doubly Linked List − Items can be navigated forward and backward.
Circular Linked List − Last item contains link of the first element as next and the first element has a
link to the last element as previous.
Basic Operations
Following are the basic operations supported by a list.
Insertion − Adds an element at the beginning of the list.
Deletion − Deletes an element at the beginning of the list.
Display − Displays the complete list.
Search − Searches an element using the given key.
Delete − Deletes an element using the given key.
Advantages
Linked lists are a dynamic data structure, which can grow and be pruned, allocating and deallocating
memory while the program is running.
Insertion and deletion node operations are easily implemented in a linked list.
4) QUEUE
Queue Data Structures
Queue is also an abstract data type or a linear data structure, in which the first element is inserted
from one end called REAR(also called tail), and the deletion of exisiting element takes place from
the other end called as FRONT(also called head). This makes queue as FIFO data structure, which
means that element inserted first will also be removed first.
The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.
Applications of Queue
Queue, as the name suggests is used whenever we need to have any group of objects in an order in
which the first one coming in, also gets out first while the others wait for there turn, like in the
following scenarios :
Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until
a service representative is free.
Handling of interrupts in real-time systems. The interrupts are handled in the same order as they
arrive, First come first served.
Applications of Queue Data Structure
Queue is used when things don’t have to be processed immediatly, but have to be processed in First
In First Out order like Breadth First Search. This property of Queue makes it also useful in
following kind of scenarios.
1) When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk
Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes. Examples include IO Buffers, pipes, file IO, etc.
A queue is a particular kind of abstract data type or collection in which the entities in the collection
are kept in order and the principal operations on the collection are the addition of entities to the rear
terminal position, known as enqueue, and removal of entities .
A stack is a particular kind of abstract data type or collection in which the principal operations on
the collection are the addition of an entity to the collection, known as push and removal of an entity,
known as pop. The relation between the push and pop operations is such that the stack is a Last-In-
First-Out (LIFO) data structure. In a LIFO data structure, the last element added to the structure
must be the first one to be removed.
For historical reasons the operation of adding items to a stack is called push. For similar reasons the
operation of removing an item from a stack is usually referred to as pop.
There are a couple more operations that we must consider before we attempt to implement a stack.
The first of these is an operation called init. This initialises the stack, and ensures that state of the
software is in a known condition before we try to use it. Just about every structure that we will ever
use will require an initialisation routine - get into the habit of writing the outline of the init operation
first!
As this is a course in developing software, we must also consider the possibility of errors. The easiest
error to envisage for a stack is when a program tries to remove an item from an empty stack. This
condition is called overflow, and if undetected will probably cause a series of mysterious errors
before the program crashes. The method that we use to detect this problem is to use an operation
called isEmpty to tell us if the stack is empty. If we try and take data from an empty stack the error
condition is usually called underflow. Similarly there is a possibility that we might run out of space. To
counter this we can provide an operation called isFull.
Using this analysis we can conclude that we need to provide five operations to implement a stack.
These operations are:
1. init
2. isEmpty
3. isFull
4. push
5. pop
If we can satisfactorily implement these operations we have implemented a stack. Note that we do
not have to say at this stage exactly how these operations are implemented, or exactly how the data
is held. There is more than one way of implementing a stack. In this Unit we are going to consider
how to implement a stack using an array.
Stack 3 11 1
2 2 5 5 55 55 56
6) FILE.
A file is a large organised data structure that contains related data such as recorwds . A file
information data structure (INFDS) can be defined for each file to make file exception/error and
file feedback information available to the program. The file information data structure, which must
be unique for each file, must be defined in the main source section. The same INFDS is used by all
procedures using the files.
7)GRAPH.
A graph is a pictorial representation of a set of objects where some pairs of objects are connected by
links. The interconnected objects are represented by points termed as vertices, and the links that
connect the vertices are called edges.
A graph is an abstract data type that is meant to implement the graph and hypergraph concepts from
mathematics. A graph data structure consists of a finite set of ordered pairs, called edges or arcs, of
certain entities called nodes or vertices.
9)SET.
A set is an abstract data structure that can store certain values, without any particular order, and no
repeated values. It is a computer implementation of the mathematical concept of a finite set. ...
Intersection,Conjunction,AND.
Union,Disjoint,OR,v,
10. STRING
A string is traditionally a sequence of characters, either as a literal constant or as some kind of
variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed
(after creation). A string is generally understood as a data type and is often implemented as an array
of bytes (or words) that stores a sequence of elements, typically characters, using some character
11. POINTERS.
A pointer is a programming language object, whose value refers to (or "points to") another value
stored elsewhere in the computer memory using its memory address. A pointer references a location
in memory, and obtaining the value stored at that location is known as dereferencing the pointer. As
an analogy, a page number in a book's index could be considered a pointer to the corresponding
page; dereferencing such a pointer would be done by flipping to the page with the given page
number.
Pointers to data significantly improve performance for repetitive operations such as traversing
strings, lookup tables, control tables and tree structures. In particular, it is often much cheaper in
time and space to copy and dereference pointers than it is to copy and access the data to which the
pointers point.
Pointers are also used to hold the addresses of entry points for called subroutines in procedural
programming and for run-time linking to dynamic link libraries (DLLs). In object-oriented
programming, pointers to functions are used for binding methods, often using what are called virtual
method tables.
What Is A Pointer?
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:
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>
main()
{
int *p, q;
p = &q; /* get q’s address */
Note: The type of the variable and type of pointer must match.
Assignment
One can assign an address to a pointer by:
Using an array name or
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()
{
int u1, u2;
int v = 3;
int *pv;
u1 = 2 * ( v + 5 );
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 */
…
}
10) ARRAYS.
An array is an aggregate data structure that is designed to store a group of objects of the same types.
Arrays can hold primitives as well as references. The array is the most efficient data structure for
storing and accessing a sequence of objects.
ARRAYS EXPLANATION.
An array is a collection of data items of similar data type. It’s a composite object;it is composed of
several elements with independent values all of which have the same type. The independent values
are called the elements of an array and they are stored in separate cells. Each cell of an array is
assigned an index or a subscript. An array can be:
What Is An Array?
An array is a data structure that consists of a homogeneous ordered set of elements or a series of
data objects of the same type stored sequentially. That is to say that an array has the following
characteristics;
Illustration examples:
age
An array of 10 student ages (stored as integers)
22 19 20 21 21 22 23 10 19 20
letters
An array of 5 characters in an employee’s name
O K O T H
Declaring Arrays
An array definition comprises;
Storage class (optional)
Data type
Array name
Arraysize expression (usually a positive integer or symbolic constant). This is enclosed in square
brackets.
Syntax:
Array_type array_name[maximum size];
Examples:
Because the array is declared as type float, each element can be assigned a float value such as
debts[5] = 32.54;
Other examples;
int emp_no[15]; /*An array to hold 15 integer employee numbers */
char alpha [26]; /*an array to hold 26 characters */
An array’s dimension is the number of indices required to manipulate the elements of the array.
A one-dimensional array requires a single index e.g. int numbers [10];
Resembles a single list of values and therefore requires a single index to vary between 0 to (array size
-1).
Multi dimensional arrays
They are defined the same way as a one-dimensional array except that a separate pair of square
brackets is required for each subscript. Thus a two-dimensional array will require two pairs of
brackets, a three dimensional array will require three pairs of square brackets, etc.
float table[50][50];
char page[24][80];
Static double records[100][60][255];
Example
Two-dimensional array representing sales ( ‘000 tonnes for a product in four months for five years).
Yr1 Yr2 Yr3 Yr4 Yr5
Month 1 23 21 27 23 22
Month 2 24 20 19 18 20
Month 3 26 23 26 29 24
Month 4 27 25 24 23 25
Arrays, like simple variables can be automatic, external or static.
Automatic array
An automatic array is one defined inside a function including formal arguments. C allows us to
initialise automatic array variables as follows.
Because the array is defined inside main, its an automatic array. The first element marks[0] is
assigned the value of 30 , marks[1] as 40 and so on.
External array
An external array is one defined outside a function.
They
are known to all functions following them in a file e.g. from above, both main ( ) and feed ( ) can
use and modify the array SOWS.
Persist (retain values) as long as the program runs. Because they are not defined in any particular
function, they don’t expire when a particular function terminates.
int feed(int n)
{
---------
---------
}
Static array
A static array is local to the function in which it is declared but like an external array, it retains its
values between function calls and is inititialised to zero by default.
Example
Initializing Arrays
Like other types of variables, you can give the elements of arrays initial values. This is accomplished
by specifying a list of values the array elements will have. The general form of array initialisation for
a one-dimensional array is shown below.
The value list is a comma separated list of constants that are type compatible with the base type of
the array. The first constant will be placed in the first position of the array, the second constant in
the second position and so on. Note that a semi colon follows the }.
In the following example, a five – element integer array is initialised with the squares of the number
1 though 5.
This means that i[0] will have the value 1 and i[4] will have the value 25.
You can initialise character arrays in two ways. First, if the array is not holding a
null -terminated string, you simply specify each character using a comma separated list. For
example, this initialises a with the letters ‘A’, ‘B’, and ‘C’.
If the character array is going to hold a string, you can initialise the array using a quoted string, as
shown here.
Notice that no curly braces surround the string. They are not used in this form of initialisation.
Because strings in C must end with a null, you must make sure that the array you declare is long
enough to include the null. This is why name is 6 characters long, even though “Peter” is only 5
characters. When a string constant is used, the compiler automatically supplies the null terminator.
EXAMPLES OF 1D ARRAY.
E.g 1
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{ n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
E.g 2
#include<stdio.h>
main()
{
char str1[80],str2[80];
printf( " Enter your name: \n");
gets(str1);
printf( " Enter your home county: \n");
gets(str2);
printf("Your name is %s\n",str1);
printf("Your home county is %s\n",str1);
system ("Pause");
return 0;
}
E.g 3
#include<stdio.h>
#define MONTHS 12
int days [MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31};
main()
{
int index;
extern int days[];
for(index=0; index <MONTHS; index ++)
printf( "Month %d has %d days. \n ", index+1, days [index]);
getch();
/*system("Pause");*/
return 0;
}
For example, here the array sqr is initialised with the values 1 though 9, using row order.
This initialisation causes sqr[0][0] to have the value 1, sqr[0][1] to contain 2, sqr[0][2] to contain 3,
and so forth.
If you are initialising a one-dimensional array, you need not specify the size of the array, simply put
nothing inside the square brackets. If you don’t specify the size, the compiler simply counts the
number of initialisation constants and uses that that value as the size of the array.
For example int p[] = {1,2,4,8,16,32,64,128}; causes the compiler to create an initialised array eight
elements long.
Arrays that don’t have their dimensions explicitly specified are called unsized arrays. An unsized
array is useful because it is easier for you to change the size of the initialisation list without having
to count it and then change the array dimension. This helps avoid counting errors on long lists,
which is especially important when initialising strings.
If at a later date, you wanted to change the prompt to “Enter your last name: “ , you would not
have to count the characters and then change the array size.
For multi dimensional arrays, you must specify all but the left dimension to allow C to index the
array properly. In this way you may build tables of varying lengths with the compiler allocating
enough storage for them automatically.
For example, the declaration of sqr as an unsized array is shown here.
int sqr[][3] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
The advantage to this declaration over the sized version is that tables may be lengthened or
shortened without changing the array dimensions.
EXAMPLES OF 2D ARRAY.
E.g 1
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
E.g 2
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2];
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
system("Pause");
return 0;
}
Sorting is the process of arranging a collection of data in order. Sorting can alsobe defined as the
process of arranging data items in a specified order. Forexample, arranging names of students in a
class in an alphabetical order. The numerical data can be arranged in increasing or decreasing order
andcharacter data can be arranged alphabetically.
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
itemsof the array in a specified order i.e. ascending or descending. Sorting techniques can be
implemented using any programming language, such as Pascal. The following sorting techniques can
used to arrange data items in a specifiedorder:
a)Bubble Sort
b)Insertion Sort
c)Selection Sort
d)Quick Sort
e)Shell Sort
f)Merge Sort etc.
BUBBLE SORT
This is the simplest sorting algorithm. The bubble sort is a sorting technique that keeps comparing
the two adjacent data items of an array and swaps them in a specified order repeatedly until the
whole array has been sorted.
How It Works
This technique starts with comparing the first two data items of the array andswaps them if they are
not in a specified order. After sorting the first two dataitems of the array, the next two data items are
compared and swapped, if they arenot in order. This process continues until all the data items of the
Algorithm
We assume list is an array of n elements. We further assume that swapfunction swaps the values of
the given array elements.
begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
Pseudo code
We observe in algorithm that Bubble Sort compares each pair of array element unless the whole
array is completely sorted in an ascending order. This may cause a few complexity issues like what if
the array needs no more swapping as all the elements are already ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap has
happened or not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it
will come out of the loop.
Pseudocode of BubbleSort algorithm can be written as follows −
Example 1
#include<stdio.h>
main()
{
int item[100];
{
/* Compare adjacent items */
if (item[b -1] > item[b])
/* exchange the elements */
{
t = item[b - 1];
item[b - 1] = item[b];
item[b] = t;
}
}
/* Display sorted list */
for(t = 0; t < count; t++)
printf(" %d ", item[t]);
system ("Pause");
return 0;
}
INSERTION SORT
This is simple but inefficient sorting algorithm. The Insertion sort is a sorting technique that picks a
data item of an array and then inserts it in the correct position in another array.In insertion sort, an
array is divided into two sub-arrays. The first keeps only the sorted data items and the second sub-
array keeps remaining unsorted data items. The data item is moved from the second sub-array to the
How It Works
This technique starts with selecting the first data item of the array from theunsorted list and then
places it in the other (sorted) list. The data items aresequentially selected from the unsorted list and
placed at the appropriate positionin the other (sorted) list. This process continues until all the data
items of thearray are sorted in a specified order.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we can derive simple steps
by which we can achieve insertion sort.
Insertion sort(a[],n)
for j->2 to n
do key <-a[j]
i<-j-1
while i>=0 and a[i]>key
do a[i+1]<-a[i]
i<-i+1
a[i+1]<-key
end
1. selectionSort(array, size)
2. repeat (size - 1) times
3. set the first unsorted element as the minimum
4. for each of the unsorted elements
5. if element < currentMinimum
6. set element as new minimum
7. swap minimum with first unsorted position
8. end selectionSort
Algorithm
Pseudocode
Quick Sort.
In this method, an element called pivot is identified and that element is fixed in its place by moving
all the elements less than that to its left and all the elements greater than that to its right.
Shellsort.
Algorithm
Following is the algorithm for shell sort.
Pseudocode
Following is the pseudocode for shell sort.
procedure shellSort()
A : array of items
/* calculate interval*/
while interval < A.length /3 do:
interval = interval * 3 + 1
end while
Merge sort is a sorting algorithm that sorts data items into ascending or descending order, which
comes under the category of comparison-based sorting. Here we apply the divide-and-conquer
strategy to sort a given sequence of data items, which can be described as follows:
1. Recursively split the sequence into two halves (i.e. subsequences) until the subsequence contains
only a single data item (i.e. singleton subsequence).
2. Now, recursively merge these subsequences back together preserving their required order (i.e.
ascending or descending order).
-In computer science, merge sort (also commonly spelled merge sort) is an O(n log n) based sorting.
Most implementations produce a stable sort, which means that the implementation preserves the
input order of equal elements in the sorted output. Merge sort is a divide and conquer algorithm that
was invented by John von Neumann in 1945.
Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out two main
functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.
Heapsort
Is a comparison-based sorting algorithm. Heapsort is part of the selection sort family; it improves on
the basic selection sort by using a logarithmic-time priority queue rather than a linear-time search.
Although somewhat slower in practice on most machines than a well-implemented quicksort, it has
the advantage of a more favorable worst-case O(n log n) runtime.
Bubble Sort
The bubble sort algorithm works by repeatedly swapping adjacent elements that are not in order
until the whole list of items is in sequence. In this way, items can be seen as bubbling up the list
according to their key values.
The primary advantage of the bubble sort is that it is popular and easy to implement. Furthermore,
in the bubble sort, elements are swapped in place without using additional temporary storage, so the
space requirement is at a minimum. The main disadvantage of the bubble sort is the fact that it does
not deal well with a list containing a huge number of items. This is because the bubble sort requires
n-squared processing steps for every n number of elements to be sorted. As such, the bubble sort is
mostly suitable for academic teaching but not for real-life applications.
Selection Sort
The selection sort works by repeatedly going through the list of items, each time selecting an item
according to its ordering and placing it in the correct position in the sequence.
The main advantage of the selection sort is that it performs well on a small list. Furthermore,
because it is an in-place sorting algorithm, no additional temporary storage is required beyond what
is needed to hold the original list. The primary disadvantage of the selection sort is its poor
efficiency when dealing with a huge list of items. Similar to the bubble sort, the selection sort
requires n-squared number of steps for sorting n elements. Additionally, its performance is easily
influenced by the initial ordering of the items before the sorting process. Because of this, the
selection sort is only suitable for a list of few elements that are in random order.
Insertion Sort
The insertion sorts repeatedly scans the list of items, each time inserting the item in the unordered
sequence into its correct position.
The main advantage of the insertion sort is its simplicity. It also exhibits a good performance when
dealing with a small list. The insertion sort is an in-place sorting algorithm so the space requirement
Quick Sort
The quick sort works on the divide-and-conquer principle. First, it partitions the list of items into
two sublists based on a pivot element. All elements in the first sublist are arranged to be smaller than
the pivot, while all elements in the second sublist are arranged to be larger than the pivot. The same
partitioning and arranging process is performed repeatedly on the resulting sublists until the whole
list of items are sorted.
The quick sort is regarded as the best sorting algorithm. This is because of its significant advantage
in terms of efficiency because it is able to deal well with a huge list of items. Because it sorts in place,
no additional storage is required as well. The slight disadvantage of quick sort is that its worst-case
performance is similar to average performances of the bubble, insertion or selections sorts. In
general, the quick sort produces the most effective and widely used method of sorting a list of any
item size.
SEARCHING TECHNIQUES
Searching is the process of finding the location of some desired data in a collection of data items,
such as an array. If the data item that you want to search matches with any data item of the array, the
search returns the location of the data item that matches. Otherwise, the search fails.
There are three searching techniques namely:
1. Linear/Sequential Search
2. Binary Search
3. Merge Searching.
1)Linear/Sequential search.
Algorithm
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Pseudocode
end procedure
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of
the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.
Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
The Binary search uses the “divide and conquer” strategy. It repeatedly divides the array into two
pieces and then searches the piece that could contain the target value. It can only work if the array is
already sorted either in ascending order or in descending order.
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm
works on the principle of divide and conquer. For this algorithm to work properly, the data
collection should be in a sorted form.
#include <stdio.h>
#define MAX 20
printf("=\n");
}
// data found
if(intArray[midPoint] == data) {
index = midPoint;
break;
} else {
void display() {
int i;
printf("[");
printf("]\n");
}
main() {
printf("Input Array: ");
display();
printline(50);
//find location of 1
int location = find(55);
3)Merge search.
A searching technique based on divide and conquer technique. With worst-case time complexity
being Ο(n log n), it is one of the most respected algorithms. Merge search first divides the array into
equal halves and then combines them in a sorted manner.
How Merge search Works?
we take an unsorted array as the following
Merge search first divides the whole array iteratively into equal halves unless the atomic values are
achieved. We see here that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two
arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the
color codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted
manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list
of 2 values we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44 are
placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them
into a list of found data values placing all in a sorted order.
After the final merging, the list should look like this −
To read a string from the keyboard you must use another of C’s standard library functions, gets( ),
which requires the STDIO.H header file. To use gets( ), call it using the name of a character array
without any index. The gets( ) function reads characters until you press <ENTER>. The carriage
return is not stored, but it is replaced by a null, which terminates the string. For example, this
program reads and writes a string entered at the keyboard.
#include<stdio.h>
main()
{
char str[80];
int i;
printf( “ Enter a string (less than 80 characters): \n”);
gets(str);
for( i = 0 ; str[i]; i++)
printf(“ %c”, str[i]);
return 0;
}
The gets( ) function performs no bounds checking, so it is possible for the user to enter more
characters that gets( ) is called with can hold. Therefore be sure to call it with an array large enough
to hold the expected input.
In the previous program, the string that was entered by the user was output to the screen a character
at a time. There is however a much easier way to display a string, using printf( ). Here is the previous
program rewritten..
#include<stdio.h>
main()
{
char str[80];
printf( “ Enter a string (less than 80 characters): \n”);
gets(str);
printf(str);
system(“pause”);
return 0;
}
This method uses the %s format specifier followed by the new line character and uses the array as a
second argument to be matched by the %s specifier.
TOPIC 7: SUBPROGRAMS
SUBPROGRAMS
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.
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.
1) 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.
2) Global Variables
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)
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 avalue to the procedure or
program which calls it.
Characteristics of a FUNCTION
Advantages of Functions.
A function improves the readability and the logic of a program.
It helps to reduce the length of the source code which in turn reduce the complexity of the program.
Functions are easy to debug.
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
i. User defined
ii. In Built.
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 reale.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:
Eg1
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()
{
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
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;
}
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.
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 */
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.
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
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. */
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;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t", fibonaci(i));
}
system("pause");
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);
int main()
{
Example 2:
/* example program to demonstrate the passing of an array */
#include <stdio.h>
int maximum( int [] ); /* ANSI function prototype */
main()
{
int values[5], i, max;
printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
scanf("%d", &values[i] );
for( i = 0; i < 5; ++i )
printf("Element[%d] = %d\n", i, values[i] );
max = maximum( values );
printf("\nMaximum value is %d\n", max );
system("Pause");
return 0;
}
What is a 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
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and takes
bigger storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than text
files.
In C, you can perform four major operations on the file, either text or binary:
When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and program.
FILE *fptr;
ptr = fopen("fileopen","mode")
1. File can be opened in basic 3 modes : Reading Mode, Writing Mode, Appending Mode
2. If File is not present on the path specified then New File can be created using Write and
Append Mode.
3. Generally we used to open following types of file in C –
Output:
putch(ch)
Remarks:
putch print only one character at a time screen.
Example Program:
void main()
{
char ch='a';
putch(ch)
}
This access method the information/data stored on a device can be accessed randomly and
immediately irrespective to the order it was stored. The data with this access method is quicker than
sequential access. This is also known as random access method. For example Hard disk, Flash
Memory.
Sequential Access
This access method the information/data stored on a device is accessed in the exact order in which
it was stored. Sequential access methods are seen in older storage devices such as magnetic tape.
Index-Sequential organization
The records is stores in some order but there is a second file called the index-file that indicates
where exactly certain key points. Can not be used with sequential access method.
Sequential records cannot support modern technologies that require fast access to stored records.
The requirement that all records be of the same size is sometimes difficult to enforce.
The pile
Data are collected in the order in which they arrive. Each record consists of one burst of data. The
purpose of the pile is simply to accumulate the mass of data and save it. Records may have different
fields, or similar fields in different orders.Thus, each field should self-describing, including a field
name as well as a value.
File Design
Creating a file and output some data
In order to create files we have to learn about File I/O i.e. how to write data into a file and how to
read data from a file. We will start this section with an example of writing data to a file. We begin as
before with the include statement for stdio.h, and then define some variables for use in the example
including a rather strange looking new type.
/* Program to create a file and write some data the file */
#include <stdio.h>
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
}
The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file
pointer for use in file operations. Before we can write to a file, we must open it. What this really
means is that we must tell the system that we want to write to a file and what the file name is. We do
this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our
case, points to the file and two arguments are required in the parentheses, the file name first,
followed by the file type.
The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or
even mixed if you so desire. It is enclosed in double quotes. For this example we have chosen the
name TENLINES.TXT. This file should not exist on your disk at this time. If you have a file with
this name, you should change its name or move it because when we execute this program, its
contents will be erased. If you don’t have a file by this name, that is good because we will create
one and put some data into it. You are permitted to include a directory with the file name. The
directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way
C handles literal strings, the directory separation character ‘\’ must be written twice. For
example, if the file is to be stored in the \PROJECTS sub directory then the file name should be
entered as “\\PROJECTS\\TENLINES.TXT”. The second parameter is the file attribute and can
be any of three letters, r, w, or a, and must be lower case.
C File management
A File can be used to store a large volume of persistent data. Like many other languages 'C' provides
following file management functions,
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file
Following are the most important file management functions available in 'C,'
function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
Sets the position of a file pointer to a specified
fseek ()
location
ftell () Returns the current position of a file pointer
• When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the
file using few commands in C.
• You can easily move your data from one computer to another without any changes.
STRUCTURES
Introduction
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];
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
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
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)
#include<stdio.h>
#define SIZE 40
struct student
{
char name[SIZE];
int marks;
};
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.
Program documentation
Server Environments
It is always beneficial to have detailed documentation about an application and its environments.
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
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.
Code Deployment
Most companies have their own deployment processes when doing releases and code updates and it
is always helpful to have the deployment instructions documented. There should be information
regarding the code repository, where the file updates are found, and where they need to be moved.
In addition, there should be step-by-step instructions on how to create an application package or a
build to be deployed.
All these documents should be readily available to the developers and team members on the project.
These can be placed in a document sharing portal for easy access, access control, and version
control. In order for them to be useful, they should be updated as changes are made or new
enhancements and processes are added to the application. Having all the necessary documents
pertaining to your application will make your development and maintenance efforts more efficient.
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.
Types of Documentations
1) User Documentation
The users are usually non-technical people, who don't need to know how the system works. They
just need to know how to use it.
User documentation refers to the documentation for a product or service provided to the end users.
The user documentation is designed to assist end users to use the product or service. This is often
referred to as user assistance. The user documentation is a part of the overall product delivered to
the customer.
Traditionally user documentation was provided as a user guide, instruction manual or online help.
However, user documentation is increasingly being delivered online today. This has enabled
technical writers to be more imaginative in how they assist users.
Without user documentation, a user may not know how to do the above things.
• FAQs
• Video tutorials
• Embedded assistance (for example, tool tips and dynamic page content)
• Support Portals
The quality of user documentation can affect the rate of implementation of the new system.
Examples should include methods such as: help files, online support and printed manuals.
• larger amount of
information • can't be accessed offline
online • easier to update • if you have slow internet connection,
support • can access from any device it's bad.
• can be faster
• slower
• easy to find • if you lose it, you're going to have a
• you can browse through bad day
printed
them • harder to search
manuals
• work without a computer • cannot be updated
• prone to physical destruction
2) Technical Documentation
The technical documentation is intended to help the maintainers of the system (the people who
need to keep the system running smoothly, fix problems, etc.)
The maintainers are usually technical people, who need to know exactly how the system works.
Program Documentation
Any written text, illustrations or video that describe a software or program to its users is
called program or software document. User can be anyone from a programmer, system analyst and
administrator to end user. At various stages of development multiple documents may be created for
different users. In fact, software documentation is a critical process in the overall software
development process.
In modular programming documentation becomes even more important because different modules
of the software are developed by different teams. If anyone other than the development team wants
to or needs to understand a module, good and detailed documentation will make the task easier.
Advantages of Documentation
These are some of the advantages of providing program documentation −
Example Documents
A software can have many types of documents associated with it. Some of the important ones
include −
• User manual − It describes instructions and procedures for end users to use the different
features of the software.
Identification – This should include the title of the program, short statement of its function, author,
date written, language used and version and the hardware requirements.
General specification – This should include a description of the main actions of the program under
normal circumstances, file specifications, restrictions and/or limitations of the programs and
references to any texts explaining any complex procedures / techniques used in the program.
User information – This should include the format of input required, e.g. source documents, how to
produce outputs and their layout and detailed instructions on how to run the program.
Program specification – This will contain the design of the program using structures charts or
flowcharts, annotated program listing and testing procedure including test data and expected output.
Author information
Program description
Calculator requirements
Installation (if necessary)
Instructions
Date released or version number
Files included in zip
Program controls
Troubleshooting
Copyright
Key files within the application. This may include files created by the development team, databases
accessed during the program's operation, and third-party utility programs.
Functions and subroutines. This includes an explanation of what each function or subroutine does,
including its range of input values and output values.
Decide how much of the documentation should be within the program code and how much should
be separate from it. The more technical documentation is developed within the program's source
code to begin with, the easier it will be to update and maintain along with the code, as well as to
document various versions of the original application. At a minimum, documentation within the
source code needs to explain the purpose of functions, subroutines, variables, and constants.
If the source code is particularly lengthy, it can be documented in the form of a help file, which can
be indexed or searched with keywords. This is a particular advantage for applications where the
program logic is fragmented over many pages and includes a number of supplemental files, as with
certain Web applications.
Choose the appropriate documentation tool. To some extent, this is determined by the language the
code is written in, be it C++, C#, Visual Basic, Java, or PHP, as specific tools exist for these and
other languages. In other cases, the tool to use is determined by the type of documentation required.
Word-processing programs for Microsoft Word are adequate for creating separate text files of
documentation, as long as the documentation is fairly short and simple. For long, complex text files,
many technical writers prefer a documentation tool such as Adobe FrameMaker.
In no case, however, should software documentation substitute for poor interface design. If an
application screen requires reams of documentation to explain it, better to change the screen design
to something more intuitive.
Understand the audience you're writing the documentation for. In most cases, software users have
little knowledge of computers outside of the tasks the applications they use enable them to do.
There are several ways to determine how to address their needs with your documentation.
Look at the job titles your prospective users hold. A system administrator is likely expert with a
number of software applications, while a data entry clerk is more likely to know only the application
he or she currently uses to enter data.
Look at the users themselves. Although job titles generally indicate what people do, there can be
considerable variation in how certain titles are used within a given organization. By interviewing
prospective users, you can get a feel for whether your impressions of what their job title indicates are
accurate or not.
A user guide format explains how to use the software to perform a particular task. User guides are
often formatted as printed guides or PDFs, although some help files include topics on how to
perform particular tasks. (These help topics are usually not context-sensitive, although they may be
hyperlinked to from topics that are.) User guides often take the form of tutorials, with a summary of
the tasks to be performed in the introduction and instructions given in numbered steps.
Decide what form(s) the documentation should take. Software documentation for end users can take
1 or several of many forms: printed manuals, PDF documents, help files, or online help. Each form
is designed to show the user how to use each of the program's functions, whether in the form of a
walkthrough or a tutorial; in the case of help files and online help, this may include demonstration
videos as well as text and still graphics.
Help files and online help should be indexed and keyword-searchable to allow users to quickly find
the information they're looking for. Although help file authoring tools can generate indexes
automatically, it is often better to create the index manually, using terms users are likely to search
for.
Choose the appropriate documentation tool. Printed or PDF user manuals can be written with a
word-processing program like Word or a sophisticated text editor like FrameMaker, depending on
Programming languages have always been heavily influenced by programming paradigms, which in
turn have been characterized by general computing trends.
• 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.
• 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.
• 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.
• 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.
Concurrent and distributed programming is about to become one of the biggest challenges of our
time to be faced for computing in general. As a result, there is still much ongoing research effort in
finding programming models that tackle concurrency and distribution more naturally. While some
specifically target multi-core concurrency, others address concurrency more generally as an intrinsic
property of distributed computing. We now take a look at some of these concepts and study their
original ideas.
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
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.
It represents an extreme approach on how to isolate and handle state and it does not resemble any
of the popular programming models. It rejects the notion of coupling state and behavior that
characterizes object-oriented programming. Instead, functional relational programming takes an
entirely declarative route, mainly resting upon relational principles and to minor extend the usage of
side-effect free functional programming constructs. It is still uncertain, whether this model will soon
immerse into mainstream development models for application programming.
Cost overruns.
Changing of requirements.
Misunderstanding of requirements.
Over-ambitious goals.
Poor planning/research.
REFERENCES