You are on page 1of 58

INTRODUCTION TO PROGRAMMING AND

ALGORITHMS

Most people are familiar with the existing tasks the computer can perform.You will
learn how to command computers to perform those tasks. i.e software-instructions you
write to command computers to perform actions and make decisions that controls
computer hardware.

PROGRAMMING CONCEPTS

a. Program-it is a sequence of instructions, statements, and series of codes that


instruct a computer to perform certain tasks.
b. Programmer-this is a person that writes the programs to the computer through
orderly set of actions.
c. Programming-This is the act of writing, coding,testing and running a series of
instructions to perform a certain task.
d. Programming language-This is an organized collection of symbols with syntax
and semantics to prepare computer programs.
e. Modules-smaller programs units(functions which are manageable than the
original program)

PROGRAMMING ERRORS/BUGS

a. Syntax error-it results as a violation of rules and procedures of writing a


program e.g omission of a semicolon
b. Semantic errors-It is the violation of the meaning inscribed in a particular term.
c. Logical error-program is running properly but giving undesired results or
doesn’t make sense.
d. Compilation/Run-time/Execution time error-This error happens when compiling
a program e.g division by zero i.e 5/0

PROGRAM TRANSLATION

C-Systems generally consists of several parts,namely:


i. Program development environment
ii. Language
iii. C-Standard library

C-Programs go through six phases to be executed

1) Editing-This is accomplished with an editor program e.g Ms Visual


studio,Borland,C++ builder e.t.c The Programmer types a c-program with the
editor,makes correction if necessary,then stores programs on a secondary
storage devices suchas a disk.C-program file names should end with the .c
extension edit
2) Pre-Process-The processor program executes automatically before the compiler
translation phase begins. The C-preprocessor directives which indicate that
certain manipulations are to be performed on the program before compilation.
a preprocessor is a program that processes its input data to produce output that
is used as input to another program.
The output is said to be a preprocessed form of the input data, which is often
used by some subsequent programs like compilers.
The amount and kind of processing done depends on the nature of the
preprocessor; some preprocessors are only capable of performing relatively
simple textual substitutions and macro expansions, while others have the power
of full-fledged programming languages.

3) Compilation phase-The programmer gives the command to compile the


program.The compiler translates the high level language(source code) into
machine language(object code).Interpreter-illustrates code to operating system.
i.e translates one programming language to another.
4) Linking-C-programs typically contain differences to functions defined
elsewhere such as in the standard library or in private libraries groups of
programmers working on a particular project.Linker-Links the object code with
the source code to ensure no missing functions to produce an executable
program(no missing pieces)
5) Loading phase-Before the program can be executed the program must first be
placed in the memory, this is done by the loader.Loader takes the executable
image from the disk and transfers it to the memory.Additional components
from shared libraries that support the program are also loaded.
6) Executing phase-The compiler under the control of its control processing unit,
executes the program/instructions at a time. execution

NB:Programs don’t always work on first try.Each of preceding phases can fail
due to various errors.

EVOLUTION OF PROGRAMMING LANGUAGE AND TECHNIQUES


OF PROGRAMMING

Unstructured Programming
It consists of a set of statements executed from top to bottom (in order)
Structured Programming (Modular programming)
Its used to divide large applications into a set of procedures that can be used to
perform a certain task.A program is subdivided into small programs called
modules that can be solved independently.It was used in large [programming
and also called bottom-up programming.
Procedural programming
This emphasizes on the design of a program using a given procedure. A
procedure is used to solve certain task.
Object oriented programming
The aspect of writing programs using objects and classes.
Event Driven programming

LEVELS OF PROGRAMMING LANGUAGES


There are many programming languages. The languages are classified into 2 major
categories:
1). Low-level programming languages.
2). High-level programming languages.
Each programming language has its own grammatical (syntax) rules, which must be
obeyed in order to write valid programs, just as a natural language has its own rules for
forming sentences.

LOW-LEVEL LANGUAGES
These are the basic programming languages, which can easily be understood by the
computer directly, or which require little effort to be translated into computer
understandable form.
They include:
1. Machine languages.
2. Assembly languages.
Features of low-level languages
 They are machine hardware-oriented.
 They are not portable, i.e., a program written for one computer cannot be installed
and used on another computer of a different family.
 They use Mnemonic codes.
 They frequently use symbolic addresses.

Machine languages (1st Generation languages)


Machine language is written using machine codes (binary digits) that consist of 0’s &
1’s.
The computer can readily understand Machine code (language) instructions without any
translation.
A programmer is required to write his program in strings of 0’s & 1’s, calculate &
allocate the core memory locations for his data and/or instructions.
Different CPU’s have different machine codes, e.g., codes written for the Intel Pentium
processors may differ from those written for Motorola or Cyrix processors. Therefore,
before interpreting the meaning of a particular code, a programmer must know for
which CPU the program was written.
A machine code instruction is made up of 2 main parts;
(i). An Address (operand):
It specifies the location (address) of the computer memory where the data to be
worked upon can be found.
(ii). A Function (operation) code:
It states to the Control Unit of the CPU what operation should be performed on
the data/item held in the address, e.g., Addition, Subtraction, Division,
Multiplication, etc.
Note. The computer can only execute instructions which are written in machine
language. This is because; it is the only language which the computer can understand.
Therefore, any program written in any other programming language must first be
translated into machine language (binary digits) before the computer can understand.

Assembly language (2nd Generation Languages)


Assembly languages were developed in order to speed up programming (i.e., to
overcome the difficulties of understanding and using machine languages).
The vocabulary of Assembly languages is close to that of machine language, and their
instructions are symbolic representations of the machine language instructions.
 Assembly language programs are easier to understand, use & modify compared to
Machine language programs.
 Assembly language programs have less error chances.
To write program statements in Assembly language, the programmer uses a set of
symbolic operation codes called Mnemonic codes.
The code could be a 2 or 3 shortened letter word that will cause the computer to
perform specific operation. E.g., MOV – move, ADD - addition, SUB – subtraction, RD
- read.
Example;
RD PAT, 15 (read the value 15 stored in the processor register named
PAT)
SUB PAT, 10 (subtract 10 from the value in register PAT)
A program written in an Assembly language cannot be executed/obeyed by the
computer hardware directly. To enable the CPU understand Assembly language
instructions, an Assembler (which is stored in a ROM) is used to convert them into
Machine language.
The Assembler accepts the source codes written in an Assembly language as its input,
and translates them into their corresponding computer language (machine code/ object
code) equivalent.
Comments are incorporated into the program statements to make them easier to be
understood by the human programmers.
Assembly languages are machine-dependent. Therefore, a program written in the
Assembly language for a particular computer cannot run on another make of computer.

Advantages of Low-level languages


1. The CPU can easily understand machine language without translation.
2. The program instructions can be executed by the hardware (processor) much faster.
This is because; complex instructions are already broken down into smaller simpler
ones.
3. Low-level languages have a closer control over the hardware, are highly efficient &
allow direct control of each operation.
They are therefore suitable for writing Operating system software & Game
programs, which require fast & efficient use of the CPU time.
4. They require less memory space.
5. Low-level languages are stable, i.e., they do not crash once written
Disadvantages of Low-level languages
Very few computer programs are actually written in machine or Assembly language
because of the following reasons;
1. Low-level languages are difficult to learn, understand, and write programs in them.
2. Low-level language programs are difficult to debug (remove errors from).
3. Low-level languages have a collection of very detailed & complex instructions that
control the internal circuiting of the computer. Therefore, it requires one to
understand how the computer codes internally.
4. Relating the program & the problem structures is difficult, and therefore
cumbersome to work with.
5. The programs are very long; hence, writing a program in a low-level language is
usually tedious & time consuming.
6. The programs are difficult to develop, maintain, and are also prone to errors (i.e., it
requires highly trained experts to develop and maintain the programs).
7. Low level languages are machine-dependent (specific), hence non-portable.
This implies that, they are designed for a specific machine & specific processor, and
therefore, cannot be transferred between machines with different hardware or
software specifications.
8. It is not easy to revise the program, because this will mean re-writing the program
again.

