0% found this document useful (0 votes)
78 views

Bit 113fundamentals of Programming Part One

This document provides information about the BIT 113 Fundamentals of Programming course offered at Kibu University during the 2023/2024 academic year. The course aims to impart an understanding of fundamental programming concepts and problem solving. It will cover topics like algorithms, control structures, data structures, and the C programming language. Students will learn to design solutions to simple problems and create programs to solve them. Assessment will consist of exercises, exams, and continuous assessments worth 30% of the final grade.

Uploaded by

muchesiaseth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Bit 113fundamentals of Programming Part One

This document provides information about the BIT 113 Fundamentals of Programming course offered at Kibu University during the 2023/2024 academic year. The course aims to impart an understanding of fundamental programming concepts and problem solving. It will cover topics like algorithms, control structures, data structures, and the C programming language. Students will learn to design solutions to simple problems and create programs to solve them. Assessment will consist of exercises, exams, and continuous assessments worth 30% of the final grade.

Uploaded by

muchesiaseth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

BIT 113 FUNDAMENTALS OF PROGRAMMING

Academic Year: 2023/2024 Semester: I

Lecturer: Dr. Roselida Maroko Ongare

Contact: 0721597710/0780617537 Email Address: [email protected]

Room: ABB206

Aim/Purpose: To impart an understanding of fundamental concepts underlying programming and


problem solving.

Pre-requisite: None

Course Hours per Week: Lecture: 2 Practical: 3. Semester Hours Credit 3.

Expected Learning Outcomes


By the end of this course, the student will be able to:
1. Demonstrate knowledge of fundamental issues in programming
2. Create algorithms for solving simple problems.
3. Create simple programs using C
4. Create programs involving sequence, selection, and iteration control structures
5. Use C language to develop, test, and debug programs for solving simple problems.
6. Describe fundamental issues in programming
7. Create algorithms for solving programming problems.

COURSE OUTLINE
Week Activity Assessment
1 Introduction
• Fundamental concepts of computing
o Hardware
o Software
• History and overview of programming languages
2 Overview of programming paradigms
• Structured programming
• Procedural programming
• Object oriented programming
3 • Problem solving techniques Exercise 1
o Algorithms
o pseudo code
o flowcharts
4 Introduction to C Exercise 2
• Basic syntax and semantics

Page 1 of 66
Week Activity Assessment
5 Variables, data types, and expressions Exercise 3
• Identifier rules
o Naming variables and constants
6 CAT 1
7 Operators Exercise 4
• Arithmetic Operators
• Assignment Operators
• Relational and Logical Operators
8 • Input/output statements Exercise 5
• Control structures
o Sequencing
o Selection
9 Control structures Exercise 6
• Iteration
10 Data structures Exercise 6
• Arrays
11 CAT 2
12 Subprograms Exercise 7
• Functions and procedures
13 Files Exercise 8
14 Revision

Mode of Delivery
Lectures, tutorials, lab demonstrations and practical exercises

Assessment
Written examination at end of Semester: 70%
Continuous Assessment: 30%

Total 100%

References
1. Kochan S. C. (2001). Programming in C Delhi : CBS Publishers & Distributors
2. Neibauer A.R. (1994) Your first C/C++ program. New Delhi : BPB Publications, ISBN 81-
7029-371-5

Approval

--------------------------------------------------------------- -------------------
Lecturer/Instructor Date

--------------------------------------------------------------- -------------------
COD Information Technology Date

Page 2 of 66
Page 3 of 66
Topic 1: Fundamental concepts of computing

Fundamental concepts of computing encompass the foundational principles and ideas that
underpin the field of computing and its practical applications. These concepts provide the basis
for understanding how computers work, how data is processed, and how algorithms operate.

1. Binary Representation:
• Computers use a binary system (0s and 1s) to represent and process data at the hardware
level.
• Binary digits (bits) are used to encode all types of information, including numbers, text,
and instructions.
2. Data vs. Information:
• Data refers to raw facts, symbols, or values.
• Information is meaningful data that has been processed or organized in a way that humans
can understand and use.
3. Algorithms:
• Algorithms are step-by-step procedures or sets of rules for solving specific problems or
performing tasks.
• They are the fundamental building blocks of computer programs.
4. Programming:
• Programming involves writing instructions (code) that a computer can execute to perform
specific tasks.
• Programming languages like Python, Java, C++, and JavaScript are used to create
software.
5. Data Structures:
• Data structures are organized ways of storing and manipulating data, such as arrays, linked
lists, and trees.
• Choosing the right data structure is critical for efficient problem-solving.
6. Computational Thinking:
• Computational thinking is a problem-solving approach that involves breaking down
complex problems into smaller, manageable parts.
• It includes techniques like decomposition, pattern recognition, and algorithm design.
7. Hardware vs. Software:
• Hardware includes physical computer components like the central processing unit (CPU),
memory, and storage devices.
• Software refers to the programs, applications, and data that run on computer hardware.
8. Operating Systems:
• Operating systems (e.g., Windows, macOS, Linux) manage hardware resources, provide
user interfaces, and support software execution.
9. Networks and the Internet:
• Networks enable computers to communicate and share information. - The Internet is a
global network of interconnected computers, facilitating data exchange and online
services.

Page 4 of 66
13. Databases: - Databases store, retrieve, and manage structured data efficiently. - SQL
(Structured Query Language) is a common language for working with databases.

14. Cybersecurity: - Cybersecurity involves protecting computer systems, networks, and data
from unauthorized access, attacks, and breaches.

15. Software Development Life Cycle (SDLC): - SDLC is a systematic process for planning,
designing, developing, testing, deploying, and maintaining software.

16. Artificial Intelligence (AI): - AI involves creating computer systems that can perform tasks
that typically require human intelligence, such as problem-solving and learning.

17. Cloud Computing: - Cloud computing provides on-demand access to computing resources
(e.g., servers, storage, databases) over the internet.

18. Human-Computer Interaction (HCI): - HCI focuses on designing user-friendly interfaces


and interactions between humans and computers.

19. Big Data: - Big Data deals with large and complex datasets that require specialized tools and
techniques for storage, processing, and analysis.

20. Ethics and Privacy: - Ethical considerations in computing include responsible data use,
privacy protection, and addressing societal impacts.

These fundamental concepts form the basis for a wide range of computer science disciplines,
including software development, data science, artificial intelligence, and more. They are
essential for anyone studying or working in the field of computing.

Computer
A computer is an electronic device that accepts data from an input device, processes the data into
information using program instructions, provides information in a useful format and stores the
information for future use.

A computer can also be defined as a programmable machine that receives input, stores and
manipulates the input and provides output in a useful format.

A computer can also be defined as an electronic device that accepts data and manipulates it into
useful information based on a program or sequence of instructions.

Computer System
A computer system consists of hardware; the physical devices that are capable of manipulating
and transforming data into information, and software; programs that carry out predefined
instructions to complete a given task. Computer software communicates with the hardware to
perform useful tasks; the software organizes the control sequences, and the hardware carry out the

Page 5 of 66
instructions defined by the software.

Computer Hardware
Computer hardware refers to the physical or tangible parts of a computer.

The block diagram below shows a basic model of a computer with input, process, storage and
output functionalities.

Storage
Devices

Input Devices Processing Output Devices


Devices (CPU)

Basic model of a computer

• Input devices are the devices used to feed or enter data into the computer.
• Processing devices are the devices used to manipulate or transform data into information.
• Output devices are the devices used to translate information processed by the computer
into a form that humans can understand.
• Storage devices are the devices used to store data and program instructions.

Computer Software
A computer software (also known as computer program) is a set of ordered instructions that enable
computer hardware to carry out a specific task.

Programming Fundamentals
We are always faced problems (tasks) that require solutions in every aspect of our lives. A
problem is any task that requires a solution. The problem may be simple or complex. Finding
solutions to simple problems is relatively easy however as the problem becomes complex so does
the problem solving procedure. Because of their accuracy, speed, diligence, and versatility
computers have become indispensable problems solving devices in modern times. Hence computer
is now an essential part of our daily life.

A problem may be simple or complex. In order to come up with a solution we must:


1. Have a clear understanding of the problem.
2. Determine what you need to help solve the problem.
3. Decide what results you want to achieve.
4. Consider different ways to achieve result and select the best one.

Why learn programming

Page 6 of 66
All the computer applications we use, the internet, games, entire businesses are made up of
programs, and someone has written them. The ability to create programs is important if you want
to participate in building the future especially in this digital age. The understanding of what can
and can’t be achieved with a program is important, even if you don’t write programs. People are
needed to design, document and specify programs, as well as code them.

Program
For computer hardware to perform a useful task it must be given a set of instructions to tell it what
to do.

A program is a sequence of instructions used to carry out a particular job. A program can also be
defined as:
• An organized list of instructions that, when executed, causes the computer to behave in a
predetermined manner.
• A series of coded instructions for the computer to obey in order to solve a problem.

