0% found this document useful (0 votes)
6 views49 pages

Introduction to Computer Science Concepts

computer science file

Uploaded by

abiyzena99
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views49 pages

Introduction to Computer Science Concepts

computer science file

Uploaded by

abiyzena99
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to

computing Science
Module

Haileyesus Tilahun
ST. MARY’S UNIVERSITY
[Link]’s University
Faculty of Informatics
Department of Computer Science

Chapter 1: An overview of computer science


 Computer science is the study of the theory, experimentation, and engineering that form
the basis for the design and use of computers.
 Computer science is the study of the theoretical foundations of information and
computation, and of practical techniques for their implementation and application in
computer systems.

It is the scientific and practical approach to computation and its applications and the
systematic study of the feasibility, structure, expression, and mechanization of the
methodical procedures (or algorithms) that underlie the acquisition, representation,
processing, storage, communication of, and access to information.

Its fields can be divided into a variety of theoretical and practical disciplines.

• Computer graphics: emphasize real-world visual applications


• Programming language theory: considers various approaches to the description of
computation, while the study of computer programming itself investigates various
aspects of the use of programming language and complex systems.
• Human–computer interaction: considers the challenges in making computers and
computations useful, usable, and universally accessible to humans.

Computer
Science

Engineering Communication Others

Computer Basic Artificial


Enginering Networking Intelligence

Software Distributed
NLP
Engineering Systems

Hardware Mobile GIS and Remot


Engineering Networking Sensing

Pervasive

Page 1 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
What is a computer?
In the simplest definition, computer is an electronic device that takes input such as raw data
which can be numbers, text, sound, image, animations, video, etc., processes it, and
converts it into meaningful information that could be understood, presenting the changed
input (processed input) as output.

What is Data?

o Data is raw, unorganized facts that need to be processed.


o It is a collection of symbols that represent a thing, a concept or an event
o It is any collection of figures that are arranged in general accessed principle or
convention.

Data Processing

o It is the process of rearrangement of collected data in to our desire.


o It is the process of collecting, arranging and representing of a given fact in accordance
with sets of rules.

What is Information

o When data is processed, organized, structured or presented in a given context so as to


make it useful, it is called information.

Data Processing Cycle

Can Be both data or information.


Input
 When the input is Information the process
is called Information Processing instead
of data processing.

Output Process

Information

Page 2 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

Chapter 2: Computer System and Its Evolutions


Evolution of computer system from a user’s point of view
Early Days Later Days

User
User User Computer User
Computer

User User
Current

Computer
Computer
Computer

User
Computer Computer

Generations of computers
Although computer professionals do not agree on exact dates or specifics, computer
developments are often categorized by generations. Actually there are four generations and
major characteristics that distinguish these generations are the following;

• Dominant type of electronic circuit elements used.


• Major secondary storage media used.
• Computer language used.
• Types or characteristic of operating system used.
• Memory access time (a time to store or retrieve a word or data from memory).

Computer generations are usually categorized by dramatic improvement in the hardware,


typically tenfold or better increases in speed and reliability.

Page 3 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

First generation (1950s)

This generation computer used vacuum tubes as components for the electronic circuit.
Punched cards were the main source of inputs, and magnetic grams were used for internal
storage. They operate in a speed of milliseconds (thousands of a second) and could handle
more than 10,000 additions each second. Most applications were scientific calculations.

Second generations (early 1960s)

Transistors were the main circuit components. Invented by Bell Labs, the transistor was
smaller, faster and more reliable than the vacuum tube. Magnetic cores, used for main
storage, could be concerned in microseconds (millionths of a second) with more than
200,000 additions possible each second. Business applications become more common
place, with large data files stored on magnetic tape and disk.

Examples: IBM 1620 –small scientific computers, IBM 1401 –small to medium commercial
computers, IBM 7094 –large scientific computer.

High level languages COBOL and FORTRAN were introduced during this period. Batch
operating systems are used that permitted rapid processing of magnetic tape files.

Third generation (late 1960s, early 1970s)

It was characterized by solid-state logic and integrated circuit (IC). Computer storage
switched from magnetic cores to integrated circuit boards that provide modularity
(expandable storage) and compatibility (interchangeable equipment). Software become
more important with sophisticated operating systems, improved programming languages,
and new input/output methods such as optical scanning and plotters.

Example: IBM system /360 was the dominant, IBM 1130

Fourth generation (late 1970s, early 1989s,)

It has greatly expanded storage capabilities and improved circuitry. It has large scale
integrated circuits (LSI) which has several hundred thousand transistors placed on one tiny
silicon chip. Computer memory operates at speeds of Nano-seconds (billionths of a second)
with large computers capable of adding 15 million numbers per second.

The fifth generation computer

It is in progress. An architecture, which makes use of the changes in technology and allows a
simple and natural methodology for solving problems, is being sought.

Page 4 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

These computers will have:

• Intelligent processors, i.e., processors which can draw inferences.


• Users will also be able to interact with them in natural languages such as English,
German etc.

Types of Computers
There are different types of computers. Their differences depend on different categories of
characteristics.

A. Classification by the method of operation (processing)

Computers are classified by the type of data they are designed to process. They are
classified into three:

1. Analog Computers

Analog computers operate by measuring. They deal with continues variables, they don’t
compete directly with numbers, rather, they operate by measuring physical magnitude such
as pressure, temperature, voltage, current etc. They are special purpose computers.

Examples: Thermometer, Voltmeter, Speedometer, Gasoline pomp, etc.

2. Digital Computers

Digital computers deal with discrete variables; they operate by counting rather than
measuring. They operate directly up on numbers (or digits) that represent numbers, letters,
or other special symbols. Digital computers have very high accuracy and speed than the
analog ones.

Examples: Abacus, Desk & pocket computers and most general purpose computers

III. Hybrid computers

The best features of analog and digital computers can be combined into a single device to
form a hybrid computer. A hybrid computer processes the information by collecting input
data with analog method, converts it into digital quantities, processes the digital values and
converts the output from digital to analog form.

Example: In hospital insensitive-care unit analog devices may measure a patient’s heart
function, temperature and other vital signs. These measurements may then be converted
into numbers and supplied to a digital component in the system. This component is used to
monitor the patient’s vital signs and to send an immediate signal to the nurse’s station if any
abnormal readings are detected.

Page 5 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

B. Classification by purpose of application

Computers can be applied or used for different purposes. Based upon their application, they
are classified as special purpose or general purpose computers.

I. Special purpose computers

They are designed to solve a single type of problem, that is their components and their
functions are uniquely adapted to a specific situation involving specific application. Most
analog computers are special purpose computers.

Example: The public telephone box, Traffic control system, Ticket machines (used in grocery,
super market etc.)

II. General purpose computers

They are designed to solve variety of problems through the use of “store program concept”.
A program or set of instructions designed to solve a problem is read and stored into the
memory and then executed by the computer one by one. The same computer can be
applied to solve another set of problem using different program. General computers are
more flexible and versatile.

Examples: Microcomputers, Mini computers, Super computers etc.

C. Classification by physical size, price, capacity and performance

At this stage, by a computer, we mean a general-purpose digital computer. General-purpose


digital computers are then classified as follows by their capacity and size.

Super computer: - is the fastest, largest and most potential type of computer. They have
speed of hundreds of millions of operation per second, a primary memory capacity of about
80 million characters, and a secondary memory of capacity of about 20 times its primary
memory. They are multi-user systems in intercontinental range. They can carry out
enormously complex scientific calculations. They are used to process huge amount of data
and are commonly used in space technology centers, meteorology stations, astronomical
observatories, intercontinental communications, airline organizations.