HIGH-LEVEL PROGRAMMING LANGUAGES


High-level languages were developed to solve (overcome) the problems encountered in
low-level programming languages.
The grammar of High-level languages is very close to the vocabulary of the natural
languages used by human beings. Hence; they can be read and understood easily even
by people who are not experts in programming.
Most high-level languages are general-purpose & problem-oriented. They allow the
programmer to concentrate on the functional details of a program rather than the details
of the hardware on which the program will run.
High-level language programs are machine-independent, (i.e., they do not depend on a
particular machine, and are able to run in any family of computers provided the relevant
translator software is installed).
Programs written in a high-level language cannot be obeyed by the computer hardware
directly. Therefore, the source codes must be translated into their corresponding
machine language equivalent. The translation process is carried out by a high-level
language software translator such as a Compiler or an Interpreter.
Features of high-level programming languages
 They contain statements that have an extensive vocabulary of words, symbols,
sentences & mathematical expressions, which are very similar to the normal English
language.
Example;
Read (TaxablePay);
IF TaxablePay<1000 THEN
Tax: =0;
ELSE
Tax: =TaxRate * TaxablePay;
Write (Tax: 6:2);
 Allow modularization (sub-routines).
 They are ‘user-friendly’ and problem-oriented rather than machine-based. This
implies that, during a programming session, the programmer concentrates on
problem-solving rather than how a machine operates.
 They require one to obey a set of rules when writing the program.
 Programs written in high-level languages are shorter than their low-level language
equivalents, since one statement translates into several machine code instructions.
 The programs are portable between different computers.

Purpose of High-level languages


1. To improve the productivity of a programmer. This is because; the source
programs of high-level languages are shorter than the source programs of low-level
languages, since one statement translates into several machine code instructions.
2. To ease the training of new programmers, since there is no need to learn the
detailed layout of a procession/sequence.
3. To speed up testing & error correction.
4. To make programs easy to understand & follow.
Advantages of High-level languages
1. They are easily portable, i.e., they can be transferred between computers of
different families and run with little or no modification.
2. High-level language programs are short, and take shorter time to be translated.
3. They are easy to learn, understand and use.
4. They are easy to debug (correct/remove errors), & maintain.
5. High level language programs are easy to modify, and also to incorporate additional
features thus enhancing its functional capabilities.
6. They are ‘user-friendly’ & problem-oriented; hence, can be used to solve problems
arising from the real world.
7. They enable programmers to adapt easily to new hardware. This is because; they
don’t have to worry about the hardware design of the computer.
8. High-level language programs are self-documenting, i.e., the program statements
displays the transparency of purpose making the verification of the program easy.
9. High level languages are more flexible; hence, they enhance the creativity of the
programmer and increase his/her productivity in the workplace.

Disadvantages of using High-level languages


1. High-level languages are not machine-oriented; hence, they do not use of the CPU
and hardware facilities efficiently.
2. The languages are machine-independent, and cannot be used in programming the
hardware directly.
3. Each high-level language statement converts into several machine code instructions.
This means that, they use more storage space, and it also takes more time to run the
program.
4. Their program statements are too general; hence, they execute slowly than their
machine code program equivalents.
5. They have to be interpreted or compiled to machine-readable form before the
computer can execute them.
6. The languages cannot be used on very small computers.
The source program written in a high-level language needs a Compiler, which is
loaded into the main memory of the computer, and thus occupies much of memory
space. This greatly reduces the memory available for a source program.

CHARACTERISTICS/FEATURES OF PROGRAMMING LANGUAGES

i. Clarity of the souce code-The ability of the code to be readable,understandable


and also reflect the logical structure of the program.
ii. Maintainability-Ability to modify a program in future
iii. Portability-The ability of the program to be transferred from one
hardware/software programs to another e.g From windows to unix or linux
system
iv. Reliability-This is the ability of the language to perform their intended function
satisfactorily through out their expected time of the process.
v. Expressivity-understandable and readable
vi. Generality-Features of a programming language should remain constant e.g
when you want to print to the screen, we use printf which is used all through in
programming.
vii. Operability-Ability of the program to operate on different platforms.
ALGORITHM

This is step by step procedure of solving a problem, attaining a goal or accomplishing a


certain objectives or verifying a problem has been solved.
 A step-by-step (a set of) instructions which when followed will produce a solution
to a given problem.

Characteristics of a good algorithm

a. Definiteness-Each step of an algorithm must be clearly defined or the action


must clearly specified.
b. Finiteness-An algorithm must terminate (end) after a number of steps.
c. Efficiency-Algorithms must be effective, or operations are executable, avoid
ambiguity.
d. Input
e. Output

Program design Tools.


Algorithms can be illustrated using the following tools:
1). Pseudocodes.
2). Flowcharts.
3). Decision Tables.
4). Decision Trees.
Note. For any given problem, the programmer must choose which algorithm (method)
is best suited to solve it.

1.Pseudocode-
This is an artificial and informal language that helps programmers develop
algorithms.It is similar to every day English.
 A pseudocode is a method of documenting a program logic in which English-like
statements are used to describe the processing steps.
 These are structured English-like phrases that indicate the program steps to be
followed to solve a given problem.

It is convenient and user friendly although its not atual computer programming
language.This helps programmers “thinking out” a program before putting it in actual
coding.
Guidelines for designing a good pseudocode.
1. The statements must be short, clear and readable.
2. The statements must not have more than one meaning (i.e., should not be
ambiguous).
3. The pseudocode lines should be clearly outlined and indented.
4. A pseudocode must have a Begin and an end.
i.e., a pseudocode should show clearly the start and stop of executable statements and
the control structures.
The input, output and processing statements should be clearly stated using keywords
such as PRINT, READ, INPUT
Example 1:
Write a pseudocode that can be used to prompt the user to enter two numbers, calculate
the sum and average of the two numbers and then display the output on the screen.
START
PRINT “Enter two numbers”
INPUT X, Y
Sum = X + Y
Average = Sum/2
PRINT Sum
PRINT Average
STOP
Example 2:
Write a structured algorithm that would prompt the user to enter the Length and Width
of a rectangle, calculate the Area and Perimeter, then display the result.
Solution
Step 1: Draw the rectangle of Length (L) and Width (W).
Step 2: Write down the Pseudocode.
START
PRINT “Enter Length and Width”
READ L, W
Area = L * W
Perimeter = 2 (L + W)
PRINT Area
PRINT Perimeter
STOP
Example 3:
Write a pseudocode that can be used to calculate the Diameter, Circumference and
Area of a circle and then display the output on the screen.
START
Set π to 3.14
Prompt the user for the Radius (R)
Store the radius in a variable (R)
Set Diameter to 2 * Radius
Set Circumference to π * 2 * Radius
Set Area to π * Sqr (Radius)
PRINT Diameter
PRINT Circumference
PRINT Area
STOP
Example 4:
Write a pseudocode for a program that would be used to solve equation: E = MC2.
START
Enter values from M to C
E=M*C*C
Display E

√ It is important to use program control structures when writing Pseudocodes. The


most common constructs are:
(i). Looping (Repetition / Iteration) – used where instructions are to be repeated
under certain conditions.
(ii). Selection – used when choosing a specified group of instructions for execution.
The group chosen depends on certain conditions being satisfied.