The computer executes these instructions (obeys the instructions) when told to do so by the user.
The number of these instructions varies, depending on the complexity of the program.

New programs are usually only created if there is no existing program that will perform the same
job. Writing a program involves a lot of work so if you can carry out a task with an off-the-shelf
package such as a database you will probably find it much easier and cheaper to use the existing
package. Developing a sophisticated computer program may take many thousands or even tens of
thousands of man hours.

Programming
This is the activity of writing computer programs. Programming therefore involves writing specific
instructions in a programming language and having them translated into machine language.

Programming Languages
All over the world, language is the source of communication among human beings. Different
countries/regions have different languages. Similarly, in order to communicate with the computer
user also needs to have a language that should be understood by the computer. For this purpose,
different languages are developed for performing different types of work on the computer.

Programming languages refer vocabulary and set of grammatical rules for instructing a computer
to perform specific tasks. Each language has a unique set of keywords (words that it understands)
and a special syntax for organizing program instructions. Syntax refers to the spelling and
grammar of a programming language. Computers are inflexible machines that understand what
you type only if you type it in the exact form that the computer expects. The expected form is
called the syntax. Each program defines its own syntactical rules that control which words the
computer understands, which combinations of words are meaningful, and what punctuation is
necessary.

Page 7 of 66
History and overview of programming languages
Programming languages date back to 1940s the same time digital computers were invented. During
this period the only programming language was machine language or machine code.

The first assembly languages emerged in the late 1950s with the introduction of commercial
computers.

The first procedural languages were developed in the late 1950s to early 1960s: FORTRAN
(FORmula TRANslation), created by John Backus, and then COBOL (COmmon Business
Oriented Language), created by Grace Hopper. The first functional language was LISP (LISt
Processing), written by John McCarthy in the late 1950s. Although greatly updated, all three
languages are still widely used today.

In the late 1960s, the first object-oriented languages, such as SIMULA, emerged. Logic languages
became well known in the mid-1970s with the introduction of PROLOG, a language used to
program artificial intelligence software. During the 1970s, procedural languages continued to
develop with ALGOL, BASIC, PASCAL, C, and Ada. SMALLTALK was a highly influential
object-oriented language that led to the merging of object-oriented and procedural languages in
C++ and more recently in JAVA. Although pure logic languages have declined in popularity,
variations have become very important in the form of relational languages for modern databases,
such as SQL (Structured Query Language).

Programming languages can be classified according to:


• Level (low & high level)
• Generation (1GL, 2GL, 3GL, 4GL & 5GL)

Levels of Programming Languages


There is only one programming language that any computer can understand and execute; its own
native binary machine language (machine code). This is the lowest possible level of language in
which it is possible to write a computer program. Programming languages are said to be high level
or low level according to how closely they resemble machine code. All the programming languages
that are closer to the machine code (code which the computer understands) are low-level
languages and the ones which are closer to the English language (what humans understand) are
high-level languages. Languages might contain keywords and sentences from the English words
or words derived from the English words.

Low Level Programming Languages


Programming languages are said to be low if they are closer to the machine language than the
natural language.

Low level programming languages are machine oriented (or machine dependent). Thus each
language is unique to the CPU on which it is implemented and is, therefore, not usable on a
computer with a different CPU (i.e. not portable).

Low level languages have the advantage that they can be written to take advantage of any
peculiarities in the architecture of the central processing unit (CPU). Thus, a program written in a

Page 8 of 66
low level language can be extremely efficient, making optimum use of both computer memory and
processing time. To write a low level program takes a substantial amount of time. The programmer
must also have a clear understanding of the inner workings of the processor. Therefore, low level
programming is typically used only for very small programs, or for segments of code that are
highly critical and must run as efficiently as possible.

There are two categories of low level programming languages; Machine Language and Assembly
Language.

Machine Language
This is the lowest and most elementary level of Programming language and was the first type of
programming language to be developed. A computer can only process (execute) instructions that
are written in machine code. A machine code instruction is a sequence of 1s and 0s. Machine
Language is basically the only language which computer can understand. The language is made
up of binary coded instructions built into the hardware of a particular computer and used directly
by the computer. In fact a manufacturer designs a computer to obey just one language, its machine
code, which is represented inside the computer by a string of binary digits (bits) 0 and 1. The
symbol 0 stands for the absence of Electric pulse and 1 for the presence of an electric pulse. Since
a computer is capable of recognizing electric signals, therefore, it understands machine language.

Initially, humans had no choice but to write programs in machine language because other
programming languages had not yet been invented

An example instruction which test if a bit in memory is set to 1 is 0010100101110100110110.

The machine code program below will convert an upper case letter stored in a particular memory
location to lower case:

Machine Code Program Explanation


000011010100101010000000 Load the contents of memory location E00 into the accumulator.
01101001 Clear the carry flag.
60010101001000000 Add 32 to the content of the accumulator.
000001010100101010000000 Store the result back in memory location E00.

Characteristics of Machine Language


i. It is made up of binary coded instructions built into the hardware of a particular computer and
used directly by the computer
ii. Every processor type has its own set of specific machine instructions
iii. The relationship between the processor and the instructions it can carry out is completely
integrated
iv. Each machine-language instruction does only one very low-level task

Advantages of Machine Language

Page 9 of 66
i) They make efficient use of the computer resources such as the processor speed and main
memory
ii) They are faster to execute because the programs are in a language the computer can
understand
iii) It requires no translator to translate the code i.e. it is directly understood by the computer.

Disadvantages of Machine Language


i) All operation codes and memory addresses have to be remembered which makes them very
difficult to use.
ii) It is hard to find or correct errors in a program written in the machine language
iii) These languages are machine dependent i.e. a particular machine language can be used on
only one type of computer hence they are not portable.
iv) They are difficult to decipher and requires the aid of a reference manual to decode
v) It is easy to make mistakes while programming
vi) It is difficult to develop programs using machine language
vii) Difficult to be read and understood by humans since all the instructions and data must be
in binary code.

Assembly Language
Assembly language was developed to overcome some of the many inconveniences of machine
language. It is written using mnemonic codes (abbreviated English words) or short codes that
suggest their meaning and are therefore easier to remember. These codes represent operations,
addresses that relate to main memory, and storage registers of the computer. Examples of these
codes include ADD for addition, SUB for subtraction, STO for store etc.

The assembly language equivalent of the program above is:


Assembly Program Explanation
LDA &E00 Load the contents of memory location E00 into the accumulator.
CLC Clear the carry flag.
ADC #32 Add 32 to the content of the accumulator.
STA &E00 Store the result back in memory location E00.

The program is still quite difficult to understand, but the instructions used in the program
are much easier to remember than the binary codes in the machine code program.

An example of a program code to add and store two numbers would be:
LDA A, 20 load accumulator A with the value 20
ADD A, 10 add the value 10 to accumulator A
STO B, A store contents of accumulator A into storage register B
NOP no operation (stop here)

Assembly languages are translated into machine language by language translators known as
assemblers.

Page 10 of 66
Advantages of Assembly Language
(i) Easy to understand and use compared to machine language. This saves a lot of time and
effort of the programmer.
(ii) It is much easier to learn assembly language instructions than machine code instructions.
(iii) Programs written in assembly language are executed faster than programs written in a high-
level language.
(iv) Programs written in assembly language use up less memory than high level languages
(v) It is easier to correct errors (debug) and modify program instructions in assembly language
than in machine language.

Disadvantages of Assembly Language


(i) It is fairly harder to remember the instructions than high level languages
(ii) It is machine dependent hence not portable. Thus Programs written in assembly language on
one computer will not work on a different type of computer.
(iii) Since it is machine dependent the programmer should have the knowledge of the hardware.
(iv) It requires a translator to translate the source code into machine code as it is not directly
understood by the computer

Advantages of Low-Level Programming Languages


(i) Low level languages are executed much faster than high level programming languages
(ii) Low level languages make optimum use of the computer resources e.g. computer memory
and processor.

Disadvantages of Low-Level Programming Languages


(i) They are machine dependent hence not portable
(ii) They are not user friendly
(iii) They are difficult to learn
(iv) It’s difficult to develop complex programs
(v) It is not easy to write and modify programs using low level languages
(vi) Low level language programs are not easy to debug (detecting and correct errors).

High Level Programming Languages


The lack of portability between different computers led to the development of high-level
languages; so called because they permitted a programmer to ignore many low-level details of the
computer's hardware and concentrate on solving the problem.

Thus they are problem oriented. Further, it was recognized that the closer the syntax, rules, and
mnemonics of the programming language could be to "natural language" the less likely it became
that the programmer would by mistake introduce errors (called "bugs") into the program. Hence,
in the mid-1950s the first high level languages were introduced (third generation of languages).
These languages are closer to human languages than the machine code.

A high level language is governed by a strict syntax (set of grammatical rules). Since the syntax
of high level languages are standardized, the languages are portable (they can be used on different
computer systems). Thus high level languages are machine independent.