Mainframe computers: - Smaller than in size and capacity, lower in speed & memory
capacity than the super computers. However, they are multi-user systems and handle
hundreds of users, usually used in large organizations. The older ones used punched card for
data input.

Page 6 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Mini computers: - have relatively lower speed, can handle multi-users, are smaller in size
than the mainframe computers. They use terminals for inputs and output. Mini computers
are used in small organizations.

Microcomputers: -are the most widely used type of computers. They are single users, can
fit on desktops, are of varying capacity and easy to handle. Microcomputers are sometimes
referred as personal computers. They have video display unit for output purpose. Data is
entered through the keyboard and by the help of floppy disk.

Computers Systems
System is a group of components, consisting of subsystems or procedures that work in a
coordination fashion to achieve some objective.

Hardware: is the physical equipment of the computer


you see, you use to and the parts you can touch.
Hardware
Computer Basic Physical components of a computer system
Software The basic units of a computer system include Central
Processing Unit (CPU), Storage Devices, Input Devices,
Output Devices and Communication Bus. Below is given a detailed explanation of these
devices.

1. Central Processing Unit (CPU) or Processor

It is also referred as the brain of the system. It is that part of the process the data which
contains electronic circuit to process the data. Depending on the instructions of input
devices it performs operations on the data. It also controls the flow of data through the
system, directing the data to enter the system, placing it in memory and retrieving it when
required and directing the output.

The CPU consists of Arithmetical Logic Unit and Control Unit


ALU (Arithmetical Logic Unit): It takes logical decision and performs all type of arithmetical
calculations.

CU (Control unit): It controls all the activities of other units of computer system. It receives
instructions from memory unit. It decodes these instructions. It decides the routing and
storage of these instructions.

Page 7 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

2. Primary Storage Devices/ main Memory

RAM (Random Access Memory)

• Is that the memory which is directly accessible by the control unit and ALU;
• Usually referred as Random Access Memory (RAM), because each memory location
can be accessed without having to work sequentially through hundreds or even
thousands of memory locations called addresses;
• Each memory location can be referred by its memory location (address);
• Holds instructions and data elements which are currently being used by the
computer;
• The data in the main memory while be lost when the power is off;

ROM (Read Only Memory)

• This type of memory is integrated into the circuitry of the computer and cannot be
altered without altering the computer circuitry;
• Used to store basic hardware information;

3. Secondary storage Devices/ Auxiliary Memory

Secondary storage or auxiliary storage, can take many forms, which have traditionally
included punched cards, papers tape, magnetic tape, magnetic disk and magnetic drum. This
storage media are stores data and information permanently.

Magnetic Tapes

Magnetic tapes are a particularly popular form of secondary storage because of their high
data density (the number of bytes of instruction per inch of tape) and their convenience in
handling. Magnetic tapes are approximately one - half inch wide is made of Mylar – based
plastic film which can be magnetized. Data are stored on a magnetic tape by running the
tape over the electromagnetic called read/write head which magnetizes small spots on the
tape. Seven-track tapes store information as bytes of information, where each byte consists
of a six-bit code and a one-bit parity bit. Nine-track tape uses an eight-bit and a parity bit.

Magnetic disks

Magnetic disks are metals or plastic platters coated with ferrous oxide, an easily
magnetically material. Magnetic disks allow for random access of information and overcome
the slow access time commonly found in tape files.

Example: HDD

Page 8 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Hard Disk Drive(HDD): - is part of a computer system which reads from and writes data on a
disk which in turn becomes a file.

• A high capacity magnetic disk made up of metal which can be fixed in the system
unit of the computer.
• Serves as a secondary storage.
• Enables very fast accessibility of data.
• The disks, which are usually grouped together into a disk pack are separated by small
air spaces to allow access for read/write head.
• Each disk has approximately 200 tracks on which information is stored. Tracks of the
small number on all adjacent disks are referred to as a cylinder of that disk.
• The disk pack is mounted on a magnetic disk drive which rotates the disk at speed up
to 1,000 revolutions per second.
• The total collection of tracks available on one movement of the access mechanism is
known as cylinder.
• The amount of time it takes to retrieve (or store) data from (or to) disk is called the
disk access time.

Compact Disk Read Only Memory (CD ROM)

The CDROM is a thin piece of clear polycarbonate plastic with a metal layer covered with a
protective layer of lacquer, with the aluminum layer measuring 120 mm in diameter. It is
mostly useful in multimedia applications where data is huge and needed to be transferred
from one place to another and the requirement is of secure data. The disk can also be used
to distribute songs that also require huge amount of space and to distribute bundled
software packages. The main disadvantage of this type of media is that they are read-only,
which means that the disk manufacture can only put data on them.

4. Input/Out Put Devices

Input Devices

• Is the unit used to enter data into the computer so that it can be processed.
• It converts information from a form suitable to human beings to one
understandable by the computer.

Examples of input devices;

Keyboard (which is the most widely used input devices), Mouse, Scanner, Light pen (a
photo cell to choose a displayed response to request further information), Voice
synthesizer; CD-ROM Drive, etc.

Page 9 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

Output Devices

• Used to get data out of a computer so that it can be examined, analyzed or


distributed to others.
• Convert the result of the only-machine understandable form to a form
understandable by human beings.

Example: The Visual Display Unit (VDU) or monitor or screen, Printers (dot matrix, laser
printers), Plotters, Voice (audio) response unit, Disk drives

5. Communication Bus

We have seen that there are different components of a computer and each performs a
specific function. But to perform a given task in synchronized form there should be some
mechanism of communication. For this reason, there is an electronic circuit which produces
communication path between the different components of a computer system along which
data are transferred, that is Bus. The bus, which communicates the different parts of the
CPU, is called Internal Bus. And the bus, which communicates the CPU with memory and
peripheral devices, is called External Bus. The size of the bus determines the speed of
efficiency of the computer.

Page 10 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

Chapter 3: Computer Software


The computer hardware is an electronic device which has the potential of performing the
task of solving a problem. However, one has to give precise instructions to the hardware in
order to solve problem.

The finite set of instructions (steps) that the computer follows to perform a given job is
called a program. Any program to be executed first it should reside / loaded/ in the
memory.

Software: - is a collection of programs and routines that support the operations of


performing a task using a computer. Software also includes documentations, rules and
operational procedures. Software makes the interface between the user and the electronic
components of the computer.

Software serves as an interface between a user and a computer.

Computer software is classified into two

1. System Software
2. Application Software

1. System Software
• Constitutes those programs which facilitates the work of the computer hardware.
• It organizes and manages the machine’s resources, handles the input/output devices.
• It controls the hardware by performing functions that users shouldn’t have to or are
unable to handle.
• System programs make complex hardware more users friendly.
• It acts as intermediate between the user and the hardware.
• It enables the computer understand programming languages i.e. it serves as means of
communication between user and a computer.

Page 11 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

The important categories of system software are:

I. Operating system
II. Language software

I. Operating system
Operating system coordinates the activity between the user and the computer. It serves as
an intermediary between programs and hardwares.

Types of Operating Systems: Operating systems can be classified by:

• The number of programs they can handle at a time and


• The number of users they serve at once at one or different stations (i.e. terminals or
micro-computers connected to a central computer).
i. Single-user, Single tasking operating systems
• With single tasking operating systems only one program can be run on a computer at
a time.
• In order to run another program, one must remove the first program loaded in the
computers main memory and load the other one (i.e. it can’t handle two or more
programs at a time)
• These types of operating systems are single user or can serve only one user at a
time.
ii. Single-user, multi-tasking operating systems
• This is the type of operating system most people use on their desktop and laptop
computers today. Microsoft's Windows and Apple's MacOS platforms are both
examples of operating systems that will let a single user have several programs in
operation at the same time. For example, it's entirely possible for a Windows user to
be writing a note in a word processor while downloading a file from the Internet
while printing the text of an e-mail message.
iii. Multi-user –
• A multi-user operating system allows many different users to take advantage of the
computer's resources simultaneously. The operating system must make sure that the
requirements of the various users are balanced, and that each of the programs they
are using has sufficient and separate resources so that a problem with one user
doesn't affect the entire community of users. Unix, VMS and mainframe operating
systems, such as MVS (Multiple Virtual Storage), are examples of multi-user operating
systems.