Example 5:
Write a pseudocode for a program that can be used to classify people according to age.
If a person is more than 20 years; output “Adult” else output “Young person”.
START
PRINT “Enter the Age”
INPUT Age
IF Age > 20 THEN
PRINT “Adult”
ELSE
PRINT “Young person”
STOP
Note. Pseudocodes make an algorithm easier to understand. This is because; the
algorithm can be read from top to bottom without the need for jumping backwards or
forwards to follow the logic of the algorithm as in flowcharts.

2.Flowcharts
This is a graphical representation of an algorithm.
They are drawn using special symbols.They are useful for developing and representing
an algorithm. They clearly show how control structures operates.
 A Flowchart is a diagrammatic or pictorial representation of a program’s algorithm.
 It is a chart that demonstrates the logical sequence of events that must be performed
to solve a problem

Types of Flowcharts.
There are 2 common types of Flowcharts:
1). System flowchart.
A System flowchart is a graphical model that illustrates each basic step of a data
processing system.
It illustrates (in summary) the sequence of events in a system, showing the
department or function responsible for each event.
2). Program flowchart.
This is a diagram that describes, in sequence, all the operations required to process
data in a computer program.
A program flowchart graphically represents the types of instructions contained in a
computer program as well as their sequence & logic.

Reasons for using flow charts

It helps in a process of problem design.


It documents the problem structure that can be understood by anyone.
1. Terminal symbol.
Ellipse (Oval in shape)

It is used to indicate the point at which a flowchart, a process or an algorithm


begins & ends.
√ All Flowcharts must have a START & STOP symbol. The START/BEGIN
symbol is the first symbol of a flowchart, & identifies the point at which the
analysis of the flowchart should begin. The STOP/END symbol is the last
symbol of a flowchart, & indicates the end of the flowchart.

√ The words Begin & End (or Start & Stop) should be inserted in the Terminal
symbol.

2. Input or Output symbol.


(Parallelogram)

- It is used to identify/specify an input operation or output operation.


For example;
READ Employee Name PRINT Employee
Input operation Name
Output operation
Note. The words mostly associated with I/O operations are READ & PRINT.
READ describes the entry of computer data, while PRINT relates to the printed
output of information.

3. Process symbol.
(Rectangle)
- Process symbol is used to indicate that a processing or data transformation is
taking place.
The information placed within the process symbol may be an algebraic formula or a
sentence to describe processing.

SUM = A + B Commission is computed at 20% of Total Sales


Processing defined as a Formula Processing defined as a Sentence
4. Decision symbol.

NO (Rhombus)

YES

- It is used to indicate/ specify a condition or to show the decision to be made.


There are 2 main components of a Decision symbol:
(i). A question asked within the Decision symbol, that indicates the comparison /
logical operation.
(ii). The results of the comparison (which are given in terms of YES or NO).
The arrows labeled YES or NO lead to the required action corresponding to the
answer to the question.

5. Flow lines.

Flow lines with arrowheads are used to indicate the direction of processing of the
program logic, i.e., they show the order in which the instructions are to be executed.
The normal flow of a flowchart is from Top to Bottom, and Left to Right.
Note. Flow lines should never cross each other.
6. Connector symbol.

Sometimes, a flowchart becomes too long to fit in a single page, such that the flow
lines start crisscrossing at many places causing confusion & also making the
flowchart difficult to understand.
The Connector symbol is used as a connecting point for arrows coming from
different directions.
A Connector symbol is represented by a Circle, and a letter or digit is placed within
the circle to indicate the link.
Note. Connectors do not represent any operation. They are used to connect two
parts of a flowchart, indicating that the flow of data is not broken.
General guidelines for drawing a program flowchart.
1. A flowchart should have only one entry/starting point and one exit point (i.e.,
ensure that the flowchart has a logical start and finish).
2. The flowchart should be clear, neat and easy to follow.
3. Use the correct symbol at each stage in the flowchart.
4. The flowchart should not be open to more than one interpretation.
5. Avoid overlapping the lines used to show the flow of logic as this can create
confusion in the flowchart.
6. Make comparison instructions simple, i.e., capable of YES/NO answers.
7. The logical flow should be clearly shown using arrows.
Note. A flowchart should flow from the Top to Bottom of a page, and from the
Left to the Right.
8. Where necessary, use Connectors to reduce the number of flow lines.
Connectors are helpful when a flowchart is several pages long, and where several
loops are needed in the logic of the flowchart.
9. Check to ensure that the flowchart is logically correct & complete.

Star
Example 1: t

Draw a flowchart for a program that


X, Ycan be used to prompt the user to enter two
numbers, find the sum and average of the two numbers and then display the output on
the screen.
Sum = X + Y
Average = Sum/2

PRINT Sum, Average

Stop
Example 2:
Draw a flowchart for a program that would prompt the user to enter the Length and
Width of a rectangle, calculate the Area and Perimeter, then display the result.
Star
t

L,
W

Area = L x W
Perimeter = 2 (L x W)

PRINT Area, Perimeter

Stop
Example 3:
Draw a flowchart for a program that can be used to calculate the Diameter,
Circumference and Area of a circle and then display the output on the screen.

Star
t

SET
π = 3.14

Radius
(R)

Diameter = 2 x Radius
Circumference = π x 2 x Radius
Area = π x Sqr (Radius)

Diameter, Circumference,
Area

Example 4: Stop
Design a flowchart for a program that can be used to classify people according to age.
If a person is more than 20 years; output “Adult” else output “Young person”.

Star
t

Age

No
Age> Young person
20?
Yes
Adul
t

Stop
Example 5:
Draw a flowchart for a program that would be used to classify animals according to
sex. If a letter M is input, the program should display ‘Male’ otherwise it should
display “Female”.

Star
t

Enter Letter

Yes
Letter = Mal
M e
No
Femal
e

Stop

Example 6:
Write a program using a flowchart to convert temperature from 0C to 0F.
Fahrenheit =32 + (9o x C/5).
Star
t

READ Temp.
in oC

Store value in
memory

Calculate Fahrenheit
F = 32 + (9/5 * oC)

PRINT temp.
in oC & oF

Stop
Notes.
 A flowchart must have a Start and an end.
 A flowchart is useful when the algorithm is short & the flowchart can fit
conveniently on a single page. If the flowchart is too large, it is recommended to
use Pseudocodes for long & complicated programs.

Advantages of using Flowcharts.


The following are the benefits of Flowcharts:
(i). Quicker understanding of relationships.
They assist programmers to understand procedures more quickly.
A programmer can represent a lengthy procedure more easily with the help of a
flowchart than describing it by means of written notes.
(ii). Effective synthesis.
Flowcharts may be used as working models in the design of new programs and
systems.
(iii). Proper program documentation.
Program flowcharts serve as good program documentation, which is needed for
the following reasons:
(a). If programs are modified in future, the flowcharts will direct the programmer
on what was originally done.
(b). When staff changes occur, the flowcharts may help new employees
understand the existing programs.
(c). Flowcharts assist in program conversion when new hardware/software are
acquired.
(iv). Effective coding.
Program flowcharts act as a guide during the program preparation stage.
Instructions coded in a programming language may be checked against the
flowchart to ensure that no steps are omitted.
(v). Orderly debugging and testing of programs.
Flowcharts help in detecting, locating and removing mistakes.
The programmer can refer to the flowchart as he/she re-checks the coding steps,
& the logic of the written instructions.
(vi). Efficient program maintenance.
Flowcharts facilitate the maintenance of operating programs. They help the
programmer to concentrate on the part of the information flow which is to be
modified.

Limitations of using Flowcharts.


(i). Flowcharts are complex, clumsy & become unclear, especially when the program
logic is complex.
(ii). If changes are to be made, the flowchart may require complete re-drawing.
(iii). Reproduction of flowcharts is usually a problem, since the flowchart symbols
cannot be typed.
(iv). No uniform practice is followed for drawing flowcharts as it is used as an aid to
the program.
(v). Sometimes, it becomes difficult to establish the link between various conditions,
and the actions to be taken upon a particular condition.