Page 11 of 66
Characteristic of High Level Language
• Program instructions are similar to natural languages.
The high Level Languages are close to human languages. The instructions written in high
level languages are similar to English like words and statements. This makes the high
level languages easy to learn and use.
• Simplicity of program logic
The logic of the program written in high level languages is very simple and easy.
The instructions of program are like English language statements. In case of errors, it is very
easy to detect (or find) and remove errors in the program. It is also easy to modify the program.
• Machine Independent
The program written in High Level Language is machine independent. It means that a program
written or compiled on one type of computer can be executed (run) on another different type
of computer that has different architecture. For Example, a program written on a computer
using Intel Processor can be run on computer having Motorola Processor
• Availability of Library Functions
Every High Level Language provides a large number of built in functions (or library functions)
that can be used to perform specific tasks during designing of new programs. For Example, to
computer the square root of a number, the programmer can use the available built in function
without writing its own code. This way of writing a program reduces the development time of
a program. This software is developed in a very short time.
• Shorter program
The Program written in high level language is shorter than the program written in low level
language. A single instruction of the program written in high level language may be equivalent
to many instructions of low level programming language.
• Well defined syntax and standard
Every high level language has a standard syntax. The standard is approved (or established) by
international organization. The most popular organization is ANSI (American National
Standard Institute). The translator programs are written according to the standard syntax of the
language. Therefore, high level languages describe a well-defined way of writing programs.
• Source code is understandable by another programmer
The instructions of the program written in high level language are like English language
statements. These are written according to the standard syntax of the language. Therefore, a
computer programmer can easily understand a program written by another programmer.

Advantages of high-level languages


• They are machine independent hence portable
• They are user friendly (easy to use)
• They are easy to learn
• Programs are easy to debug (locate and correct errors)
• They permit faster development of complex programs
• They are more flexible hence they enhance the creativity of the programmer thus increasing
productivity

Disadvantages of high-level languages


• They are executed much slower than low level programming languages
• Programs have to be translated into machine code before execution
Page 12 of 66
• One instruction translates into several machine code instructions hence requires more storage
space

Comparison between High-Level and Low-Level Languages

High-Level Languages Low-Level Languages

Are in machine code or closer to


Closer to human language
machine code

Low development time High development time

Easy to write, read and modify Difficult to write, read and modify

Slower execution Faster execution

Larger file size Small file size

Machine independent Machine dependent

Language Translators
A computer does not understand assembly languages or high level languages. Computers work in
machine code or machine language. Language translators are system programs that convert
assembly language and high level language into the machine language.

Source code
Source code is a program of either an assembly language or high level language that the
programmers write in a program editor that has not been translated into machine code.

Object Code
Object Code is a program in machine readable form (source program that has been translated into
machine code).

Functions of Language Translators


1. Translate source code into object code
2. Identify syntax errors by providing diagnostic and useful error messages
3. Work out where to store the object code and its data
4. Produce a list of the source code and object code
5. Provide links to other programs and routines

Types of Language Translators

Assemblers
Assembly-language program must be translated into machine code by a program called an
assembler. The assembler program recognizes the character strings that make up the symbolic
names of the various machine operations, and substitutes the required machine code for each

Page 13 of 66
instruction. At the same time, it also calculates the required address in memory for each symbolic
name of a memory location, and substitutes those addresses for the names.

Compilers
Compilers are language translators that translate high level languages into machine code.

A compiler translates the entire program (source code) to machine code, and then the code is
executed. The translated codes are known as object codes and are saved as a file on disk. The
object code (machine code) stored on disk has an EXE file name extension.

Advantages
• It can be executed faster than when using an interpreter
• The object codes are saved and can be run at any time.

Disadvantages
• As the entire program is translated to object code, it uses much more of the computer’s
memory.

Interpreters
Interpreters are language translators that translate high level language into machine code. An
interpreter translates and executes one statement at a time as it is encountered. The machine codes
are not saved after execution.

This use of interpreters to directly execute the user's program has both advantages and
disadvantages.

Advantages
• You can run the program to test its operation, make a few changes, and run it again directly.
There is no need to recompile because no new machine code is ever produced. This can speed
up the development and testing process.
• It translates one statement at a time therefore it uses a minimum amount of the computer’s
memory.
• It is also helpful in the debugging process, as the interpreter can relate error messages to the
statement being executed.

Disadvantages
• The interpreter takes longer to run a program as time is spent interpreting the source code every
time the program needs to be run.
• It requires that both the interpreter and the user's program reside in memory at the same time.
• Object code cannot be saved on disk.

Comparison between Compilers and Interpreters

Page 14 of 66
Compilers Interpreters

Translates the source code statement


Translates the whole source code at
by statement and executes the
once before it can be executed (run
statement before moving to the next
later)
statement (run immediately)

Creates an object (executable) code Object code is only created in the


which can be saved and run later memory

The program need only be The program is translated each time


translated once it is run

Compiled programs run faster Interpreted programs run slower

Generation of Programming Languages


Many programming languages have been developed over the years hence programming languages
have evolved from First generation (1GL) to Fifth generation (5GL) with the latter generations
being closer to natural languages than the former. In the computer industry, these generations are
widely used to represent major steps in the evolution of programming languages.

There are currently five generations of computer programming languages. In each generation, the
languages syntax has become easier to understand and more human-readable.

Low level languages can be grouped into two generations;


• First Generation Languages (1GLs) – Machine Languages
• Second Generation Languages (2 GLs) – Assembly Languages

High level languages have evolved over the years hence can be grouped into five categories;
• Third Generation Languages (3GLs)
• Fourth Generation Languages (4GLs)
• Object Oriented Programming Languages (OOP)
• Fifth Generation Languages (5GLs)
• Scripting Languages.

Third Generation Languages (3GL)


A third generation (programming) language (3GL) is a grouping of programming languages that
introduced significant enhancements to second generation languages, primarily intended to make
the programming language more programmer-friendly. English words are used to denote
variables, programming structures and commands, and Structured Programming is supported by
most 3GLs.

3GLs are procedural or algorithmic languages. Procedural oriented language program instructions
comprise lists of steps (procedures) that tell the computer what to do by specifying all the steps for
doing it.