It's important to differentiate between multi-user operating systems and single-user


operating systems that support networking. Windows 2000 and Novell Netware can
each support hundreds or thousands of networked users, but the operating systems

Page 12 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

themselves aren't true multi-user operating systems. The system administrator is the
only "user" for Windows 2000 or Netware. The network support and all of the remote
user logins the network enables are, in the overall plan of the operating system, a
program being run by the administrative user.

iv. Real Time Operating System


• A real time is a system that is capable of processing data so quickly that the results
are available to influence the activity currently taking place.
• Real-time operating systems are used to control machinery, scientific instruments
and industrial systems. An RTOS typically has very little user-interface capability, and
no end-user utilities, since the system will be a "sealed box" when delivered for use.
A very important part of an RTOS is managing the resources of the computer so that
a particular operation executes in precisely the same amount of time, every time it
occurs. In a complex machine, having a part move more quickly just because system
resources are available may be just as catastrophic as having it not move at all
because the system is busy.
II. Language Software
Are software which are used by programmers to develop application software and translate
programs to machine code.

• Language software is a generic name consisting of various programs that serve as


editors & translators to develop programs in a number of programming languages.
 Translator: - is a program that converts one or more languages to another language.
 Three types of translators are Assemblers, Compilers & Interpreters.
 Assemblers: -is a program that translates assembly languages into machine code.
An assembler is a program that takes basic computer instruction s and converts
them into a pattern of bit s that the computer's processor can use to perform its
basic operations. Some people call these instructions assembler language and
others use the term assembly language. The programmer can write a program
using a sequence of these assembler instructions. This sequence of assembler
instructions, known as the source code or source program, is then specified to the
assembler program when that program is started. The assembler program takes
each program statement in the source program and generates a corresponding bit
stream or pattern (a series of 0's and 1's of a given length). The output of the
assembler program is called the object code or object program relative to the
input source program. The sequence of 0's and 1's that constitute the object
program is sometimes called machine code. The object program can then be run
(or executed) whenever desired.

Page 13 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

 Compiler: - is a program that translates a high level language into machine code.
A compiler is computer software that transforms computer code written in one
programming language (the source language) into another computer language
(the target language). Compilers are a type of translator that support digital
devices, primarily computers. The name compiler is primarily used for programs
that translate source code from a high-level programming language to a lower
level language (e.g., assembly language, object code, or machine code) to create
an executable program.
 Interpreter: - is a program that translates each instruction of high level language
& executes the instruction before translating the next instruction. Interpreter is a
program that executes instructions written in a high-level language. There are two
ways to run programs written in a high-level language. The most common is to
compile the program; the other method is to pass the program through an
interpreter. One of the well-known programming languages that uses an
interpreter is PHP.
• High-level programming languages Vs Low-level programming languages
 A High-level language is a programming language designed to simplify computer
programming. It is "high-level" since it is several steps removed from the actual
code run on a computer's processor. High-level source code contains easy-to-read
syntax that is later converted into a low-level language, which can be recognized
and run by a specific CPU. Most common programming languages are considered
high-level languages. Examples include: C++, C#, Java, JavaScript, PHP, Python...
 A Low-level language is a programming language that deals with a computer's
hardware components and constraints. It has no (or only a minute level of)
abstraction in reference to a computer and works to manage a computer's
operational semantics. A low-level language may also be referred to as a
computer’s native language. Low-level languages are designed to operate and
handle the entire hardware and instructions set architecture of a computer directly.
Machine language and assembly language are popular examples of low-level
languages.
• Procedural Vs Structured Vs Object Oriented programming languages
 A procedural programming language consists of a set of procedure calls and a set
of code for each procedure. Example: BASIC
 A structural programming language emphasizes on separating a program’s data
from its functionality. Example: C
 Object oriented languages are based on entities known as objects. Example: Java

Page 14 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

2. Application Software
• Is software that is designed to perform tasks for the specific area or areas. But for use in
more than one installation.
• Are usually called application packages as they may include a number of programs along
with operating instruction, documentation and so forth.

Malwares:
Are computer programs that interfere with a computer's hardware and operating system.
There are different types of malware that contain unique traits and characteristics. A virus is
the most common type of malware, and it's defined as a malicious program that can
execute itself and spreads by infecting other programs or files. A

worm is a type of malware that can self-replicate without a host program; worms typically
spread without any human interaction or directives from the malware authors. A Trojan
horse is a malicious program that is designed to appear as a legitimate program; once
activated following installation, Trojans can execute their malicious functions.

Spyware is a kind of malware that is designed to collect information and data on users and
observe their activity without users' knowledge.

Other types of malware include functions or features designed for a specific purpose.
Ransomware, for example, is designed to infect a user's system and encrypt the data.
Cybercriminals then demand a ransom payment from the victim in exchange for decrypting
the system's data.

Virus, a malicious code that replicates and hides itself inside other programs usually without
your knowledge. A virus is a piece of software that can "infect" other programs by modifying
them. Similar to biological virus: Replicates and Spreads Some exists to simply replicate
themselves. Others can do serious damage such as erasing file…

Page 15 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

Chapter 4: Computer Number System


Before discussing numbering systems with in a computer context there are a few terms we
need to define.
1. Bit:
• Is the smallest unit of data representation.
• Is a space that can hold a single state.
2. Byte:
• Is the smallest unit of data measurement.
• Is a single group of 8 bits. [1 Byte = 8 Bits.]
3. Word:
• Is a group of 8 Bytes. [1 word = 8 Bytes.]
Decimal Number System

Z = {0,1,2,3,4,5,6,7,8,9}; B = 10

• Each position to the left of a digit increases by a power of 10.

• Each position to the right of a digit decreases by a power of 10.

Example:

(47692)10 = 2 * 100 + 9 * 101 + 6 * 102 + 7 * 103 + 4 * 104

= 2 + 90 + 600 + 7000 + 40000

Binary Number System

• Has two states 1(ON state) and 0(OFF state).

Z = {0,1}; B = 2

Unsigned number representation

With n bits we can represent 2n unsigned integer numbers.

Range: from 0 to 2n-1

So with 8 bits we can represent 28 (256) numbers from 0 to 28-1(255)

• Each position to the left of a digit increases by a power of 2.

• Each position to the right of a digit decreases by a power of 2.

Example:

(11001)2 = 1*20 + 0*21 + 0*22 + 1*23 + 1*24

= 1 + 0 + 0 +8 + 16 = (25)10

Page 16 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Signed number representation

Here we would need to consider sign, meaning we represent both positive and negative numbers. To do
this we will first look at a method called sign and magnitude.

Sign and magnitude

With this method we reserve the most significant bit of the left most bit for sign. This bit is called sign
bit.

0 Posetive
Sign Bit
1 Negative

Similar to the unsigned numbers with n bits we represent 2n numbers. The difference here is that both
positive and negative are to be represented.

Range:

 Since we took 1 bit for parity we have n-1 bits left for the number.
 We want to include negative as well as positive numbers and zero so our range starts from the
negative goes through zero and reaches the positive.
With these two ideas in mind our range becomes from -(2n-1-1) to 2n-1-1

So with 8 bits we can represent 28 numbers (256)

-(28-1-1) to (28-1-1) = -(27-1) to (27-1) = -127 to 127.