PROGRAMMING PRACTICES AND STYLES


Good programming practices
a) Use of comments-comments are non-executable statements in a program that
tries to tell what part of the program is doing or give the name(author of the
program, date of creation or explain a block,a single statement, a function or
intended purpose)
Advantages of using comments
i. It makes a program understandable (readability)
ii. It makes the modification of a program more easier in future
Two types of comments
i. Single line comment (//)-its used when commenting using one line
e.g //My first program in C
ii. Multiple line comment(/*--------------------------------
--------------------------------*/)
Its used when commenting on multiple or many lines also known as
block comment
e.g/*Program to calculate the total,
and average of 5 units*/
b) Braces({ })-The opening and closing braces.All braces must be opened and
must be closed
c) Whitespace-it refers to character in programming.e.g tabs,newlines e.t.c
d) Indenting-It refers to moving away from the margin
e) Escape sequence-These are programming shortcuts that are used when writing
codes and they perform a certain task.Its represented by a backslash followed by
an escape character
Escape Sequence Description
\’ (single quote) Outputs the single quote character
\” (double quote) Outputs the double quote character
\? (Question mark) Outputs the question mark character
\\ (backslash) Outputs the backslash character
\a (alert or bell) Cause an audible bell or visual alert
\b (backspace) It moves the cursor back on position on the current line
\f (new page or form feed) It moves the cursor to the start of the next logical page
\n (new line) It moves the cursor to the beginning of the next line
\r (carriage return) It moves the cursor to the beginning of the current line
\t (horizontal tab) It moves the cursor to the next horizontal tab position
\v (vertical tab) It moves the cursor to the next vertical tab position

STRUCTURE OF A PROGRAM

#include<stdio.h>//pre-processor directive
Int main()
{
Printf(“My first program\n”);
Return 0;/*program end successfully*/
}
a) Documentation section-it consists of comments giving the title of the
program,the author,the date of creation,the aim or objectives of the program.
b) The compile directive-It provides instructions to the compiler to link the
functions to its system library e.g
#include<stdio.h>,#include<math.h>.#include<stdlib.h>
c) Main function-It indicates the start of execution or the program statement.The
main function is used to call any other program in the body of a program and is
executable in a sequential manner. A function is a small program that carries out
a specific task when called
d) Body of the program-It consists of opening and closing braces.
e) Declaration of variables-All variables must be declared before use.
f) Return 0-This means terminating a function, it puts an end to execution of a
program. It returns the control to the operating system
IDENTIFIERS
In C programming, identifiers are names given to C entities, such as variables,
functions, structures etc.
 Identifier are created to give unique name to C entities to identify it during the
execution of program.
 It’s a name given to a variable, constant or a function.
Rules for naming identifiers
i. It must should not be a reserved word or keyword
ii. It should always start with an alphabet
iii. It should not contain special characters
iv. It can contain alphabets, numericals i.e alphanumeric
v. Should be upto 256 characters

NB:C is case sensitive

Keyword-These are used within specific programming language and cant


change(inbuilt)e.g scanf,printf,int ,main e.t.c
Variable
These are programming concepts that are memory locations which stores a value that
are determined to change with different executions.
Variable declaration
All variables must be declared before use
General syntax:
Data type variable_name
data type:
 C data types are defined as the data storage format that a variable can store a data to perform a
specific operation.
 Data types are used to define a variable before to use in a program.
 Size of variable, constant and array are determined by data types.
C – DATA TYPES:
There are four data types in C language. They are,

Types Data Types

Basic data types int, char, float, double

Enumeration data type enum

Derived data type pointer, array, structure, union

Void data type void


1. BASIC DATA TYPES IN C LANGUAGE:
1.1. INTEGER DATA TYPE:
 Integer data type allows a variable to store numeric values.
 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use.  If we are using 16 bit processor, 2
byte  (16 bit) of memory will be allocated for int data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64
bit processor is allocated for int datatype.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
 If you want to use the integer value that crosses the above limit, you can go for “long int” and
“long long int” for which the limits are very high.
Note:
 We can’t store decimal values using int data type.
 If we use int data type to store decimal values, decimal values will be truncated and we will get
only whole number.
 In this case, float data type can be used to store decimal values in a variable.
1.2. CHARACTER DATA TYPE:
 Character data type allows a variable to store only one character.
 Storage size of character data type is 1. We can store only one character using character data
type.
 “char” keyword is used to refer character data type.
 For example, ‘A’ can be stored using char datatype. You can’t store more than one character
using char data type.
 Please refer C – Strings topic to know how to store more than one characters in a variable.
1.3. FLOATING POINT DATA TYPE:
Floating point data type consists of 2 types. They are,

1. float
2. double
1. FLOAT:
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4. This also varies depend upon the processor in the CPU as
“int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.
2. DOUBLE:
 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The range for double datatype is from 1E–37 to 1E+37.
1.3.1. SIZEOF() FUNCTION IN C LANGUAGE:
sizeof() function is used to find the memory space allocated for each C data types.

1 #include <stdio.h>
2 #include <limits.h>
3 int main()
4 {
5    int a;
6    char b;
7    float c;
8    double d;
9    printf("Storage size for int data type:%d \n",sizeof(a));
10    printf("Storage size for char data type:%d \n",sizeof(b));
11    printf("Storage size for float data type:%d \n",sizeof(c));
12    printf("Storage size for double data type:%d\n",sizeof(d));
13    return 0;
14 }
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
1.3.2. MODIFIERS IN C LANGUAGE:
 The amount of memory space to be allocated for a variable is derived by modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
 There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
of each C basic data type in 16 bit processor.
Below table gives the detail about the storage size
Please keep in mind that storage size and range for int and float datatype will vary
depend on the CPU processor (8,16, 32 and 64 bit)

C Data types / storage


Size Range

char / 1 –127 to 127

int / 2 –32,767 to 32,767

1E–37 to 1E+37 with six digits of


float / 4 precision

1E–37 to 1E+37 with ten digits of


double / 8 precision

1E–37 to 1E+37 with ten digits of


long double / 10 precision

long int / 4 –2,147,483,647 to 2,147,483,647

short int / 2 –32,767 to 32,767

unsigned short int / 2 0 to 65,535

signed short int / 2 –32,767 to 32,767

long long int / 8 –(2power(63) –1) to 2(power)63 –1

signed long int / 4 –2,147,483,647 to 2,147,483,647

unsigned long int / 4 0 to 4,294,967,295

unsigned long long int / 8 2(power)64 –1


2. ENUMERATION DATA TYPE IN C LANGUAGE:
 Enumeration data type consists of named integer constants as a list.
 It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the
list.
 Enum syntax in C:
enum identifier [optional{ enumerator-list }];
 Enum example in C: 
enum month { Jan, Feb, Mar }; or
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by default */

 The above enum functionality can also be implemented by “#define” preprocessor directive as
given below. Above enum example is same as given below.
#define Jan 20;
#define Feb 21;
#define Mar 22;
C – ENUM EXAMPLE PROGRAM:
C

1 #include <stdio.h>
2 int main()
3 {
4    enum MONTH { Jan = 0, Feb, Mar };
5    enum MONTH month = Mar;
6    if(month == 0)
7    printf("Value of Jan");
8    else if(month == 1)
9    printf("Month is Feb");
10    if(month == 2)
11    printf("Month is Mar");
12 }
Output:
Month is March
3. DERIVED DATA TYPE IN C LANGUAGE:
 Array, pointer, structure and union are called derived data type in C language.
 To know more about derived data types, please visit “C – Array” , “C – Pointer” , “C –