Page 15 of 66
Examples of 3GLs include:
• FORTRAN (Formula translation) developed (1953–57) for scientific and engineering
applications by John Backus at the IBM Corp.
• LISP (LISt Processing) developed by John McCarthy at the Massachusetts Institute of
Technology in the early 1950s and implemented in 1959. LISP has become the standard
language for the artificial intelligence community.
• COBOL (COmmon Business Oriented Language), the first language intended for
commercial applications, is still widely used; it was developed by a committee of computer
manufacturers and users under the leadership of Grace Hopper, a U.S. Navy programmer, in
1959.
• ALGOL (ALGOrithmic Language), developed in Europe about 1958, is used primarily in
mathematics and science
• APL (A Programming Language), published in the United States in 1962 by Kenneth Iverson
is used primarily in mathematics and science
• PL/1 (Programming Language 1), developed in the late 1960s by the IBM Corp.
• ADA (for Ada Augusta, countess of Lovelace, biographer of Charles Babbage), developed
in 1981 by the U.S. Dept. of Defense, are designed for both business and scientific use.
• BASIC (Beginner's All-purpose Symbolic Instruction Code) was developed by two
Dartmouth College professors, John Kemeny and Thomas Kurtz, as a teaching tool for
undergraduates (1966); it subsequently became the primary language of the personal
computer revolution.
• Pascal (for French mathematician Blaise Pascal, who built the first successful mechanical
calculator) developed in 1971 by Swiss professor Nicholas Wirth for teaching.
• Modula 2, a Pascal like language for commercial and mathematical applications, was
introduced by Wirth in 1982.
• C developed by Dennis Ritchie of Bell Laboratories in 1972 to implement the UNIX
operating system.
• Logo developed in 1968 at MIT to facilitate learning mathematics concepts. It has become
the language of choice for introducing programming to young school children.

Fourth Generation Language (4GL)


4GL is a non-procedural oriented language. Non procedural instructions only tell the computer
what to do without specifying all the procedure (steps) for doing it. 4GLs are closer to human
language than 3GLs. They are user friendly and allow multiple common operations to be
performed with a single programmer-entered command. They are intended to be easier for users
than 1GLs, 2GLs and 3GLs. Most 4GLs are used to access databases.

Advantages of 4GLs
• They possess friendly interfaces
• The time taken to develop software is reduced
• Requires less coding than lower (1 GL, 2GL & 3GL) languages
• Reduces the cost of software development
• They contain a built-in function wizard to assist the user in solving problems
• They are easier to use than previously used high level languages
• The programming language is closely linked to the English language structure

Page 16 of 66
Disadvantages of 4GLs
• 4GL programs run slower than those of earlier language generations because their machine
code equivalent is considerably longer and more complicated to execute

Examples of 4GLs
• Database query languages, e.g. SQL (Structured Query Language)
• Report generators, e.g. Oracle Report, RPG-II, RPG-III, RPG-IV (Report Program Generator)
• Data manipulation, analysis and reporting languages, e.g. Focus
• Data stream languages, e.g. Iris Explorer
• Screen painters and generators, e.g. Oracle Forms
• GUI (graphical user interface) creators, e.g. Visual Basic

Software tools that use graphical interfaces for building applications or generating queries are also
considered fourth generation. Underlying the menus and buttons are fourth-generation command
structures that are activated with a click of the mouse.

Fifth Generation Languages (5GLs)


Fifth-generation programming language (5GL) or logical language is a programming language
based around solving problems using constraints given to the program, rather than using an
algorithm written by a programmer. 5GLs give people a more natural connection with computers.
The main difference between fourth-generation programming languages and fifth-generation
languages is fourth-generation languages are designed to build specific programs while fifth
generation languages are designed to make the computer solve the problem for you. This way the
programmer only needs to worry about what problems needs to be solved and what conditions
need to be met without worrying about how to implement a routine or algorithm to solve them.
Fifth-generation languages are used mainly in Artificial intelligence research.

Advantages of 5GLs Languages


• Logical Languages are quite reliable.
• Best suited for problems in which knowledge base can be established to come to a solution.
• Programs can be quickly developed as it uses true/false statements, rather than objects, etc.

Disadvantages of 5GLs Languages


• Limited to which types of problems it can efficiently solve.
• The programs execution can be slow.
• True/false statements cannot solve most problems--at all.

Examples of 5GLs are OPS5 (Official Production System), Prolog (Logical Programming) and
Mercury.

Here is an example of Prolog programming language:

girl(Mercy). (The program code “Sarah is a girl”)


?- girl(Mercy). (Question asked “Is Sarah a girl?”)

Page 17 of 66
yes. (The program returns yes)
?-girl(Omondi). (Question asked “Is Omondi a girl?”)
no. (The program returns no.)

Scripting (Internet Programming) Languages


Internet programming languages or Web languages are high level languages used to create and
edit web pages. These languages can do anything from putting plain text on a webpage, to
accessing and retrieving data from a database. They vary greatly in terms of power and complexity.

Some of these languages include:


1. Hypertext Markup Language (HTML) is a used to create Web pages. It is the core language of
the World Wide Web that is used to define the structure and layout of web pages by using
various tags and attributes. Although a fundamental language of the web, HTML is static -
content created with it does not change. HTML is used to specify the content a webpage will
contain, not how the page functions. It is a collection of tags which, when inserted into regular
text, tell a Web browser how to:
– format text,
– insert an image, video clip, or sound into a Web page,
– link to another location in the page or another Web page, even on another computer
(server) or
– link to other programs written in Java, JavaScript, or other languages.
2. Python is an object-oriented scripting language
3. Extensible Markup Language (XML). This is a language developed by the W3C (W3C is short
for World Wide Web Consortium, an international consortium of companies involved with the
Internet and the Web. It works like HTML, but unlike HTML, allows for custom tags that are
defined by programmers. XML allows for the transmission of data between applications and
organizations through the use of its custom tags.
4. JavaScript is a language developed by Netscape used to provide dynamic and interactive
content on web pages. With JavaScript it is possible to communicate with HTML, create
animations, create calculators, validate forms, and more. JavaScript is often confused with
Java, but they are two different languages.
5. VBScript (Visual Basic Scripting Edition) is a language developed by Microsoft that works
only in Microsoft's Internet Explorer web browser and web browsers based on the Internet
Explorer engine such as FlashPeak's Slim Browser. VBScript can be used to print dates, make
calculations, interact with the user, and more. VBScript is based on Visual Basic, but it is much
simpler.
6. PHP (Hypertext Preprocessor) is a powerful language used for many tasks such as data
encryption, database access, and form validation.
7. Java is a powerful and flexible language created by Sun MicroSystems that can be used to
create applets (a program that is executed from within another program) that run inside web
pages as well as software applications. Things you can do with Java include interacting with
the user, creating graphical programs, reading from files, and more.
8. Virtual Reality Markup Language (VRML)
Virtual Reality Markup also known as Visual Reality Modeling Language is a language for
describing three-dimensional (3-D) image sequences and possible user interactions to go with
them. Using VRML, you can build a sequence of visual images into Web settings with which

Page 18 of 66
a user can interact by viewing, moving, rotating, and otherwise interacting with an apparently
3-D scene.

Programming Language Paradigms


Like many human languages, different programming languages use very different basic ways of
thinking to achieve much the same results. These are called paradigms. Sometimes, one
paradigm is distinctly superior for a given type of task (e.g., programming artificial intelligence,
or creating device drivers) and programmers are typically familiar with several languages so
they can employ the most appropriate language to most efficiently achieve a required result.

Non-Structured Programming
This style of programming helps us to write small and simple programs. If application becomes
very large then it poses real difficult in terms readability, modification and ease of use. In this
programming no separate procedure were written for repetitive task. Generally we avoid such type
of programming.

A program in a non-structured language usually consists of sequentially ordered commands, or


statements, usually one in each line. The lines are usually numbered or may have labels: this allows
the flow of execution to jump to any line in the program. Non-structured programming introduces
basic control flow concepts such as loops, branches and jumps. Although there is no concept of
procedures in the non-structured paradigm, subroutines are allowed. Unlike a procedure, a
subroutine may have several entry and exit points.

Structured Programming
This is computer programming in which the statements are organized in a specific manner to
minimize error or misinterpretation. This style of programming helps us to broken down a large
program into small independent tasks that are easy to understand without having to understand the
whole program. These tasks are developed independently, without the help of other tasks. When
these tasks are completed then these are combined together to solve the problem. Structured
programming can be performed on two ways: procedural and modular.

Procedural Programming
Procedural Programming focuses on the steps with which to complete a task. These languages
define sequences of commands for the computer to perform. Procedural Programming breaks
down tasks into variables, data structures, and subroutines. These procedures can be called at any
given time to carry out its specific function within the programs execution.

Advantages of Procedural languages


• Procedural languages are easier to learn and easier to use than OOP
• Procedural languages execute quickly.
• Procedural language code can be reused in various parts of the program.

Disadvantages of Procedural languages


• Program code is harder to write.

Page 19 of 66
• There are no great tools for abstraction and modularization in procedural languages thus, it is
hard to add new functionality or change the work flow without going back and modifying all
other parts of the program.
• Procedural code is not easily reusable, so programmers must often recreate the wheel, if the
wish to use similar code in another application.

Modular Programming
Modular programming is the process of subdividing a computer program into separate sub-
programs.

A module is a separate software component. It can often be used in a variety of applications and
functions with other components of the system. Similar functions are grouped in the same unit of
programming code and separate functions are developed as separate units of code so that the code
can be reused by other applications. Modular programming has evolved into object-oriented
programming, which provides formal rules for developing self-contained software modules

Characteristics of a Module
• A module is complete program unit in itself containing the processing logic.
• A module is designed to perform a well-defined job or task.
• A module can be compiled, tested and debugged separately without the intervention of the
other modules.
• There is only entry and one exit point for a module.
• A module can interact with other modules i.e. it can call other modules.
• A module is designed in such a manner that it can be used with different programs or software
systems.

Advantages of modular programming


• Easier to Debug: When debugging large programs, how and when any bugs occur can become
a mystery. This can take much of a programmer valuable time as he/she searches through lines
and lines of code to find out where an error occurred, and problems it causes later in the
program. Errors can easily be identified, as they are localized to a subroutine or function.
• Reusable Code: Modular code allows programmers to easily reuse code. A single procedure
can be developed for reuse, eliminating the need to retype the code many times.
• Readability: Modular code is code that is highly organized. To organize code based on task
means that the programmer can organize each piece of code based on what it does.
• Reliability: Reusability, ease of debugging and readability enhances reliability. A code that is
easier to read, easier to debug, easier to maintain and easier to share will always run smoother
with less errors
• Programs can be designed more easily because a small team deals with only a small part of the
entire code.
• Modular programming allows many programmers to collaborate on the same application.
• Code is short, simple and easy to understand.

Non-Procedural Languages
Expresses what needs to be done, without prescribing how to do it in terms of sequences of
actions to be taken.

Page 20 of 66
Advantages of Non Procedural Languages
• They improve productivity compared to third generation language.
• They are result oriented; they emphasize what instead of how.
• They can be used with minimum of training by both programmers and non programmers.
• They defend users from needing an awareness of hardware and program structure.
• Programs are easy to write and modify.

Disadvantages of Non Procedural Languages


• They are still evolving and are not standardized. One of the main criticisms is that the new
languages are lack of necessary control and flexibility.
• They do not make efficient use of machine resources.

Object Oriented Programming (OOP) Languages


Historically, a program has been viewed as a logical procedure that takes input data, processes it,
and produces output data. Programming challenge was seen as how to write the logic, not how to
define the data.

Object-oriented programming takes the view that what we really care about are the objects we
want to manipulate rather than the logic required to manipulate them. Thus Object-oriented
programming (OOP) is model organized around "objects" rather than "actions" and “data” rather
than logic.

OOP is a of programming language in which programmers define not only the data type of
a data structure, but also the types of operations (functions) that can be applied to the data
structure. In this way, the data structure becomes an object that includes both data and functions.
In addition, programmers can create relationships between one object and another. For example,
objects can inherit characteristics from other objects.

The first step in OOP is to identify all the objects you want to manipulate and how they relate to
each other. Once you've identified an object, you generalize it as a class of objects (think of Plato's
concept of the "ideal" chair that stands for all chairs) and define the kind of data it contains and
any logic sequences that can manipulate it. Each distinct logic sequence is known as a method. A
real instance of a class is called an "object" or an "instance of a class." The object or class instance
is what you run in the computer. Its methods provide computer instructions and the class object
characteristics provide relevant data.

Important Concepts of OOP


Object Oriented Programming involves some important concepts:

Objects
Objects are the basic run-time entities in an object-oriented system. Programming problem is
analyzed in terms of objects and nature of communication between them. When a program is
executed, objects interact with each other by sending messages. Different objects can also interact
with each other without knowing the details of their data or code.

Page 21 of 66
Classes
A class is a collection of objects of similar type. Once a class is defined, any number of objects
can be created which belong to that class.

Data Abstraction
Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes.

Data Encapsulation
Storing data and functions in a single unit (class) is encapsulation. Data cannot be accessible to
the outside world and only those functions which are stored in the class can access it.

Inheritance
Inheritance is the process by which objects can acquire the properties of objects of other classes.
In OOP, inheritance provides reusability like adding additional features to an existing class without
modifying it. This is achieved by deriving a new class from the existing one. The new class will
have combined features of both the classes.

Polymorphism
Polymorphism means the ability to take more than one form. An operation may exhibit different
behaviors in different instances. The behavior depends on the data types used in the operation.
Polymorphism is extensively used in implementing Inheritance.

Advantages of OOP
(i) Reusability of Code: In the object-oriented approach, you build classes, which can be used
by several applications. The reuse of the components once created not only reduces the
effort of recreating the components, but also reduces the chances of introduction of errors
in various modules. After integrating all the modules) a consolidated system can be created
that has various components reused across the modules. The benefit of reusability translates
to savings in time and effort, which in turn results in cost effectiveness.
(ii) Modularity of Code: OOP provides a clear modular structure for programs. It means that
an object can be maintained independently of other objects. All these objects are
independent of each other and are maintained separately. You can make modifications in
the required object without affecting the functionality of other objects.
(iii) Flexibility to Change: Object-oriented programming also enables you to evolve various
versions of software. When a change is suggested, the old system need not be completely
abandoned and re-built from scratch. Flexibility to change enables easier maintenance of
the program. For the same reason, even during construction, parts of the system under
development can be refined without any major change in other parts.
(iv) Information Hiding: Objects provide the benefit of information hiding. Implementation
details are hidden from other modules. Only a limited access to information is provided to
the user. Information hiding ensures data security in a program. An end-user is given an
access to the essential details only hiding the complex and no-essential details that user
might not be aware of. Information hiding is necessary to keep the user away from the
complex part of the application or a program. This way the application appears to be simple