Example: (11001)2

The first bit (MSB) indicates the number is negative since it is 1.

= 1*20 + 0*21 + 0*22 + 1*23

= - (1 + 0 + 0 +8) = (-9)10

Octal Number System

Z = {0,1,2,3,4,5,6,7}; B = 8

• Each position to the left of a digit increases by a power of 8.

• Each position to the right of a digit decreases by a power of 8.

Example:

(12403)8= 3 * 80 + 0 *81 + 4 * 82 + 2 * 83 + 1 * 84

= 3 * 1 + 0 * 8 + 4 * 64 + 2 * 512 + 1 * 4096

= (5379)10

Page 17 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Hexadecimal Number System

Z = (0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F}; B = 16

• Each position to the left of a digit increases by a power of 16.

• Each position to the right of a digit decreases by a power of 16.

Example:

FB40A16 = 10 * 160 + 0 * 161 + 4 * 162 + 11 * 163 + 15 * 164

= 10 * 1 + 0 * 16 + 4 * 256 + 11 * 4096 + 15 * 65536

= (1,029,130)10

Comparison of Number Systems

Decimal Dual Octal Hexadecimal Decimal Dual Octal Hexadecimal

0 00 000 00 00 16 10 000 20 10
1 00 001 01 01 17 10 001 21 11

2 00 010 02 02 18 10 010 22 12

3 00 011 03 03 19 10 011 23 13

4 00 100 04 04 20 10 100 24 14

5 00 101 05 05 21 10 101 25 15

6 00 110 06 06 22 10 110 26 16

7 00 111 07 07 23 10 111 27 17

8 01 000 10 08 24 11 000 30 18

9 01 001 11 09 25 11 001 31 19

10 01 010 12 0A 26 11 010 32 1A

11 01 011 13 0B 27 11 011 33 1B

12 01 100 14 0C 28 11 100 34 1C

13 01 101 15 0D 29 11 101 35 1D

14 01 110 16 0E 30 11 110 36 1E

15 01 111 17 0F 31 11 111 37 1F

Conversions Between Number Systems

Page 18 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Conversion of Natural Numbers: Base 10 ⇒ Base B Conversion

We use the method of iterated division to convert a number N10 of base 10 into a number NB of base B.

Step 1. Divide the number N10 by: whole number BN & remainder R.

 Take N as the next number to be divided by B.


 Keep R as the next left-most digit of the new number.
Step 2. If N is zero then STOP, else set N10 = N and go to step 1.

Example: Decimal to Binary (1020)10 = ( )2

Number to be converted: N10 = 1020; target base B=2

1020 / 2 = 510 Remainder: 0

510 / 2 = 255 Remainder: 0

255 / 2 = 127 Remainder: 1

127/ 2 = 63 Remainder: 1

63 / 2 = 31 Remainder: 1 (1020)10 = (1111111100 )2

31 / 2 = 15 Remainder: 1

15 / 2 = 7 Remainder: 1

7/2=3 Remainder: 1

3/2=1 Remainder: 1

1/2=0 Remainder: 1

Powers of 2
N 2N N 2N Note:
0 1 17 131,072
1 2 18 262,144 By looking at the power of 2, we can figure out a better
2 4 19 524,288 way of converting decimals to binary.
3 8 20 1,048,576
4 16 21 2,097,152
5 32 22 4,194,304
6 64 23 8,388,608
7 128 24 16,777,216
8 256 25 33,554,432
9 512 26 67,108,864
10 1,024 27 134,217,728
11 2,048 28 268,435,456
12 4,096 29 536,870,912
13 8,192 30 1,073,741,824
14 16,384 31 2,147,483,648
15 32,768 32 4,294,967,296
16 65,536 33 8,589,934,592

Page 19 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Example: Decimal to Octal (1020)10 = () 8

Number to be converted: ; target base

1020 / 8 = 127 Remainder: 4

127 / 8 = 15 Remainder: 7
(1020)10 = (1774 )8
15 / 8 = 1 Remainder: 7

1/8=0 Remainder: 1

Example: Decimal to Hexadecimal (1020)10 = () 16

1020 / 16 = 63 Remainder: C

63 / 16 = 3 Remainder: F
(1020)10 = (3FC )8
3 / 16 = 0 Remainder: 3

Conversion of Rational Numbers

Converting binary fractions to rational numbers (decimal fractions)

To convert binary fractions to their decimal equivalents, all we would need to do is multiply each bit
with its power of 2 position.

Example: (0.11001)2 = ()10

0.11001 = 1 * 2-1 + 1 * 2-2 + 0 * 2-3 + 0 * 2-4 + 1 * 2-5

= 1 * 0.5 + 1 * 0.25 + 0 * 0.125 + 0 * 0.0625 + 1 * 0.03125

= 0.5 + 0.25 + 0.03125

= 0.7812510

Note: To convert octal and hexadecimal fractions to their decimal equivalents we follow the same steps
we used above except we change the multiplier(Base) to 8 and 16 respectively.

Converting rational numbers to Baes B fractions

To convert rational numbers to their Base B fraction equivalent we will follow the following steps.

Step 1: Multiply the number after decimal point by B

Step 2: Take number before the decimal point from the result.

Step 3: repeat steps 1 and 2 until there is no decimal point to multiply

Page 20 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Example 1: (0.15625)10 = ()2

Step i N Operation Next z


(–i)
1 0.15625 0.15625 * 2 = 0.3125 0.3125 0
2 0.3125 0.3125 * 2 = 0.625 0.625 0 (0.15625)10 = (00101)2
3 0.625 0.625 * 2 = 1.25 0.25 1
4 0.25 0.25 * 2 = 0.5 0.5 0
5 0.5 0.5 · 2 = 1 None 1

Example 2: (0.15625)10 = ()8

Step i N Operation Next z


(–i)
1 0.15625 0.15625 * 8 = 1.25 0. 25 1 (0.15625)10 = (12)8
2 0.25 0.25 * 8 = 2 None 2

Example 3: (0.15625)10 = ()16

Step i N Operation Next z


(–i)
1 0.15625 0.15625 * 16 = 2.5 0. 5 2 (0.15625)10 = (28)8
2 0.5 0.5 * 16 = 8 None 8

Conversion of binary digits to octal and hexadecimal digits

To convert binary digits to their octal equivalent it’s important to answer one question.

How many binary digits are equivalent to one octal digit? ( 1 octal bit = ? binary bits)

Octal => base 8 => 8=23 hence 1 octal digit is equivalent with 3 binary digits. (1 octal bit = 3 binary bits)

So all we need to do is group each 3 binary digits and convert to its decimal equivalent.

Converting binary digits to Hexadecimal is also done in the same manner. So we will answer the same
kind of question we asked earlier, how many binary digits are equivalent to one hexadecimal digit?

Hexadecimal => base 16 => 16=24 hence 1 hexadecimal digit is equivalent with 4 binary digits.

(1 hex bit = 4 binary bits)

Example: (101111010)2 = 101 111 010 => 101 = 5, 111 = 7, 010 = 2

= (5 7 2)8

Example: (101111010)2 = 0001 0111 1010

= (1 7 A)16

Page 21 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

Chapter 5: Computer Arithmetic


Now that binary numbers are discussed, it’s time to look at how their arithmetic works. But
there are two basic binary number representations so far. Unsigned binary numbers and binary
numbers that are represented using the sign and magnitude method.

 Addition and subtraction for unsigned binary integers


1. Addition Rule 2. Subtraction Rule
1 with a borrow of 1
1 0 1 1 0 1 Making it
0 1 + 1 0 with a 1 1 - 0
0 0 0 carry of 1 0 0 0 [10-1=1]
1 1 10 0 1 1
Example: Example:

Carry Borrow

 Addition & subtraction for signed binary integers (using sign and magnitude)
If the binary numbers are signed then addition and subtraction can be expressed using just the
addition operation. Take a look at the following equations.

• X – Y = X + (- Y )
• - X – Y = (- X ) + (- Y)

Recap: The first bit of the binary number indicates sign, 0 for positive and 1 for negative

Rules:
1. Identify the sign of each binary number [ the sign bit is excluded for the calculation]
A. If they both have the same sign
• Add the two binaries.
• Apply the sign to the result.

Page 22 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Example:

Same
sign

B. If they have different signs


• Compare the numbers
• Subtract small from large.
• Apply the sign of the large number to the result.
Example:

Different
sign

Compare 100>010

Take the sign of


the large number
[100]

Which is 1

Note: When calculating binary addition for integers represented using sign and magnitude,
overflow may occur.
0101 + 0110 = 1011 => 5 + 6 = -5 [ Discuss Correction]

Page 23 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
 Multiplication and Division for unsigned binary integers
Multiplication Rules:

1 0 0 Multiplication for unsigned integers is straight


0 1 * 0 forward,
0 0 0 • Find out the number of bits needed n
1 1 1 • Represent both numbers with n
• apply decimal multiplication rule
• apply the unsigned binary addition rule
• cut-off unnecessary bits

Example:

4*2=8
Number of bits needed -> the immediate next 2n for 8 is 16=24 so 4 bits
0 1 0 0 * 0 0 1 0
0 0 0 0
0 1 0 0
0 0 0 0
0 0 0 0
0 0 0 1 0 0 0

Cut off

Division Rules:

• Assumption
o n= number of bits of the divisor db1
o db2= dividend
• cut n from db2 to create a smaller binary b
• if b is less than db1 then multiply db1 by 1
• if b is greater than db1 then multiply db1 by 0
• subtract and continue until the dividend is exhausted
o apply the subtraction rule for unsigned integers
o trim unnecessary bits

Page 24 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Example 1:

8/2=4
1 0, 0 0 1 0
1 0 1 0 0
0 0 0
0 0
0 0 0
0 0
0 0 End

Example 1:
9 / 4 = 2 with a reminder of 1

1 0 0, 1 1 0 0
1 0 0 1 0 0
0 0 0
0 0 0
0 0 0 1
0 0 0
0 0 1 End with a remainder

 Multiplication and Division for signed binary integers (using sign and
magnitude)
Rules:

• Look at the sign bits of each binary integers


• Exclude the sign bits from the calculation
• Perform the normal multiplication/division
 If the signs are different assign 1 as the sign bit for the result
 If the signs are the same assign 0 as the sign bit for the result

Page 25 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
 Binary Complements
Complements are used to represent negative integers in a binary form. Positive integers are
represented in the normal binary from.

• 1’s complement
Simply convert 0s to 1s and 1s to 0s.

()10 ()2 Notice that the 1’s C ()2 ()10 Take +1 (001), to find -1 all that is needed
0 000 negative integers 111 0 to be done to convert 0s to 1s and 1s to 0s
+1 001 always start with 1 110 -1 so
+2 010 and the positive 101 -2
+3 011 once start with a 0 100 -3 001
+4 010 101 -4
+5 0101 1010 -5
110

• Subtraction using 1’s complement


Since every negative integer can be represented uniquely subtraction can be replaced with
addition. Like previously X – Y = X + (-Y).
Rule: If there is a remainder at the end it’s added to the result.
Example:

4 – 2 = 4 + (-2) = 2
(4)10 == (0100)2 -(2)10 = -( (2)10 ) == -( (0010)2 ) = (1101)2

1 1 This Method is much better and more effective than the


0100 sign-magnitude method because there is no need to
+ 1101 Last Carry isolate the sign bit making the calculation more natural.
So It’s mathematically less complicated.
0001
+ 1 Discussion: What problems do you observe in 1’s
0010 complement and it’s subtraction? [Use -2-2]

• 2’s compliment
This is a more refined version of 1’s compliment. It solves the problem of 1’s complement.
To find the 2’s complement of a negative integer, first find the 1’s complement the add 1.

Page 26 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
()10 ()2 1’s C ()2 2’s C ()2 ()10 Discussion: How does 2’s complement solve the problem
0 000 111 000 0 of 1’s complement?
+1 001 110 111 -1
+2 010 101 110 -2
+3 011 100 101 -3
+4 010 101 110 -4
+5 0101 1010 1011 -5

• Subtraction using 2’s complement


Rule: If there is a remainder at the end it’s dropped and the process ends.
Example:

4 – 2 = 4 + (-2) = 2
(4)10 == (0100)2 -(2)10 = -( (2)10 ) == -( (0010)2 ) = (1101 + 1)2
1
1 1
1101
0100
+ + 1
Drop 1110
1110
0010

 Multiplication using 1’s complement


Observe the following example:

2 * -2 = -4 using 4 bits
0 0 1 0 * 1 1 0 1
0 0 1 0
0 0 0 0
This is incorrect. +
To check perform 0 0 1 0
–(-x)=x using 1’s 0 0 1 0
complement 0 0 1 1 0 1 0
-(1010)=(0101)=5
but -2*2 = -4 and
–(-4)=4 not 5
Discussion: Why is this happening? How can it be solved?

Page 27 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
 Multiplication using 2’s complement
The benefit of 2’s complement is that the mathematics is very straight forward, hence applying
the normal binary multiplication is enough to get the accurate result.

2 * -2 = -4 0010 * 1110
0 0 1 0 * 1 1 1 0
0 0 0 0
0 0 1 0
+
0 0 1 0
0 0 1 0
0 0 1 1 1 0 0
 Division using 2’s complement
Observe the following statements.

X / -Y = -X / Y = -( X / Y ) With these rules set, division can be interpreted to


subtraction. For example: 16/4 means
-X / -Y = X / Y
16 – 4 = 12 =========> 1 step There are 4 steps
needed to reach 0,
Rules: 12 – 4 = 8 ==========> 1 step
which indicates the
8 – 4 = 4 ===========> 1 step end of the process.
• Check the sign of each binary.
Hence 16/4 = 4
• Apply the above rule 4 – 4 = 0 ===========> 1 step
• Perform 2’s comp’ subtraction.
Example:
16 / -4 using 6 bits.

- ( 16 / 4 ) = -( 4 ) 16 = 0 1 0 0 0 0 4 = 0 0 0 1 0 0
Translate division to subtraction in 2’s complement.
0 1 0 0 0 0 – ( 0 0 0 1 0 0 ) == 0 1 0 0 0 0 + 1 1 1 1 0 0 = 0 0 1 1 0 0
0 0 1 1 0 0 – ( 0 0 0 1 0 0 ) == 0 0 1 1 0 0 + 1 1 1 1 0 0 = 0 0 1 0 0 0
0 0 1 0 0 0 – ( 0 0 0 1 0 0 ) == 0 0 1 0 0 0 + 1 1 1 1 0 0 = 0 0 0 1 0 0
0 0 0 1 0 0 – ( 0 0 0 1 0 0 ) == 0 0 0 1 0 0 + 1 1 1 1 0 0 = 0 0 0 0 0 0 End
It took 4 steps to reach 0 hence the quotient 4 [ 0 0 0 1 0 0 ] but the
sign of the result is negative as established at the beginning so
– ( 0 0 0 1 0 0 ) so 1 1 1 1 0 0
Discussion: How would 2’s complement division work for integers that divide to give out a
remainder? [ Use 7 / -3 ]
Page 28 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

 Floating-Point Number Representation