Structure” and “C – Union” topics in this tutorial.
4. VOID DATA TYPE IN C LANGUAGE:
 Void is an empty data type that has no value.
 This can be used in functions and pointers.
 Please visit “C – Function” topic to know how to use void data type in function with simple call
by value and call by reference example programs.

VARIABLE DECRALATION
Variable declaration tells the computer to allocate memory for the variables of the
given data type.

Variables can be declared into two cases:


a. After the opening brace of a block of code(usually at the top of the function)
b. Before a function name(such as before main()in the program)

Scope of variables

a. Global variables-these are variables which are used in the whole program. They
are declared before the main function
e.g #include<stdio.h>
int marks;//Global variable
int main()
{

}
b. Local variables-the scope is limited to a block of codes enclosed in braces
e.g #include<stdio.h>
int main()
{
Int marks;//local variable
}

Initializing variables

Syntax:
Datatype variable_name=value

To initialize a variable is to assign a value to a variable


e.g int marks=76
This program will read two numbers from user and calculate sum and
average of numbers.
/* c program find sum and average of two numbers*/
#include <stdio.h>
 
int main()
{
    int a,b,sum;
    float avg;
 
    printf("Enter first number :");
    scanf("%d",&a);
    printf("Enter second number :");
    scanf("%d",&b);
 
    sum=a+b;
    avg= (float)(a+b)/2;
 
    printf("\nSum of %d and %d is = %d",a,b,sum);
    printf("\nAverage of %d and %d is = %f",a,b,avg);
 
    return 0;
}

Constants
This is a memory location that stores values which are not determined to change
 Constants are the terms that can't be changed during the execution of a program.
e.g pie=3.142
Declaration of constants
There are two ways of declaring constants
a. Before the main function-We use the #define followed by the constant name
and the value
i.e #define constant_name value

e.g #include<stdio.h>
#define pie 3.142
Int main()
{

}
b. After the main function
Syntax:
Const datatype constant_name=value
e.g
#include<stdio.h>
Int main()
{
Const double pie=3.14
}

Reasons for using constants

a) Makes a program easier to read and modify


b) Reduces repetition of codes

EXPRESSIONS

An expression is a sequence of operands and operators.


Operands are values reacted upon e.g x,y e.t.c
Operators are symbols that tell the computer to perform certain mathematical or logical
operations.
Types of operators and precedence

a) Arithmetic operators-they carry out mathematical operations


Symbol Meaning
* Multiplication
/ Division
% Modulus or Remainder
+ Addition
- Substraction
Order of precedence also called math hierarchy or order of operators determines
exactly how C computes formulas.
C always performs multiplication,division,and modulus first,and then addition and
substraction.Same as BODMAS
b) Relational operators-their task is to compare data.

Operator Description
== Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!= Not equal to

c) Logical operators-They are used to test more than one condition and make a
decision. They always perform true or false results.

Operator Meaning
&& AND
|| OR
! NOT

Logical AND (&&) Truth table


Result
True True True
True False False
False True False
False False False

Logical OR(||)Truth table

Result
True True True
True False True
False True True
False False False

Logical NOT(!)Truth table

NOT False=True
NOT True=False
It gives the opposite of the results

d) Assignment operators-its used to assign values to variables,a lso used to assign


results of expressions to a variable.

Operator Example Equivalent


+= bonus+=500 bonus=bonus+500
-= Budget budget=budget-50
*= salary*=1.2 salary=salary*1.2
/= factor/=.50 factor=factor/.50
%= daynum%=7 daynum%7

e) Special operators-they are used to increment or decrement


Operator Example Description Equivalent
statements
++ i++ Postfix i=i+1;i+=1;
++ ++i Prefix i=i+1;i+=1
__ i- - Postfix i=i-1;i-=1;
__ - -i Prefix i=i-1;i-=1;
Notice that the ++ and - - can go on either side of the modified variable.if the ++ or - -
appears on the left,its known as prefix operator.If it appears on the right,it’s a postfix
operator.
NB: Whether you use prefix or postfix it doesn’t matter.
INPUT AND OUTPUT

Understanding printf()
printf() sends data to the standard output device,which is generally the screen.
Format:
printf(control_string[,one or more values])
printf() always requires a control_string.

Defining conversion characters


Conversion characters tell printf() exactly how the data(following the characters)are to
be interpreted.

Conversion Character Output


%s String of characters
%c character
%d Decimal integer
%f Floating point numbers
%e Exponential notation
%g Use the shorter of %f or %e
%u Unsigned integer
%o Octal integer
%x Hexadecimal integer
%% Prints a percent sign(%)

NB: You can insert an l (lowercase l) or L before the integer and floating point
conversion characters(such as %ld and %lf)to indicate that a long integer or long
double floating point is to be printed.

Printing strings
printf(“This is stage 2”); is the same as
printf(“%s”,”This is stage 2”);
The %s informs the printf() function that a string follows.
NB:C does not need the %s to print strings,the %s is redundant.

Character conversion characters

You must use the %c conversion character any time you print single characters.
e.g printf(“%c %c %c”,’A’,’B’,’C’);
Output on screen is:
ABC

Integer and floating point conversion characters %d and %f

When you want to print a numeric constant or variable,you must include the proper
conversion character inside the printf() control string.

e.g printf(“I am a student in stage II,I am %d years old,and I make %f\n”,20,50000.75);

NB: /n is an escape sequence character

output on the screen:


am a student in stage II,I am 20 years old,and I make 50000.75

Example 1
#include<stdio.h>
main()
{
char first='E';
char middle='W';
char last='C';
int age=32;
int dependents;
float salary=25000.00;
float bonus=575.25;

printf("Here are the initials\n");


printf("%c%c%c\n\n",first,middle,last);
printf("The age and number of dependents are:\n");
printf("%d %d \n", age,dependents);
printf("The salary and bonus are:\n");
printf("%f %f",salary,bonus);
return 0;
}
The output from this program is
Here are the initials
EWC
The age and number of dependents are:
32 2
The salary and bonus are:
25000.00 575.25

If you need to print a table of numbers,you can use the \t tab character.
Example 2
#include<stdio.h>
main()
{
printf(“Parrots\tRams\tKings\n”);
printf(“%d\t%d\t%d\n”,3,5,2);
printf( “%d\t%d\t%d\n”,2,5,1) ;
printf( “%d\t%d\t%d\n”,2,6,4) ;

return 0 ;
}

This program produces the following table.


Parrots Rams Kings
3 5 2
2 5 1
2 6 4

Conversion character modifiers


You insert a modifying number inside numeric conversions to tell C how many print
positions to use.
e.g printf(“%d”,456) it prints the number 456,using three positions(the length of the
data).

However if you insert a number before the d in the conversion character,you can
control exactly how many positions print.
The following printf() prints the number 456 in five positions(with two leading spaces)
Printf(“%5d”,456);
If you put a minus sign before the width specifier,C left justifies the number inside the
width.

The width specifier is more important when you want to print floating point numbers.
Format:
%width.decimalsf
The floating point conversion character,%6.2f tells C to print a floating point number
within six positions,including the decimal point and the fractional part.It also informs C
to print two decimal places.If C has to round the fractional part,it does so
e.g printf(%6.2f,134.568767);
produces this output:
134.57
Without the format modifier,C would print
134.568767
Using scanf() for input

The scanf() function is one way to get input from the keyboard.
Format:
Scanf(control_string,one or more values);

Never include the newline character(\n)in a scanf() control string.The scanf()function


knows the input is finished when the user presses enter.
Always put a beginning space inside every scanf() control string.

NB:Always put an ampersand(&)before variable names inside a scanf().


Never put an ampersand (&) before an array name inside a scanf()
Example 3

/*Prompt for a sales amount and print the sales tax*/