Page 22 of 66
and also security is maintained. Information hiding is done using abstraction and
encapsulation.
(v) Improved software maintainability: Object oriented programming
make code maintainable. This simply means that identifying errors becomes easier since the
objects are vivid (encapsulation). It is also easy to maintain and modify existing codes as
new objects can be created without modifying the existing ones.
(vi) Higher-quality software: Faster development of software and lower cost of development
allows more time and resources to be used in the verification of the software. Although
quality is dependent upon the experience of the teams, object-oriented programming tends
to result in higher-quality software.
(vii) Lower cost of development: The reuse of software also lowers the cost of development.
Typically, more effort is put into the object-oriented analysis and design, which lowers the
overall cost of development.
(viii) Faster development: Reuse enables faster development. Object-oriented programming
languages come with rich libraries of objects, and code developed during projects is also
reusable in future projects.
(ix) Scalable: OOP applications are more scalable than their earlier structured programming. A
well-defined interface provides an opportunity to reuse the code in new software. Also, it
provides the programmer will the information he/she requires to replace the object’s
interface without affecting the codes. By doing so, it becomes easy to replace aging code
with newer technology and faster algorithms.
(x) Understandability: Object-Oriented languages mimic the real world and
therefore make them easier to grasp
(xi) Definition of abstract data types: OOP is good for defining abstract data types. The
concept of data classes allows a programmer to create any new data type that is not already
defined in the language itself.
(xii) Sharing code: You may want to use a custom code in a new software project. With OOP a
programmer can inherit and use the old code into a new project.

Disadvantages of OOP
1. Steep learning curve: The thought process involved in object-oriented programming may not
be natural for some people, and it can take time to get used to it. It is complex to create
programs based on interaction of objects. Some of the key programming techniques, such as
inheritance and polymorphism, can be challenging to comprehend initially.
2. Larger program size: Object-oriented programs typically involve more lines of code than
procedural programs.
3. Slower programs: Object-oriented programs are typically slower than procedure based
programs, as they typically require more instructions to be executed.
4. Not suitable for all types of problems: There are problems that lend themselves well to
functional-programming style, logic-programming style, or procedure-based programming
style, and applying object-oriented programming in those situations will not result in efficient
programs.

Examples of OOP include:


− Smalltalk (1974-1980): Smalltalk was the first purely object-oriented programming (OOP)
language.

Page 23 of 66
− HyperTalk(1987): Hypertalk is Apple's object oriented programming language.
− Java (1991- today): Java is a purely OOP, procedural, high level language designed to facilitate
reliable, platform-independent, distributed processing.
− C++ an extension of the C language that provides OOP facilities
− Simula, Curl, Delphi, Eiffel, Ruby, Perl, Objective C, Python and Visual Basic.Net

Event-driven Languages
The flow of the program is determined by events i.e., sensor outputs or user actions (mouse clicks,
key presses) or messages from other programs. The language natively supports detection of the
events and does not rely on the programmer to create code to do so.

Review Questions
1. Define the following terms
(a) Computer program
(b) Programming
(c) Programming language
2. Distinguish between high level and low level languages
3. Distinguish between machine language and assembly language
4. Distinguish between high level language and assembly language
5. State TWO advantages and three disadvantages of low level languages
6. State three advantages and two disadvantages of high level languages
7. Explain two advantages of 3GLs over 2GLs
8. Distinguish between fourth generation languages and fifth generation languages.
9. State THREE characteristics of first generation languages.
10. (a) State any THREE advantages of object oriented programming languages (OOP)
(b) Name THREE examples of object oriented programming languages
11. Distinguish between procedural and non-procedural programming languages
12. State any THREE advantages of modular programming
13. What are the main characteristics of the following Internet programming languages?
(a) HTML
(b) XML
(c) VRML
(d) JavaScript
14. Object-oriented programming involves four important concepts as listed below. Describe
each of these concepts:
(a) Data abstraction
(b) Encapsulation
(c) Inheritance
(d) Polymorphism
15. Distinguish between object code and source code.
16. State any FOUR functions of language translators
17. Distinguish between the following pairs of terms;
(a) Assemblers and Compilers
(b) Compilers and Interpreters
18. State any four factors to consider when choosing a programming language.

Page 24 of 66
Page 25 of 66
Topic 2: Problem Solving and Algorithm Design

Many programmers use a design approach called structured programming. Structured


programming allows a top-down design approach where a program is broken down into modules
or sub-programs.

In structured programming, the program is designed in three steps:


1. First the program is logic is determined through a top-down approach on the basis of program
modules and a hierarchy chart
2. Secondly the program logic is designed in detailed form either in narrative form using
pseudocodes or graphically using flowcharts.
3. Lastly the design is tested with a structured walkthrough.

Determining the program logic using a top-down approach


Top-down design proceeds by identifying the function of the program and the breaking it down in
a hierarchical manner to specify processing steps or modules required to perform that function
down to the lowest level of detail.

Modularization simplifies program design by allowing individual programs modules to be


developed and tested separately. A module (sub-program) is a self-contained processing step
consisting of logically related program statements.

Rules of Module design


1. Each module must be of manageable size
2. Each module should be independent and have a single function.
3. The functions of input and outputs must be clearly defined in separate modules.
4. Each module has a single-entry point and a single exit point. Thus, execution of the program
module should always start at the same place and the control should always leave the module
at the same place.
5. If one module refers to or transfers control to another module, the latter module should return
control to the point to which it was called by the first module.

In a top-down design a program can be represented graphically in a hierarchical chart which


illustrates the overall purpose of the program and identifies all the modules needed to achieve that
purpose and the relationship among them. The figure below represents a top-down design for an
examination processing program. The program must move upward through the chart in sequence,
from one module to the next until all have been processed. The three principal modules
corresponding to three principal computing operations (input, processing and output) must be
there.