A floating-point number (or real number) can represent a very large (1.23×10^88) or a very
small (1.23×10^-88) value. It could also represent very large negative number (-1.23×10^88)
and very small negative number (-1.23×10^88), as well as zero, as illustrated:

A floating-point number is typically expressed in the scientific notation, with a fraction (F), and
an exponent (E) of a certain radix (r), in the form of F×r^E. Decimal numbers use radix of 10
(F×10^E); while binary numbers use radix of 2 (F×2^E).
Representation of floating-point number is not unique. For example, the number 55.66 can be
represented as 5.566×10^1, 0.5566×10^2, 0.05566×10^3, and so on. The fractional part can be
normalized. In the normalized form, there is only a single non-zero digit before the radix point.
For example, decimal number 123.4567 can be normalized as 1.234567×10^2; binary number
1010.1011B can be normalized as 1.0101011B×2^3.
It is important to note that floating-point numbers suffer from loss of precision when
represented with a fixed number of bits (e.g., 32-bit or 64-bit). This is because there are infinite
number of real numbers (even within a small range of says 0.0 to 0.1). On the other hand, a n-
bit binary pattern can represent a finite 2^n distinct numbers. Hence, not all the real numbers
can be represented. The nearest approximation will be used instead, resulted in loss of
accuracy. It is also important to note that floating number arithmetic is very much less efficient
than integer arithmetic. It could be speed up with a so-called dedicated floating-point co-
processor. Hence, use
integers if your application does not require floating-point numbers. In computers, floating-
point numbers are represented in scientific notation of fraction (F)
and exponent (E) with a radix of 2, in the form of F×2^E. Both E and F can be positive as well as
negative. Modern computers adopt IEEE 754 standard for representing floating-point numbers.
There are two representation schemes: 32-bit single-precision and 64-bit double-precision.

Page 29 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

• IEEE-754 32-bit Single-Precision Floating-Point Numbers


In 32-bit single-precision floating-point representation:
 The most significant bit is the sign bit (S), with 0 for positive numbers and 1
for negative numbers.
 The following 8 bits represent exponent (E).
 The remaining 23 bits represents fraction (F).

• Normalized Form
Let's illustrate with an example, suppose that the 32-bit pattern is 1 1000 0001 011 0000 0000
0000 0000 0000, with:
 S=1
 E = 1000 0001
 F = 011 0000 0000 0000 0000 0000
In the normalized form, the actual fraction is normalized with an implicit leading 1 in the form
of 1.F. In this example, the actual fraction is 1.011 0000 0000 0000 0000 0000 = 1 + 1×2^-2 +
1×2^-3 = 1.375D. The sign bit represents the sign of the number, with S=0 for positive and S=1
for negative number. In this example with S=1, this is a negative number, i.e., -1.375D. In
normalized form, the actual exponent is E-127 (so-called excess-127 or bias-127). This is
because we need to represent both positive and negative exponent. With an 8-bit E, ranging
from 0 to 255, the excess-127 scheme could provide actual exponent of -127 to 128.
In this example, E-127=129-127=2D.
Hence, the number represented is -1.375×2^2=-5.5D

Page 30 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

Chapter 7: System Development


The systems development life cycle (SDLC) is a term used in
systems engineering, information systems and software
engineering to describe a process for planning, creating, testing,
and deploying an information system.

A systems development life cycle is composed of a number of


clearly defined and distinct work phases which are used by
systems engineers and systems developers to plan for, design,
build, test, and deliver information systems.

Design: In systems design, the design functions and operations are described in detail, including screen
layouts, business rules, process diagrams and other documentation. The output of this stage will
describe the new system as a collection of modules or subsystems.

Design can be shown using algorithms.

Algorithm: an effective method expressed as a finite list of well-defined instructions for solving a
problem.

An algorithm must possess the following properties:

finiteness: The algorithm must always terminate after a finite number of steps.

definiteness: Each step must be precisely defined; the actions to be carried out must be rigorously and
unambiguously specified for each case.

input: An algorithm has zero or more inputs, taken from a specified set of objects.

output: An algorithm has one or more outputs, which have a specified relation to the inputs.

effectiveness: All operations to be performed must be sufficiently basic that they can be done exactly
and in finite length.

An algorithm may be expressed in a number of ways, including:

natural language: usually verbose and ambiguous

flow charts:

• avoid most (if not all) issues of ambiguity


• Difficult to modify without specialized tools
• Largely standardized

Page 31 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
pseudo-code:

• also avoids most issues of ambiguity


• Vaguely resembles common elements of programming languages
• No particular agreement on syntax

programming language: tend to require expressing low-level details that are not necessary for a high-
level understanding.

1. Flowchart
• is a picture (graphical representation) of the problem
• solving process.
A flowchart gives a step-by-step procedure for solution of a problem.

Flowchart symbols Geometric shape Purpose


Ellipse Ellipse is used to indicate the start and end of a flowchart.
Start written in the ellipse indicates the beginning of
a flowchart. End or Stop or Exit written in the ellipse
indicates the end of the flowchart.
Parallelogram A parallelogram is used to read data (input) or to print
data (output).
Rectangle A rectangle is used to show the processing that takes place
in the flowchart.
Diamond A diamond with two branches is used to show the decision
Y making step in a flowchart. A question is specified in the
diamond. The next step in the sequence is based on the
N answer to the question which is “Yes” or “No”.
Arrows Arrows are used to connect the steps in a flowchart, to
show the flow or sequence of the problem solving process

Example1 : Ana algorithm that takes two numbers and finds the sum.

Page 32 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Example 2: An algorithm that list the multiplication table for a given number.

2. Pseudocode
Artificial and Informal language that helps programmers to plan an algorithm. It is somewhat similar to
everyday English with a feel of programming language.

Example: a Pseudocode for a program that calculates the factorial for a given number.

Page 33 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

Chapter 8: Introduction to C Programming


Introduction
A program written in a high-level language is called a source program (or source code). Since a
computer cannot understand a source program. Program called a compiler is used to translate
the source program into a machine language program called an object program. The object
program is often then linked with other supporting library codes before the object can be
executed on the machine.

Source File Compiler Object File Linker Excutable File

• Source program
– The form in which a computer program, written in some formal programming
language, is written by the programmer.
– Can be compiled automatically into object code or machine code or executed by
an interpreter.
– C source programs have extension ‘. c’
• Object program
– Output from the compiler
– Equivalent machine language translation of the source program
– Files usually have extension ‘.obj’ or (.o) in C
• Executable program
– Output from linker/loader
– Machine language program linked with necessary libraries & other files
– Files usually have extension ‘.exe’
• Linker
– A program that pulls other programs together so that they can run.
– Most programs are very large and consist of several modules.
– Even small programs use existing code provided by the programming
environment called libraries.
– The linker pulls everything together, makes sure that references to other parts
of the program (code) are resolved.
Only about 100 instructions that the computer understands - Different programs will just use
these instructions in different orders and combinations. The most valuable part of learning to
program is learning how to think about arranging the sequence of instructions to solve the
problem or carry out the task.

Page 34 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Putting the Instructions Together

 Sequential Processing
 A List of Instructions
 Conditional Execution
 Ifs
 Repetition
 Looping / Repeating
 Stepwise Refinement / Top-Down Design
 Breaking Things into Smaller Pieces
 Calling Methods / Functions / Procedures / Subroutines
 Calling a segment of code located elsewhere
 Reuse of previously coded code segment

C Programming
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It is a
Procedural Oriented Programming Language (POP) i.e., it focuses on the procedure in which
the program is written. It is one of the oldest programming languages almost 3 decades old.

C is one of the most popular programming languages. It is being used on several different
software platforms. C is an procedural language. It was designed to be compiled using a
relatively straightforward compiler, to provide low-level access to memory, to provide language
constructs that map efficiently to machine instructions, and to require minimal run-time
support.
Relations to other languages