#include<stdio.h>
main()
{
float total_sale;
float tax;

printf(“what is the total amount of the sale?”);


scanf(“%f”,total_sale);
tax=total_sale* .07;

printf(“The sales tax for %.2f is %.2f”,total_sale,tax);

return 0;
}

output
What is the total amount of the sale? 10.00
The sales tax for 10.00 is 0.70

TYPECASTING

You can override c defaults conversions by specifying your own temporary type
change.This is called typecasting
When you typecast you temporarily change variable data type from its declared data
type to a new one.
e.g
int age;
double age_factor;
int factor;
age_factor=(double)age*factor//temporarily change age from int to double
CONTROL STRUCTURES

These are programming statements that control the flow of execution in a


program.They are organized into three kinds of control structures.
a. Sequence
b. Selection
c. Repetition/Iteration/Looping

Sequence control structure

The sequence structure is essentially built into C.Unless directed otherwise,the


computer automatically executes C statements one after the other in the order in which
they are written.

Add grade to total total=total +grade;

Add 1 to counter counter=counter+1;

NB:Flowlines indicates order in which actions are performed.

Selection control structure

They are used to choose among alternatives causes of actions.


They include :
i. The if selection statement(Single selection statement)
ii. The if……else selection statement(Double-selection statement)
iii. Switch statement(Multiple-selection statement)

The if selection statement


It performs (selects)an action if a condition is true or skips the action if the condition is
false.

Start

Conditio True Action


n

Exit

#include<stdio.h>
int main()
{
int grade;
printf("Enter grade\n");
scanf("%d", &grade);
if(grade>=50)
{
printf("Passed\n");
}
return 0;
}
The if……else selection statement
It performs an indicated action only when the condition is true; otherwise the action is
skipped.

Start

Conditio
n

Action Action

