Bit 113fundamentals of Programming Part One
Bit 113fundamentals of Programming Part One
Room: ABB206
Pre-requisite: None
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.
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 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.
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).
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
The machine code program below will convert an upper case letter stored in a particular memory
location to lower case:
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.
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 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.
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.
Easy to write, read and modify Difficult to write, read and modify
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).
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.
Page 14 of 66
Compilers Interpreters
There are currently five generations of computer programming languages. In each generation, the
languages syntax has become easier to understand and more human-readable.
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.
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.
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.
Examples of 5GLs are OPS5 (Official Production System), Prolog (Logical Programming) and
Mercury.
Page 17 of 66
yes. (The program returns yes)
?-girl(Omondi). (Question asked “Is Omondi a girl?”)
no. (The program returns no.)
Page 18 of 66
a user can interact by viewing, moving, rotating, and otherwise interacting with an apparently
3-D scene.
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.
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.
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.
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.
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.
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.
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
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 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.
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?
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;
}
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;
}
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.
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.
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.
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
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.
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.
Integer Types
The following table provides the details of standard integer types with their storage sizes and value
ranges.
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
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.
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.
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.
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
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 */
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).
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.
#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
When the above code is compiled and executed, it produces the following result −
value of area : 50
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.
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.
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.
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.
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.
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then.
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.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then.
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
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;
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.
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.
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 () {
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
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 () {
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 () {
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) {
You can nest else if...else in the similar way as you have nested if statements.
Example
#include <stdio.h>
int main () {
Page 61 of 66
int b = 200;
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 */
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" );
}
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
#include <stdio.h>
int main () {
switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:
Page 64 of 66
printf("This is part of inner switch\n", a );
}
}
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.
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