Many later languages have borrowed directly or indirectly from C, including C++, Java, JavaScript,
C#, Unix's C shell. These languages have drawn many of their control structures and other basic
features from C. Most of them are also very syntactically similar to C in general.
1. A high level programming language enables the programmer to concentrate on the problem
Characteristics of C
at hand.
2. C has only 32 keywords.
3. Makes extensive use of function calls.
4. C is well suited for structured programming.
5. Facilitates low level(bitwise) programming.
6. C is a core language as many other programming languages( like c++, java etc) are based
on C.
7. C is a portable language i.e a C program written for one computer can be run on another
computer with little modification.
8. C is an extensible language as it enables the user to add his own functions to C library.

Page 35 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Structure of a C program

Writing the first C program

#include
int main()
{
printf(”\n Welcome to the world of C”);
return 0;
}

Output

Welcome to the world of C

Program Explanation
#include

This is a preprocessor command that comes as the first statement in our [Link] # include
statement tells the compiler to include the standard input/output library i.e stdio.h in the program. So
by simply including this file in our code we can use these functions directly.
int main ()

Execution starts from main() and int is the return value of the main function. The two curly braces {}
are used to group all the related statements of the function main.
printf ()

This function is defined in stdio.h file and is used to print text on the screen. Like in this program the
line written in printf in double quotes is automatically printed on the output screen i.e Welcome to the
world of C. ‘\n’ is an escape sequence and represents a new line.
return 0;

This is a return command that is used to return the value 0 to the operatinf system to give an
indication that there were no errors during the execution of the program.

Note: Every statement in the main function ends with a semicolon ;

Keywords: are the reserved words in programming and are part of the syntax.

Identifiers: are the names that are given to various program elements such as variables, symbolic
constants and functions.
Some rules are to be followed:

Page 36 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
1. Identifier name must be a sequence of letter and digits, and must begin with a letter.
2. The underscore character (‘_’) is considered as letter.
3. Names shouldn't be a keyword (such as int , float, if ,break, for etc).
4. Both upper-case letter and lower-case letter characters are allowed. However, they're not
interchangeable.
5. No identifier may be keyword.
6. No special characters, such as semicolon,period,blank space, slash or comma are permitted.

Basic data types in C

C has a concept of 'data types' which are used to define a variable before its use. The definition of a
variable will assign storage for the variable and define the type of data that will be held in the
location.
The value of a variable can be changed any time.

C has the following basic built-in datatypes.

1. int
2. float
3. double
4. char
5. Void: - Void is a data type that holds no value. Its size in bytes is 0. The range is valueless.

Variables and Constants


• Variables

An entity that varies through the programming is called a variable. These are names given to
locations in memory which can be integer, real or character constant. The type of variables depend
upon the constants it can hold ie an integer variable will hold integer constants.

There are some rules which have to be followed while constructing variables. These rules hold true
for every type of variable.

1. It can be a combination of 1 to 31 characters (alphabets, numbers or underscores). Some


compilers allow a combination of up to 247 characters but it is recommended to stick to 31
characters.
2. First character has to be an alphabet or an underscore.
3. There can’t be any blanks or commas in variable name.
4. You can’t use any special character except underscore ex abc_xyz

The C compiler can identify each variable as it makes compulsory for the user to declare the type of
variable it is. This is done in the beginning of the program.

Example, int si,add ; float ci ; etc

Page 37 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
NOTE: There are some predefined keywords in C compiler. It is advised to not use variable names
similar to these.
• Numeric Variables

Numeric Variable can be used to store either integer values or floating point values. Numeric
Variables can also be associated with modifiers like short, long, signed, and unsigned.

When we do not specify the signed/ unsigned modifier, C language automatically takes it as a
signed variable.
• Character Variables

Character variables can include any letter from any alphabet or from the ASCII chart and numbers 0-
9 that are given within single quotes. For eg:- 2 is considered an Integral value whereas ‘2’ is
considered a character variable.

Declaring Variables

Each variable to be used in the program must be declared.

To declare a variable, specify the data type of the variable followed by its name. This data type
indicates the kind of data that the variable will store. Variable names should always be meaningful
and must reflect the purpose of their usage in the program. In C, variable declaration always ends
with a semicolon,
For example:-

int roll_no;
float marks;
char grade;
double amount;
unsigned short int add_no;

C allows multiple variables of the same type to be declared in one statement.

float temp_in_celcius , temp_in_farenheit;

is legal in c

In C variables are declared at three basic places:

1. When a variable is declared inside a function it is known as local variable.


2. When a variable is declared in the definition of function parameters it is known as formal
parameter.
3. When the variable is declared outside all functions it is known as global variable.

Page 38 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Note: - A variable cannot be of type void

Initializing Variables

While declaring the variables, we can also initialize them with some value.
For example: -

int roll_no = 7;
float salary =1000;

Constants

Constants are identifiers whose value does not [Link] can change their value at any time
but constants can never change their [Link] are used to define fixed values like Pi or
charge on an electron so that their value does not get changed in the program even by mistake.

We can use alphabets (A,B,C,d,e…) , numbers (1,2,3…) and characters or special symbols (-,*,&…)
while using C. These when combined properly form constants and variables. There are mainly two
types of C Constants:

1. Primary Constants
2. Secondary Constants

Rules for constructing integer constants:

1. Must have at least one digit.


2. Can be either positive or negative.
3. Should not have a decimal point.
4. If there is no sign before a digit it is taken as positiv.
5. No commas or blanks within.
6. Allowable range is -32768 to 32767.

Well actually the range depends on the compiler ie if it is a 16-bit or 32-bit or 64-bit, the range keeps
on increasing respectively.

Rules for constructing real constants:

1. Often called floating point constants.


2. Must have at least one digit.
3. Must have a decimal.
4. Could be either positive or negative.
5. Default sign is positive.
6. No commas or blanks within.

Page 39 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
Real constants can also be expressed in exponential form. The part appearing before e is
called mantissaand following it is called exponent. These rules must be taken care of before
expressing in exponential form:

1. Mantissa and exponential part should be separated by e.


2. Mantissa part may be negative or positive.
3. Default sign is positive.
4. There must be a digit after exponent; it may be positive or negative.
5. Ranges from -3.4e38 to 3.4e38.

Rules for constructing character constants:

1. It can be a single digit, a single alphabet, a single special symbol. It should be enclosed
within two inverted commas going towards left ie, ‘A’.
2. The maximum length can be of 1 character.

Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and assign its
value. For example, const float pi= 3.14.
The constant keyword specifies the value of pi which cannot change.
However another way to designate a pre processor command defines with a preceded # symbol.
#define PI 3.141459
#define service tax 0.12
Ex:

#include
/* Calculating area and circumference of circle */

int main()
{
int rad; // variable
float PI = 3.14; // constant
float area, ci;

printf("\n Enter radius of circle: ");


scanf("%d", &rad);

area = PI * rad * rad;


printf("\nArea of circle : %f ", area);

Page 40 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science

ci = 2 * PI * rad;
printf("\nCircumference : %f ", ci);
return (0);
}

Explaining the program:

1. We have used /* */ these, which are used by the programmer to write comments. It is not
necessary to use it. But it helps the other person to understand the program more easily.
2. main( ) is a collective name given to a set of statements. This name has to be main( ), it
cannot be anything else. All statements that belong to main( ) are enclosed within a pair of
braces { }. And main is a function about which will study later.
3. Any variable used must be declared before ie float pi=3.14.
4. ';' it is used to terminate the statement.
5. printf is used to display the calculated area and circumference. It is a library function. The
general form for printf() is, printf("", ); .
6. Format string can contain %d for containing integer values, %f for containing real values, %c
for containing characters.
7. printf can also be used to print results of an expression ie a combination of constants,
variables and operators. < br> Ex: 3, 5+y-c, a+b-c*d which would be, printf(“d,”3, 5+y-c, a+b-
c*d);