End
#include<stdio.h>
int main()
{
int grade;
printf("Enter grade\n");
scanf("%d", &grade);
if(grade>=50)
{
printf("passed\n");
}
else
{
printf("failed\n");
}
return 0;

Nested if….else statements


It tests for multiple cases by placing if….else statements inside if….else statements.
#include<stdio.h>

int main()
{
int marks;
printf("Enter grade\n");
scanf("%d", &marks);
if ((marks>=0) &&(marks<=49))
{
printf("Grade is D\n");
}
else if((marks>=50) &&(marks<=64))
{
printf("Grade is C\n");
}
else if((marks>=65) &&(marks<=79))
{
printf("Grade is B\n");
}
else if((marks>=80) &&(marks<=100))
{
printf("Grade is A\n");
}
else
{
printf("Invalid entry");
}
return 0;
}

Switch multiple selection statement


An algorithm contain a series of decisions in which a variable or expression is tested
separately for each of the constant integral values it may assume and different actions
are taken.This is called multiple selection.
Each case can have one or more actions.
The switch statement consists of a series of case labels,and an optional default case.

Format:
Switch(expression)
{
Case (expression1):
{
One or more C statements;
}
Case (expression2):
{
One or more C statements;
}
Case (expression3):
{
One or more C statements;
}



Default:
{
One or more C statements;
}
}
If the block is only one statement long,you do not need the braces,but they are
recommended.
The default line is optional and it doesn’t have to be the last line of the switch body.

true
Case Case a action(s) break
a
false

true
Case Case a action(s) break
b
false

.
.

Case true Case a action(s) break


z

false

default

The flowchart makes it clear that each break statement at the end of a case causes
control to immediately exit the switch statement.

#include<stdio.h>
Int main()
{
Int marks;
Char Grade;
printf(“Please enter student marks\n”);
scanf(“%d”, &marks);
switch(marks)
{
case (marks>=0 && marks<=49)
{
Grade=’D’;
Break;
}
case (marks>=50 && marks<=64)
{
Grade=’C’;
Break;
case (marks>=65 && marks<=79)
{
Grade=’B’;
Break;
case (marks>=80 && marks<=100)
{
Grade=’A’;
Break;
}
default:
{
Printf(“You must enter a number between 0 to 100”);
}
return 0;
}
}

Repetition/Looping

A loop is a group of instructions the computer executes repeatedly while some loop-
continuation condition remains true.
Two main types :
i. Counter-controlled repetition-Also called definite repetition because we know
in advance exactly how many times the loop will be executed.e.g for loop
ii. Sentinel-uncontrolled repetition-Also called indefinite repetition because its not
known in advance how many times the loop will be executed.e.g do…while and
while

Repetition structures include:


i. while
ii. do------while
iii. for loop

for loop
format of the for loop:
for(start expression;test expression;count expression)
{
Block of one or more c statements;
}

Start expression is an assignment statement(such as ctr=1;)


Test expression evaluates to true or false,and then determines if the body of the loop
repeats again.(loop condition)
Count expression usually increments and decrements.

Start

Initial counter
(start expression)

Test Body/Execute Increment


expression statements Count expression

Exit

Example 1
#include<stdio.h>
int main()
{
int ctr;
for(ctr=1;ctr<=10;ctr++)
{
printf(“%d\n,ctr”);
}
return 0;
}

Example 2
#include<stdio.h>
int main()
{
int total,ctr;
total=0;
for(ctr=100;ctr<=200;ctr++)
{
total+=ctr;
}
printf(“The total is %d\n,total”);
return 0;
}

Example 3
#include<stdio.h>
int main()
{
int ctr;
total=0;
for(ctr=10;ctr!=0;ctr--)
{
printf(“%d\n,ctr”);
}
return 0;
}

When decrementing a loop variable,the initial value should be larger than the end value
being tested.

output

10
9
8
7
6
5
4
3
2
1

Nested for loops


When you create a loop within a loop ,you are creating a nested loop.
Example for factorials

/*computes the factorial of numbers through the users number*/


#include<stdio.h>
Int main()
{
int outer,num,fact,total;
printf(“What factorial do you want to see?”);
scanf(“%d”, &num);
for(outer=1;outer<=num;outer++)
{
total=1;//initialize total for each factorial
for(fact=1;fact<=outer;fact++)
{
total*=fact;
}
}
printf(“The factorial for %d is %d”,num,total);
return 0;
}

output

What factorial do you want to see?7


The factorial for 7 is 5040

While

Format:
While(test expression)
{
Block of one or more statements;
} Start
The test expression usually contains relational,and possibly logical operators.
The while loop tests the expression at the top of the loop.

Conditio Execute
n statements

Exit
True

False

#include<stdio.h>
int main()
{
int counter=0;
while(counter<=10)
{
printf(“%d”,counter);
counter++;
}
printf(“%d”,counter);
return 0;
}

Start
do……while
its similar to the while loop except the relational test occurs at the bottom(rather than
top)of the loop.this ensures that the body of the loop executes at least once.
Format:
do Execute statement(s)
{
Block of one or more c statements;
}
while(test expression)

it tests the condition after the body is performed.


Conditio
n

Exit
True

False

#include<stdio.h>
Int main()
{
int ctr=1;
do
{
printf(“%d\n”,ctr);
ctr++;
}
while (ctr<=10);
return 0;
}

Controlling flow
Using break statement
You use a break statement to quit or exit a loop early.

Using continue statement


It forces the computer to perform another iteration of the loop
Format:
continue;
e.g The first printf() in the for loop executes,but the second does not,due to the continue

#include<stdio.h>
main()
{
int ctr;
for(ctr=1;ctr<=10;ctr++)
{
printf(“%d”,ctr);
continue;//causes body to end early
printf(“C programming \n”);
}
return 0;
}

output
1 2 3 4 5 6 7 8 9 10

Working with goto statement


It causes your program to jump to different location,rather than execute the next
statement in sequence.
format

goto statement_label

statement_label is named just as variables.


If you use a goto statement,there must be a statement_label elsewhere in the program
that the goto branches to.
Follow all statement labels with a colon(:)so C knows they are labels and doesn’t
confuse them with variables
Example
#include<stdio.h>
main()
{
Again:
printf(“this message\n”);
printf(“\t keeps repeating\n);
printf(“\t\t over and over\n”);
goto Again;
return 0;
}

C FUNCTIONS
Experience has shown that the best way to develop and maintain a large program is to
construct it from smaller pieces or modules each of which is more manageable than the
original program.
Modules in C are called functions

Two kinds of a function

i. Functions in C standard library


C standard library provides a rich collection of functions for performing
common mathematical calculations,string manipulations,input/output e.t.c
ii. Programmer defined functions
A programmer writes functions to define specific tasks.

Functions are invoked by a function call,which specifies the function name and
provides information(as arguments)that the called function needs inorder to perform its
designated task.
Functions are normally used in a program by writing the name of the function followed
by a left parenthesis followed by the arguments(or a comma separated list of
argument)of the function followed by a right parenthesis.
e.g a programmer desiring to calculate and print the square root of 900.0 might write.
printf(“%2f”,sqrt(900.0));

Function Description Example


sqrt(x) Square root of x sqrt(900.0) is 30.0
sqrt(9.0) is 3.0
exp(x) Exponential function ex exp(1.0) is 2.718282
exp(2.0) is 7.389056
log(x) Natural logarithm of x(base e) log(2.718282) is 1.0
log(7.389056) is 2.0
log10(x) Logarithm of x(base 10) log10(1.0) is 0.0
log10(10.0) is 1.0
log10(100.0) is 2.0
fabs(x) Absolute value of x fabs(5.0) is 5.0
fabs(0.0) is 0.0
fabs(-5.0) is 5.0
ceil(x) Rounds x to the smallest integer ceil(9.2) is 10.0
Not less than x ceil(-9.8) is -9.0
floor(x) Rounds x to the largest integer floor(9.2) is 9.0
Not greater than x floor(-9.8) is -10.0
pow(x,y) X raised to power y(xy) pow(2,7)is 128.0
pow(9,.5)is 3.0
fmod(x,y) Remainder of x/y as a floating fmod(13.657,2.333)is 1.992
point number
sin(x) Trigonometric sine of x sin(0.0)is 0.0
(x in radians)
cos(x) Trigonometric cosine of x cos(0.0)is 1.0
(x in radians)
tan(x) Trigonometric tangent of x tan(0.0)is 0.0
(x in radians)

Reasons for using functions

a. The divide and conquer approach makes program development more


manageable
b. Software reusability-existing functions are used as building blocks to create new
programs.
c. To avoid repeating code in a program-packaging code as a function allows the
code to be executed from several locations in a program simply by calling the
function

NB:Each function should be limited to performing a single,well defined task,and the


function name should effectively express the task.This facilitates abstraction and
promotes software reusability.

Function definitions

Each program we have presented has consisted of a function called main that called
standard library functions to accomplish its tasks.We now consider how programmers
write their own customized function
Format:

return_value_type function_name(parameter_list)
{
definitions
statements
}
 The function_name is any valid identifier.
 The return_value_type is the data type of the result returned to the caller.
 The return_value_type void indicates that a function does not return a value. An
unspecified return_value_type is assumed by the compiler to be int.
N/B However omitting the return type is discouraged.
 Together,the return_value_type,function_name and parameter_list are
sometimes referred to as the function header.
 The parameter_list is a comma-separated list that specifies the parameters
received by the function when it is called.if a function doesn’t receive any
values,parameter_list is void.
 A type must be listed explicitly for each parameter unless the parameter is of
type int.If a type is not listed,int is assumed.

Example
#include<stdio.h>
#define pi 3.142
int main()
{
float radius;
printf(“Please enter radius\n”);
scanf(“%f”, &radius);
circle(radius);
}
float circle(float y)//function definition
{
float Area;
Area=pi*y*y;
printf(“The area is:%f”,Area);
}

Use of return statement/Function return values

This is where a function return a result.You pass data back from a receiving function to
its calling function. When you want to return a value from a function to its calling
function,put the return value after the return statement.
To make the return value clearer, many programmers put parentheses around the return
value, as shown in the following syntax:
return(return value);

Example 1
#include<stdio.h>
int main()
{
int x;
For(x=1;x<=10;x++)
{
printf(“%d”,square(x));
return 0;
}
int square(int y)
{
return y*y;
}

Example 2
/*Calculates the average of three input values*/
#include<stdio.h>
main()
{
int num1,num2,num3;
int avg;
printf(“Please type three numbers\n”);
scanf(“%d,%d,%d”,&num1,&num2,&num3);
avg=calcAv(num1,num2,num3);
printf(“\n\nThe average is %d,avg”);//print the return value
return 0;
}
int calcAv(int num1,int num2,int num3)
{
int localAvg;//Holds the average for three numbers
localAvg=(num1+num2+num3)/3;
return (localAvg);
}

Function prototypes
It tells the compiler the type of data returned by the function ,the number of parameters
the function expects to receive,the types of the parameters,and the order in which these
parameters are expected.
The compiler uses function prototype to validate function calls.

Example 1
#include<stdio.h>
int square(int y)//function prototype
int main()
{
it x;
For(x=1;x<=10;x++)
{
printf(“%d”,square(x));
return 0;
}
int square(int y)//function definition
{
return y*y;
}

Example 2
#include<stdio.h>
void main(void);
float convert(float cType);
void main(void)
{
float cTemp;
float fTemp;
printf(“What is the Celsius temperature to convert?”);
scanf(“%f”,&cTemp);
fTemp=convert(cTemp);
printf(“The Fahrenheit equivalent is %.lf”,fTemp);
return 0;
}
float convert(float cTemp)
{
float fTemp;
fTemp=cTemp*(9.0/5.0)+32;
return(fTemp);
}
NB:You should prototype every function in your program,even main().

Headers

Some of the standard library headers that may be included in programs


Standard library header Explanation
ctype.h It helps to test characters for certain properties and convert
lowercase letters to uppercase and vice versa.
errno.h Defines macros that are useful for reporting error conditions.
math.h Its for math library functions.
stdio.h Its for the standard input/output library functions, and
information used by them.
stdlib.h Its for conversion of numbers to text and text to numbers,
memory allocation, random numbers, and other utility
functions.
string.h Its for string processing functions.
time.h Its for manipulating the time and date.

CALLING FUNCTIONS:Call by value and call by reference


Call by value (by copy)
When arguments are passed by value,a copy of the argument’s value is made and
passed to the called function.Changes to the copy do not affect an original variable’s
value in the caller.
Example

The following program asks users for the weight.It then passes that weight to a function
that calculates the equivalent weight on the moon.

#include<stdio.h>
moon(int weight);
main()
{
int weight;
printf(“How many pounds do you weigh?”);
scanf(“%d”, &weight);
moon(weight);
return 0;
}
moon(int weight)
{
weight/=6;
printf(“You weigh only %d pounds on the moon!”,weight);
return 0;
}

Call by reference(by address)

When you pass an argument(local variable) by address,the variables address is sent to-
and is assigned to-the receiving function’s parameter.The caller allows the called
function to modify the original variable’s value.
To pass a non-array by address,you must do the following:
a. Precede the variable in the calling function with an ampersand(&)
b. Precede the variable in the receiving function with an asterisk(*),everywhere the
variable appears.

#include<stdio.h>
main()
{
int amt;
amt=100;
printf(“Amount is %d\n”,amt);
dofun(&amt);
printf(Amount is %d,amt);
return 0;
}
dofun(int*amt)
{
*amt=85;
printf(“Amount is %d”,*amt);
return 0;
}

Output

Amount is 100
Amount is 85
Amount is 85

C Pointers
Pointers enable programs to simulate call-by-reference,and to create and manipulate
dynamic data structures.i.e data structures that can grow and shrink at execution
time,such as linked lists,queues,stacks and trees.
Pointers are variables that contains addresses of other variables,they contain the
location of regular data variables;they in effect point to the data because they hold the
address of the data.
There are two pointer operators in C:
a. & The “address of” operator.
b. * The dereferencing operator

The * means,of course,multiplication.The asterisk is called an overloaded


operator.Overloaded operators perform more than one kind of operation depending on
how you use them in your programs.C does not confuse * for multiplication when you
use it as a dereferencing operator with pointers.
The & operator always produces the memory address of whatever it precedes.
The * operator,when used with pointers,either declares a pointer or dereferences the
pointer’s value.

Declaring pointers

int * age;//declaring an integer pointer

Some C programmers prefer to declare such a variable without space after the * as
follows:
int *age;

Example 1
#include<stdio.h>
main()
{
int num=123;
int *pNum;
printf(“num is %d\n”,num);
printf(“The address of num is %ld\n”,&num);
pNum=&num;
printf(“*pNum is %d\n”,*pNum);
printf(“pNum is %ld\n”,pNum);
return 0;
}

Output
num is 123
The address of num is 65522
*pNum is 123
pNum is 65522

Example 2
#include<stdio.h>
void swapThem(int *num1,int *num2);
void main(void);
void main(void)
{
int i=10,j=20;
printf(“\n\nBefore swap,i is %d and j is %d\n\n”,i,j);
swapThem(&i,&j);
printf(“\n\nAfter swap, i is %d and j is %d\n\n”,i,j);
return 0;
}
void swapThem(int *num1,int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
return 0;
}

Recursion

This is a function that calls itself either directly or indirectly through another function.
Example 1

/*Recursive factorial function*/


#include<stdio.h>
long factorial(long number);
int main()
{
int i;
for(i=0;i<=10;i++)
{
printf(“%d!=%ld\n”,i,factorial(i));
}
return 0;
}
long factorial(long number)
{
if(number<=1)
{
return 1;
}
else
{
return(number*factorial(number-1));
}
}

Example 2
/*Recursive Fibonacci function*/
#include<stdio.h>
long fibonacci(long n);
int main()
{
long result;
long number;
printf(“Enter an integer”);
scanf(“%ld”, &number);
result=fibonacci(number);
printf(“Fibonacci(%ld)=%ld\n”,number,result);
return 0;
}
long fibonacci(long n)
{
If(n==0 || n==1)
{
return n;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}

Output
Enter an integer:10
Fibonacci(10)=55

C ARRAYS
An array is a group of memory locations related by the fact that they all have the same
name and the same type. To refer to a particular location or element in the array, we
specify the name of the array and the position number of the particular element in the
array.
The first element in every array is the zeroth element .Thus, the first element of array is
referred to as e.g marks[0] if the array name is marks.
The position number contained within square brackets is more formally called a
subscript. A subscript must be an integer or an integer expression.

Defining arrays
Syntax:
Array_type Array_name [Array_Size]

e.g int marks [10]


marks[0] 70
marks[1] 80
marks[2] 54
marks[3]
67 Array element
marks[4]
43
marks[5]
59
marks[6]
21
marks[7]
marks[8] 89
marks[9] 12
31
Using initializer list
#include<stdio.h>
int main()
{
int marks[10]={70,80,54,67,43,59,21,89,12,31};
int i;
for(i=0;i<10;i++)
{
printf(“%d\n ”,marks[i]);
}
return 0;
}

Using a loop to initialize the array’s element

#include<stdio.h>
int main()
{
int marks[10];
int i;
printf("Please enter marks\n");
for(i=0;i<10;i++)//assigning values
{
scanf("%d", &marks[i]);
}
for(i=0;i<10;i++)//displaying values
{
printf("%d", marks[i]);
}
return 0;
}

Summing the elements of an array


#include<stdio.h>
#define SIZE 10
int main()
{
int a[SIZE]={45,23,12,43,64,32,76,30,54,93};
int i;
int total=0;
for(i=0;i<SIZE;i++)
{
total+=a[i];
}
printf(“Total of array element values is %d\n”,total);
return 0;
}

Multiple-Subscripted Arrays
A common use of multiple-subscripted arrays is to represent tables of values consisting
of information arranged in rows and columns.To identify a particular table element,we
must specify two subscripts.The first (by convention)identifies the element’s row and
the second(by convention)identifies the elements column.
Tables or arrays that require two subscripts to identify a particular element are called
double-scripted arrays.
NB:Multiple-subscripted arrays can have more than two subscripts.
An array with m rows and n columns is called an m-by-n array.

Column
0 1 2 3
Row 0 a[0][0] a[0][1] a[0][2] a[0][3]

1 a[1][0] a[1][1] a[1][2] a[1][3]


a[2][0] a[2][1] a[2][2] a[2][3]
2

Array Row Column


name Subscript subscript

Initializing a multiple subscripted array

int b[2][2]={{1,2},{3,4}};
STRUCTURES

Structures sometimes referred to as aggregates are collections of related variables under


one name. Structures may contain variables of many different data types.
Structures are commonly used to define records to be stored in files.
Defining structures
To define a structure,you must use the struct statement.
Format:

struct[structure tag]
{
Member definition;
Member definition;
.
.
Member definition;
}[one or more structure variables];

Example:
struct cdCollection
{
char title[25];
char artist[20];
int numSongs;
float price;
char dateBought[9];
} cd1, cd2, cd3;
Initializing structure data

There are two ways to initialize members of a structure


a. When you declare a structure
b. Within the body of the program

Structure declared and initialized at the same time


struct cdCollection
{
char title[25];
char artist[20];
int numSongs;
float price;
char dateBought[9];
} cd1={“Red Moon Men”,”Sam and the sneeds”,12,11.95,”25/12/2010”};
Structure declared within the body of the program

A better approach to initializing structures is to use the dot operator(.)


Its one way to initialize individual members of a structure variable within the body of
the program
Format:
structureVariableName.memberName

#include<stdio.h>
#include<string.h>
Main()
{
Struct cdcollection
{
char title[25];
char artist[20];
int numSongs;
float price;
char dateBought[9];
} cd1;

/*initialize members here*/


strcpy(cd1.title,”red moon men”);
strcpy(cd1.artist,”sam and the sneeds”);
cd1.numsongs=12;
cd1.price=11.95;
strcpy(cd1.datebought,”25/12/2010”);

/*print the data to the screen*/


printf(“Here is the CD information:\n\n”);
printf(“Title:%s \n”,cd1.title);
printf(“Artist:%s \n,cd1.artist”);
printf(“Songs:%d\n”,cd1.numsongs) ;
printf(‘’Price:%.2f\n’’,cd1.price);
printf(“Date bought:%s\n”,cd1.dateBought);

return 0;
}

Output
Here is the CD information:
Title: red moon men
Artist: sam and the sneeds
Songs: 12
Price: 11.95
Date bought: 25/12/2010
Declaring arrays of structures
The following structure definition defines the inventory:

struct inventory
{
long int storage;
int accessTime;
char vendorCode;
double code;
double price ;
}drive[125] ;/*defines 125 occurences of the structure*/

Unions
It’s a derived data type-like a structure-with members that share the same storage space.
For different situations in a program, some variables may not be relevant, but other
variables are-so a union shares the space instead of wasting storage on variables that are
not being used.
The members of a union can be of any data type. The number of bytes used to store a
union must be at least enough to hold the largest member.
Only one member, and thus one data type, can be referenced at a time.
A union is declared with keyword union in the same format as a structure.

Union definition:
union number
{
int x;
double y;
};

Union definition is normally placed in a header and included in all source files that use
the union type.

You might also like