Page 26 of 66
Once the essential logic of the program has been determined through the use of top-down
programming and hierarchy charts, you can now work on the details. There are many programming
tools that can be used to show program details e.g., pseudocodes and flowcharts.

Pseudocodes
Pseudocode is an algorithm that models or resembles the real programming language of the
computer. It is a tool for designing a program in a narrative form using human language statements
to describe the logic and processing flow.

Pseudocode is an informal high-level description of the operating principle of a computer program


or other algorithm. It uses the structural conventions of a programming language, but is intended
for human reading rather than machine reading

Pseudocode is an informal way of describing a program that does not require strict syntax, but
instead serves as a general representation of a program's functions.

Examples of an algorithm and pseudocode to process examination results are shown below. More
examples will be covered in the development of pseudocodes and flowcharts section.

Page 27 of 66
Guidelines in designing a good pseudocode
1. The statements must be short, clear and readable
2. The statements should be unambiguous i.e. the statements must not have more than one
meaning
3. The statements should be clearly outlined
4. The construct statements should be clearly indented to shown the entry and exit points
5. The control structures should be clearly shown.
6. The start and stop of executable statements be clearly shown
7. The input, output and processing statements should be clearly stated using appropriate key
words.

Advantages of pseudocodes
1. Pseudocodes can be easily typed in any word processor.
2. Pseudocodes can be easily modified as compared to flowchart.
3. Pseudocodes implementation is very useful in structured design elements.
4. Pseudocodes can be written easily.
5. Pseudocodes can be read and understood easily.
6. Converting a pseudocode to programming language is easier as compared to converting a
flowchart to programming language.

Disadvantages of pseudocodes
1. One does not get a picture of the design as pseudocodes are not visual.
2. There is no standardised style or format, so one pseudocode may be different from another.
3. It is more difficult to follow the program logic as compared to flowchart.

Program Flowchart
A program flowchart is a diagrammatic representation of program’s processing logic. A
flowchart can also be defined as a diagrammatic representation that illustrates the sequence of
operations to be performed to get the solution of a problem. A flowchart shows how your program
works before you begin actually coding it.

Page 28 of 66
Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts
facilitate communication between programmers and users. These flowcharts play a vital role in the
programming of a problem and are quite helpful in understanding the logic of complicated and
lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high
level language. Often we see how flowcharts are helpful in explaining the program to others.

Flowcharts are usually drawn using some standard symbols called ANSI symbols (called after the
American National Standards Institute that developed them) and short statements that describe
various activities. The table below shows ANSI standard symbols for program flowcharts.

Guidelines in Flowcharting
(a). In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
(b). The flowchart should be clear, neat and easy to follow. There should be no room for
ambiguity in understanding the flowchart.

Page 29 of 66
(c). The usual direction of the flow of a procedure or system is from left to right or top to bottom.
(d). Only one flow line should come out from a process symbol.

(e). Only one flow line should enter a decision symbol, but two or three flow lines, one for each
possible answer, should leave the decision symbol.

(f). Only one flow line is used in conjunction with terminal symbol.

(g). Write within standard symbols briefly. As necessary, you can use the annotation symbol to
describe data or computational steps more clearly.

(h). If the flowchart becomes complex, it is better to use connector symbols to reduce the number
of flow lines.
(i). Avoid the intersection of flow lines if you want to make it more effective and better way of
communication.
(j). Ensure that the flowchart has a logical start and stop.
(k). It is useful to test the validity of the flowchart by passing through it with a simple test data.

Advantages of Flowcharts
(i) Flowcharts are better way of communicating the logic of a program to all concerned.
(ii) With the help of a flowchart, a problem can be analyzed in more effective way.
(iii) Program flowcharts serve as a good program documentation, which is needed for various
purposes.
(iv) The flowcharts act as a guides or blueprints during the analysis and program coding phase.
(v) The flowchart helps in debugging process.
(vi) The maintenance of an operating program becomes easy with the help of flowchart. It helps
the programmer to put efforts more efficiently on that part

Disadvantages of Flowcharts

Page 30 of 66
(i) When the program logic is complicated, a flowchart becomes complex and clumsy.
(ii) If alterations are required, the flowchart may require re-drawing completely.
(iii) As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
(iv) The essentials of what is done can easily be lost in the technical details of how it is done if
a program is complex

Control Structures
When designing a program, one needs to reason through the problem to determine the correct
logic. The logic of a program can be established through the use of control structures. Control
structures or logic structures/constructs control the logic sequence in which computer program
instructions are executed. Three basic control structures are used to form the logic of a program:
sequence, selection (case) and iteration (loop).

Any control structure must have only one entry and one exit, thus the control structure is entered
at a single point and exited at another single point.

Sequence Control Structure


In sequence control structure, one program statement follows another in logical order. There are
no decisions to make, no choices between “yes” or “no”.

Selection Control Structure


Selection control structure, also known as IF..THEN..ELSE structure allows a logical expression
to select one of two alternative blocks of code to execute.

Note: The statement after ENDIF will be executed irrespective of whether the test condition
evaluates to true or false.

Page 31 of 66
Below is a sample flowchart, can you determine what it does?

Case Control Structure


The case control structure is a variation of the selection structure that involves more than a single
yes-or-no decision. The case structure allows several alternatives or cases to be presented. The
case control structure saves the programmer the trouble of having to indicate a lot of separate
IF..THEN..ELSE conditions.

Page 32 of 66
As you can notice, the case structure is simpler to write than multiple selection involving the
IF…THEN…ELSE structure

Page 33 of 66
Iteration (Loop/Repetition) Control Structure
This is a control structure in which a process maybe repeated as long as a certain condition remains
true. There are two types of loop: finite loop ad infinite loop

A finite loop is where the number of times a repetition is to be made is known in advance. Finite
loops can be implemented using the FOR structure. In this construct the loop is controlled by a
counter which increases each time the set of instructions is executed. This construct is used when
the number of times a set of instructions has to be repeated is known.

The statements (loop statements) between FOR and ENDFOR are repeatedly executed four times.
When these statements are executed, the counter variable is initially set to the beginning value, in
this case, 1. After the execution of the instructions between the FOR and the ENDFOR, the counter
variable is increased by 1. The instructions are repeated and the counter variable increases until it
becomes equal to the ending value, in this case, 4. So the instructions are repeated four times.

Note: The variable in the FOR construct is a counter variable which keeps track of the number
of times the loop is executed.

An indefinite (infinite) loop is where the instructions are repeated an unspecified number of times.
A sentinel or terminal value is required to cause the program to exit the loop. A sentinel value is
a lookout value such that if the data being entered ever becomes equal to the sentinel value, the
computer exits the loop. The sentinel value must not be one of the values in the list of data to be
processed. Either the user can input this value, or the computer can be programmed so that a certain
condition can be met, triggering the end of the loop.

Page 34 of 66
Indefinite loops can be implemented using two structures: REPEAT.. UNTIL and WHILE.. DO
structures.

Page 35 of 66
Page 36 of 66
Topic 3: Introduction to C Programming
Introduction
C is a general-purpose, high-level language that 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 application programs have
been written in C. C has now become a widely used professional language for various reasons.
(a) Easy to learn
(b) Structured language
(c) It produces efficient programs
(d) It can handle low-level activities
(e) 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 the early 1970s.
• The language was formalized in 1988 by the American National Standard Institute (ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
• Most of the state-of-the-art software have been implemented using C.
• Today's most popular Linux OS and RDBMS MySQL have been written in C.

Why use C?
C was initially used for system development work, particularly 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 the code written in assembly language. Some examples of the use of C
might be −
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities

Page 37 of 66
Environment Setup
#include <stdio.h>
int main() {

/* my first program in C */
printf("Hello, World! \n");
return 0;
}

Local Environment Setup


If you want to set up your environment for C programming language, you need the following two
software tools available on your computer; (a) Text Editor and (b) The C Compiler.

Text Editor
This will be used to type your program. Examples of few editors include Windows Notepad.

The files you create with your editor are called the source files and they contain the program
source codes. The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have
enough experience to write a computer program, save it in a file, compile it and finally execute
it.

The C Compiler
The source code written in source file is the human readable source for your program. It needs to
be "compiled", into machine language so that your CPU can actually execute the program as per
the instructions given.

The compiler compiles the source codes into final executable programs. The most frequently used
and free available compiler is the GNU C/C++ compiler, otherwise you can have compilers either
from HP or Solaris if you have the respective operating systems.

The following section explains how to install GNU C/C++ compiler on various OS. We keep
mentioning C/C++ together because GNU gcc compiler works for both C and C++ programming
languages.

C Program Structure
A C program basically consists of the following parts
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments

Page 38 of 66
Example
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");

return 0;
}

Let us take a look at the various parts of the above program