The Decision Control Structure

In previous chapter we read about how statements are executed sequentially. In this chapter we will
study about how one can use a set of instructions for one situation and the other set for a more
general situation. This can be done by decision control structure in which can be implemented in C
using:

1. The if statement
2. The if-else statement
3. The conditional operators

The if statement

General form of if statement:

If (this condition is true)


execute this statement;

Whatever follows if statement tells the compiler that it is a decision control instruction. The condition
in if is always enclosed in parentheses and if true the statement is executed and if not it is skipped.

Page 41 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
The user can create decisions using relational operators using the relational operators we can
compare two values, equate them, use greater or lesser than etc here is a list.

NOTE: = and == are two different operators. = is used as an assignment operator whereas ==
is a relational operator ie it is used for comparison.

/*Example of if statement*/
main()
{
int num;
printf(“Enter any number less than 100”);
scanf(“%d”, &num);
if(num<100);
printf(“You are my servant HAHAHA”);
}

Let’s explain the program a little bit to you. In the above program the statement you are my servant
HAHAHA gets executed only if you enter a number less than 100 if you don’t the execution the
statement doesn’t take place and the program stops there and then only.
The if statement can also have arithmetic statements ie,

1. If (a=10)
printf(“I told you that it will work”);
2. If (-5)
printf(“even this works”);

NOTE: Only non-zero constants can be used in the if condition.

We can write multiple statements in if statement using the following method.

/*calculation of discount*/
main()
{
int qty, dis = 0 ;
float rate, tot ;
printf ( "Enter quantity and rate " ) ;
scanf ( "%d %f", &qty, &rate) ;

Page 42 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
if ( qty > 1000 )
{
dis = 10 ;
printf(“discount = %d”, dis);
}
}

The statements that are to be executed are placed in between the parentheses if this is not done
then the exact statement after the if is executed on satisfaction this means that the default scope
of if is the statement right after it.

The if-else statement

The if statement alone is not enough what if we want to execute a different set of statements that
doesn’t satisfy the if condition for this we use the if-elsestatement.

Example: To calculate the raise in salary of an employee by looking at his/her year of joining, year of
service.

/*calculation of raise in salary*/


main()
{
int yoj,cy,yos,raise,cs;
float ns;
printf(“Enter year of joining and current year”);
scanf(“%d %d”, &yoj, &cy)
yos = cy – yoj;
printf(“Enter current salary”);
scanf(“%d”, &cs);
if(yos>5)
{
raise = 27%
printf(“Raise=%d”, raise);
}
else
{
raise = 15%
printf(“Raise=%d”, raise);

Page 43 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
}
ns = cs + cs*raise/100;
printf(“New salary = %f”, ns);
}

As you can see in the above program we have used if-else statement to calculate the new salary of
an employee. If the condition comes out to be false then the else condition is executed.
NOTE

1. The statements upto the if not including else form the ‘if block’ similarly , ‘else block’ is
formed.
2. else is written exactly below if and the statements succeeding are intended towards right to
make the program understandable.
3. If we want to execute only one statement then pair of parenthesis could have been dropped.
To override the default scope one uses a pair of parentheses

The Nested if-elses

We can also write an if-else statement within an if block or an else block, this is called nesting of ifs.
Example:

main()
{
int x;
printf(“Enter any number less than 10”);
scanf(“%d”, &x);
if(x==5)
printf(“you entered the highest factor of 10”);
else
{
If(x==2)
printf(“you entered the smallest factor of10);
else
printf(“you are an idiot”);
}
}

Page 44 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
As you can see in this program, if the first statement inif is false then the compiler checks for
the if statement in the else block if even this fails then the compiler goes to the else statement and
executes it. Here, it is only an example you can build if statement within if block too.

This is how nesting of if-elses takes place.

Different Forms of if

1. if ( condition )
2. do this ;

3. if ( condition )
4. {
5. do this ;
6. and this ;
7. }

8. if ( condition )
9. do this ;
10. else
11. do this ;

12. if ( condition )
13. {
14. do this ;
15. and this ;
16. }
17. else
18. {
19. do this ;
20. and this ;
21. }

22. if ( condition )
23. do this ;
24. else
25. {
26. if ( condition )
27. do this ;
28. else
29. {
30. do this ;

Page 45 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
31. and this ;
32. }
33. }

34. if ( condition )
35. {
36. if ( condition )
37. do this ;
38. else
39. {
40. do this ;
41. and this ;
42. }
43. }
44. else
45. do this ;

Use of Logical Operators

C allows its users to use three logical operators namely &&, ||, ! these are AND, OR and NOT
operators respectively.

Remember AND(&&) , OR(||) we can’t use &,| they have different meaning, you have to always
use them in pair.

AND(&&) and OR(||) operators help the user to combine two conditions within an if statement.
Let’s understand this with the help of an example.
In this example we will give students cash prize by calculating their overall percentage in 5 subjects.

/*Giving cash prize according to their percentage*/

main()
{
int s1,s2,s3,s4,s5,cash_prize;
float per;
printf(“enter marks in 5 subjects”);
scanf(“%d %d %d %d %d %d”, &s1, &s2, &s3, &s4, &s5);
per= (s1+s2+s3+s4+s5)/5;
if(per>=85)
{
cash_prize=3500;

Page 46 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
printf(“Cash prize given =%d”, &cash_prize);
}
if((per>=70) && (per<85))
{
cash_prize=3000;
printf(“Cash prize given =%d”, &cash_prize);
}
if((per>=60) && (per<70))
{
cash_prize=2000;
printf(“Cash prize given =%d”, &cash_prize);
}
else
printf(“You are not given any cash prize”);
}

As you can see in the above program we have used AND operator to combine to conditions and if
they come out to be true then printf is executed accordingly.

There are some advantages of using this, which are:

1. The program doesn’t go on intending towards right.


2. Mismatching of if-else doesn’t occur.

We can write the same program using the else if block ie,
if(per>=85)
{
cash_prize=3500;
printf(“Cash prize given =%d”, &cash_prize);
}
else if(per>=70)
{
cash_prize=3000;
printf(“Cash prize given =%d”, &cash_prize);
}

Page 47 of 48
[Link]’s University
Faculty of Informatics
Department of Computer Science
else if(per>=60)
{
cash_prize=2000;
printf(“Cash prize given =%d”, &cash_prize);
}
else
printf(“You are not given any cash prize”);

As you can see in this program the indentation reduces and every else is associated with its
previous of.

Now we shall discuss the NOT(!) operator. When we use the ! operator it reverses the meaning of
the statement ie it will turn non-zero value to zero value and vice-versa. Ex: !(y>10), this means that
we can use any value of y for which it is less than 10 or in other words not y greater than 10.

The Conditional Operators


‘?’ and ‘:’ these are known as conditional operators or as ternary operators as they take three
arguments. These can be used in place of if-else in some cases.
Their general form is:
Expression1? Expression2 : Expression3

Which means that if expression1 is true then the value returned will be expression2 and if false it will
return expression3, by true or false it means that the value should be non-zero or zero respectively.
Example:

int f,g;
printf(“Enter value of f”);
scanf(“%d”, &f);
g = (f>6 ? 5 : 0);

If the entered value is more than 6 then 5 will be stored in g else 0 will be stored in it.

The GOTO Statement

The goto statement is used to transfer control to a specified label . However, the label must reside in
the same function and can appear only before one statement in the same function. Syntax as
follows-

Page 48 of 48

You might also like