• The first line of the program #include <stdio.h> is a preprocessor command, which tells a C
compiler to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.

Basic Syntax
You have seen the basic structure of a C program, so it will be easy to understand other basic
building blocks of the C programming language.

Tokens in C
A C program consists of various tokens. A token is either a keyword, an identifier, a constant, a
string literal, or a symbol. For example, the following C statement consists of five tokens.

printf("Hello, World! \n");

The individual tokens are


printf
(
"Hello, World! \n"
)
;

Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity.

Given below are two different statements.

Page 39 of 66
printf("Hello, World! \n");
return 0;

Comments
Comments are like helping text in your C program and they are ignored by the compiler. They
start with /* and terminate with the characters */ as shown below

/* my first program in C */

You cannot have comments within comments and they do not occur within a string or character
literals.

Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An
identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters,
underscores, and digits (0 to 9).

C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language. Thus, Manpower and manpowerare two different identifiers in
C. Here are some examples of acceptable identifiers.

name age abc move_name a_123 myname50 _temp j a23b9 retVal

Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
Auto Else long Switch
break Enum register Typedef
Case Extern return Union
Char Float short Unsigned

const For signed Void


continue Goto sizeof Volatile
default If static While
Do Int struct _Packed
double

Page 40 of 66
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C
compiler totally ignores it.

Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify
where one element in a statement, such as int, ends and the next element begins.

Therefore, in the following statement;


int age;
• There must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the following statement

fruit = apples + oranges; // get the total fruit


• No whitespace characters are necessary between fruit and =, or between = and apples, although
you are free to include some if you wish to increase readability.

Page 41 of 66
Topic 4: Constants, Variables, Data types, and Expressions

Data Types
Data types in C refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.

The types in C can be classified as follows;


S.N. Types & Description
1 Basic Types
They are arithmetic types and are further classified into: (a)
integer types and (b) floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define
variables that can only assign certain discrete integer values
throughout the program.

3 The type void


The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure
types, (d) Union types and (e) Function types.

Integer Types
The following table provides the details of standard integer types with their storage sizes and value
ranges.

Type Storage size Value range


Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to


2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647

Page 42 of 66
unsigned long 4 bytes 0 to 4,294,967,295

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in
bytes. Given below is an example to get the size of int type on any machine.

#include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}

Floating-Point Types
Type Storage size Value range Precision

Float 4 byte 1.2E-38 to 3.4E+38 6 decimal places


double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

The header file float.h defines macros that allow you to use these values and other details about
the binary representation of real numbers in your programs. The following example prints the
storage space taken by a float type and its range values.

The void Type


The void type specifies that no value is available. It is used in three kinds of situations −
S.N. Types & Description
1 Function returns as void
There are various functions in C which do not return any value
or you can say they return void. A function with no return value
has the return type as void. For example, void exit (int status);
2 Function arguments as void
There are various functions in C which do not accept any
parameter. A function with no parameter can accept a void. For
example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object, but
not its type. For example, a memory allocation function void
*malloc( size_t size ); returns a pointer to void which can be
casted to any data type.

Page 43 of 66
Variables in C
A variable is a name given to a storage area that our programs can manipulate. Each variable in
C has a specific type, which determines the size and layout of the variable's memory; the range
of values that can be stored within that memory; and the set of operations that can be applied to
the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive.

Type Description
char Typically, a single octet (one byte). This is an integer type.

int The most natural size of integer for the machine.


float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.

C programming language also allows programmers to define various other types of variables,
which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union,
etc.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type
as follows.

type variable_list;

Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object. Variable_list may consist of one or more identifier names separated by
commas.

int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.

Page 44 of 66
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists
of an equal sign followed by a constant expression.

type variable_name = value;

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without requiring
the complete detail about the variable. A variable definition has its meaning at the time of
compilation only; the compiler needs actual variable definition at the time of linking the program.

A variable declaration is useful when you are using multiple files and you define your variable in
one of the files which will be available at the time of linking of the program. You will use the
keyword extern to declare a variable at any place. Though you can declare a variable multiple
times in your C program, it can be defined only once in a file, a function, or a block of code.

Example
Variables in the following example have been declared at the top, but they have been defined and
initialized inside the main function.

#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}

Page 45 of 66
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f : 23.333334

The same concept applies on function declaration where you provide a function name at the time
of its declaration and its actual definition can be given anywhere else.
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}

Expressions
Lvalues and Rvalues in C
There are two kinds of expressions in C
• lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue
may appear as either the left-hand or right-hand side of an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address in memory. An
rvalue is an expression that cannot have a value assigned to it which means an rvalue may
appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so they may not be assigned and cannot appear on the left-hand side.
int g = 20; // valid statement

10 = 20; // invalid statement; would generate compile-time error

Constants & Literals


Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, a string literal or enumeration.

Constants are treated just like regular variables except that their values cannot be modified after
their definition.

Page 46 of 66
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or
radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.

212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */

Following are other examples of various types of integer literals −


85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
You can represent floating point literals either in decimal form or exponential form.

While representing decimal form, you must include the decimal point, the exponent, or both; and
while representing exponential form, you must include the integer part, the fractional part, or
both. The signed exponent is introduced by e or E.

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */

Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable
of char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').

Page 47 of 66
There are certain characters in C that represent special meaning when preceded by a backslash
for example, newline (\n) or tab (\t).

Escape sequence characters


#include <stdio.h>
int main() {
printf("Hello\tWorld\n\n");
return 0;
}

When the above code is compiled and executed, it produces the following result:
Hello World

String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines using string literals and separating them using white
spaces.

Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant.

#define identifier value

The following example explains it in detail.


#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

Page 48 of 66
int main() {
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}

When the above code is compiled and executed, it produces the following result
value of area : 50

The const Keyword


You can use const prefix to declare constants with a specific type as follows

const type variable = value;

The following example explains it in detail −


#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}

When the above code is compiled and executed, it produces the following result −
value of area : 50

Note that it is a good programming practice to define constants in CAPITALS.

Page 49 of 66
Topic 5: Input/Output Statements

Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.

C programming language provides many built-in functions to read any given input and to display
data on screen when there is a need to output the result. In this topic, we will learn about such
functions, which can be used in our program to take input from user and to output the result on
screen.

All these built-in functions are present in C header files, we will also specify the name of header
files in which a particular function is defined while discussing about it.

scanf() and printf() functions


The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to take input from
user respectively.

include<stdio.h>
int main()
{
// defining a variable
int i;
// displaying message on the screen asking the user to input a value
printf("Please enter a value...");
// reading the value entered by the user
scanf("%d", &i);
//displaying the number as output
printf( "\nYou entered: %d", i);
return 0;
};
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered on screen.

You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is
known as format string and this informs the scanf() function, what type of input to expect and
in printf() it is used to give a heads up to the compiler, what type of output to expect.

Format String Meaning


%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning ends at whitespace.

Page 50 of 66
We can also limit the number of digits or characters that can be input or output, by adding a
number with the format string specifier, like "%1d" or "%3s", the first one means a single
numeric digit and the second one means 3 characters, hence if you try to input 42,
while scanf() has "%1d", it will take only 4 as input. Same is the case for output.

In C Language, computer monitor, printer etc. output devices are treated as files and the same
process is followed to write output to these devices as would have been followed to write the
output to a file.

NOTE: printf() function returns the number of characters printed by it, and scanf() returns the
number of characters read by it.

int i = printf("Kibabii");

In this program printf("Kibabii"); will return 6 as result, which will be stored in the variable i,
because kibabii has 6 characters.

getchar() & putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in a loop in case you
want to read more than one character.

The putchar() function displays the character passed to it on the screen and returns the same
character. This function too displays only a single character at a time. In case you want to display
more than one characters, use putchar() method in a loop.

#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
display the character stored
in variable c
*/
putchar(c);
}

When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.

Page 51 of 66
gets() & puts() functions
The gets() function reads a line from stdin(standard input) into the buffer pointed to
by str pointer, until either a terminating newline or EOF (end of file) occurs.

The puts() function writes the string str and a trailing newline to stdout.

str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not
able to understand this now.)

#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
When you will compile the above code, it will ask you to enter a string. When you will enter the
string, it will display the value you have entered.

Difference between scanf() and gets()


The main difference between these two functions is that scanf() stops reading characters when
it encounters a space, but gets() reads space as character too.

If you enter name as Study Tonight using scanf() it will only read and store Study and will
leave the part after space. But gets() function will read it completely.

Page 52 of 66
Topic 6: Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then.

Operator Description Example


+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200


/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an B % A = 0
integer division.
++ Increment operator increases the integer A++ = 11
value by one.
-- Decrement operator decreases the integer A-- = 9
value by one.

Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then.

Operator Description Example


== Checks if the values of two operands are (A == B) is not true.
equal or not. If yes, then the condition
becomes true.
!= Checks if the values of two operands are (A!= B) is true.
equal or not. If the values are not equal,
then the condition becomes true.

Page 53 of 66
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand. If
yes, then the condition becomes true.
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand. If yes, then
the condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of right
operand. If yes, then the condition becomes
true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right operand.
If yes, then the condition becomes true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then.

Operator Description Example


&& Called Logical AND operator. If both the operands are (A && B)
non-zero, then the condition becomes true. is false.
|| Called Logical OR Operator. If any of the two operands (A || B) is
is non-zero, then the condition becomes true. true.

! Called Logical NOT Operator. It is used to reverse the !(A && B)


logical state of its operand. If a condition is true, then is true.
Logical NOT operator will make it false.

Assignment Operators
Operator Description Example
= Simple assignment operator. Assigns values from C = A + B
right side operands to left side operand will assign
the value
of A + B to
C
+= Add AND assignment operator. It adds the right C += A is
operand to the left operand and assign the result to equivalent
the left operand. to C = C +
A

Page 54 of 66
-= Subtract AND assignment operator. It subtracts the C -= A is
right operand from the left operand and assigns the equivalent
result to the left operand. to C = C –
A
*= Multiply AND assignment operator. It multiplies C *= A is
the right operand with the left operand and assigns equivalent
the result to the left operand. to C = C *
A
/= Divide AND assignment operator. It divides the C /= A is
left operand with the right operand and assigns the equivalent
result to the left operand. to C = C /
A
%= Modulus AND assignment operator. It takes C %= A is
modulus using two operands and assigns the result equivalent
to the left operand. to C = C %
A
<<= Left shift AND assignment operator. C <<= 2 is
same as C
= C << 2
>>= Right shift AND assignment operator. C >>= 2 is
same as C
= C >> 2
&= Bitwise AND assignment operator. C &= 2 is
same as C
=C&2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is
same as C
=C^2
|= Bitwise inclusive OR and assignment operator. C |= 2 is
same as C
=C|2

Misc Operators ↦ sizeof & ternary


Besides the operators discussed above, there are a few other important operators
including sizeof and ? :

Operator Description Example

Page 55 of 66
sizeof() Returns the size of a variable. sizeof(a), where a is
integer, will return 4.
& Returns the address of a variable. &a; returns the actual
address of the variable.
* Pointer to a variable. *a;

?: Conditional Expression. If Condition is true ?


then value X : otherwise
value Y

Page 56 of 66
Topic 7: Selection Control Structures in C
Decision making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.

Show below is the general form of a typical decision-making structure found in most of the
programming languages.

C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.

C programming language provides the following types of selection statements.


S.N. Statement & Description
1 if statement
An if statement consists of a Boolean expression followed by one or more statements.

2 if...else statement
An if statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).

4 switch statement
A switch statement allows a variable to be tested for equality against a list of values.

5 nested switch statements


You can use one switch statement inside another switch statement(s).

if statement
An if statement consists of a Boolean expression followed by one or more statements.

Page 57 of 66
Syntax

if(boolean_expression) {
/* statement(s) will execute if the Boolean expression is true */
}

If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will
be executed. If the Boolean expression evaluates to false, then the first set of code after the end
of the 'if' statement (after the closing curly brace) will be executed.

C programming language assumes any non-zero and non-null values as true and if it is
either zero or null, then it is assumed as false value.

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);

return 0;
}

Page 58 of 66
if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.

Syntax
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
else {
/* statement(s) will execute if the boolean expression is false */
}

If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else
block will be executed.

C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.

Flow Diagram

Example
#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;

/* check the boolean condition */


if( a < 20 ) {
/* if condition is true then print the following */
Page 59 of 66
printf("a is less than 20\n" );
}
else {
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}

printf("value of a is : %d\n", a);


return 0;
}

If...else if...else Statement


An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.

When using if...else if..else statements, there are few points to keep in mind
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax
The syntax of an if...else if...else statement in C programming language is −
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
}
else {
/* executes when the none of the above condition is true */
}

Example
#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;

Page 60 of 66
/* check the boolean condition */
if( a == 10 ) {
/* if condition is true then print the following */
printf("Value of a is 10\n" );
}
else if( a == 20 ) {
/* if else if condition is true */
printf("Value of a is 20\n" );
}
else if( a == 30 ) {
/* if else if condition is true */
printf("Value of a is 30\n" );
}
else {
/* if none of the conditions is true */
printf("None of the values is matching\n" );
}
printf("Exact value of a is: %d\n", a );

return 0;
}

nested if statements
It is always legal in C programming to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).

Syntax
if( boolean_expression 1) {

/* Executes when the boolean expression 1 is true */


if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
}

You can nest else if...else in the similar way as you have nested if statements.

Example
#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;

Page 61 of 66
int b = 200;

/* check the boolean condition */


if( a == 100 ) {

/* if condition is true then check the following */


if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}

printf("Exact value of a is : %d\n", a );


printf("Exact value of b is : %d\n", b );

return 0;
}

switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case.

Syntax
switch(expression) {

case constant-expression :
statement(s);
break; /* optional */

case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement


• The expression used in a switch statement must have an integral or enumerated type, or be of
a class type in which the class has a single conversion function to an integral or enumerated
type.
• You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.

Page 62 of 66
• The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.

Flow Diagram

Example
#include <stdio.h>

int main () {
/* local variable definition */
char grade = 'B';
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :

Page 63 of 66
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}

printf("Your grade is %c\n", grade );


return 0;
}

nested switch statements


It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the
case constants of the inner and outer switch contain common values, no conflicts will arise.
Syntax
switch(ch1) {

case 'A':
printf("This A is part of outer switch" );

switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}

Example
#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;
int b = 200;

switch(a) {

case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:

Page 64 of 66
printf("This is part of inner switch\n", a );
}
}

printf("Exact value of a is : %d\n", a );


printf("Exact value of b is : %d\n", b );

return 0;
}

The ? : Operator
The conditional operator ?: can be used to replace if...else statements.

Syntax
Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a ? expression is determined like this;


• Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire
? expression.
• If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

Practical Exercises
1. Positive or Negative: Write a C program that takes an integer as input and uses an if statement
to determine whether it's positive, negative, or zero.
2. Even or Odd: Develop a program that reads an integer as input and uses an if statement to
print whether it's even or odd.
3. Maximum of Two Numbers: Create a program that takes two numbers as input and uses an
if statement to determine and print the maximum of the two.
4. Minimum of Three Numbers: Write a C program that takes three numbers as input and uses
an if statement to determine and print the minimum of the three.
5. Leap Year Checker: Develop a program that takes a year as input and uses an if statement to
check if it's a leap year or not.
6. Month Days Calculator: Write a C program that takes a month number as input and uses a
switch statement to print the number of days in that month. Account for leap years in February.
7. Calculator with Menu: Create a calculator program with a menu that allows the user to
choose an operation (addition, subtraction, multiplication, or division). Use a switch statement
to perform the selected operation on two numbers entered by the user.
8. Calculator with Error Handling: Extend the calculator program from exercise 7 to handle
division by zero gracefully. Display an error message if the user attempts to divide by zero.

Page 65 of 66
9. Traffic Light Simulation: Write a program that simulates a traffic light. Use a switch
statement to display the appropriate message based on the user's input for the color (red, green,
or yellow).
10. Discount Calculator: Develop a program that calculates the total cost of items after applying
a discount. Take the number of items and their prices as input and use if statements to apply
the discount as follows:
• 10% discount for 10 or more items
• 5% discount for 5-9 items
• No discount for less than 5 items
11. Quadratic Equation Solver: Create a C program that solves a quadratic equation of the form
ax^2 + bx + c = 0. Take the coefficients a, b, and c as input, and use if statements to calculate
and display the roots of the equation.
12. Age Group Classifier: Write a program that reads a person's age as input and uses if
statements to classify them into age groups such as child, teenager, adult, or senior citizen.
13. Grade Point Average (GPA) Calculator: Develop a C program that calculates the GPA of
a student based on their grades in multiple subjects. Take the subject names and corresponding
grades as input and calculate the GPA.
14. Character to ASCII Value: Write a program that takes a character as input and uses printf to
display its ASCII value.
15. Check for Uppercase or Lowercase: Create a program that reads a character as input and
uses if statements to determine whether it's an uppercase or lowercase letter.
16. Simple Interest Calculator: Develop a program that calculates the simple interest based on
user input for principal amount, rate of interest, and time period. Display the interest.
17. Positive, Negative, or Zero: Write a C program that takes a real number as input and uses if
statements to determine whether it's positive, negative, or zero.
18. Month Name: Create a program that reads a month number (1 to 12) as input and uses a
switch statement to print the corresponding month name.
19. Triangle Type Classifier: Develop a program that takes the lengths of three sides of a triangle
as input and uses if statements to classify the triangle as equilateral, isosceles, or scalene.
20. Menu-Driven Grade Calculator: Write a C program that calculates the grade for a student
based on their score using a menu-driven approach. The program should allow the user to
enter scores for multiple students and display grades for each.

Page 66 of 66

You might also like