Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
65 views

Computer Programming Book

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

Computer Programming Book

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

Faculty of Engineering Assiut

University
Electrical Engineering Department

Computers and Programming

For
Preparatory Year

Prof. Dr. Omar Abdelgaber


Dr. Mostafa Abdo

1
CONTENTS
CHAPTER 1: INTRODUCTION TO COMPUTER 2

CHAPTER 2: THE COMPUTER SYSTEM HARDWARE 10

CHAPTER 3: DATA REPRESENTATION 23

CHAPTER 4: COMPUTER SOFTWARE 48


CHAPTER 5: COMPUTER PROGRAMMING 58
FUNDAMENTALS

CHAPTER 6: BASICS OF C++ 73

CHAPTER 7: CONTROL STRUCTURES 99

CHAPTER 8: FUNCTIUONS 114

CHAPTER 9: ARRAYS 126

2
CHAPTER 1

INTRODUCTION TO COMPUTER

CHAPTER 1: INTRODUCTION TO COMPUTER

3
Computers are an integral part of our lives. Wherever we are—sitting in our homes,
working in the office, driving on roads, sitting in a movie hall, staying in a hotel, etc.—
our lives are directly or indirectly affected by the computers. In this era of information,
we are dependent on the storage, flow and processing of data and information, which can
only be possible with the help of computers. The purpose of this chapter is to introduce
you to the “computer”.

1.1 INTRODUCTION

A computer is an electronic machine that accepts data from the user, processes the data
by performing calculations and operations on it, and generates the desired output results.
Computer performs both simple and complex operations, with speed and accuracy.

1.2 CHARACTERISTICS OF COMPUTER

Speed, accuracy, diligence, storage capability and versatility are some of the key
characteristics of a computer. A brief overview of these characteristics are:

• Speed The computer can process data very fast, at the rate of millions of
instructions per second.
• Accuracy Computer provides a high degree of accuracy.
• Diligence When used for a longer period of time, the computer does not get tired
or fatigued.
• Storage Capability Large volumes of data and information can be stored in the
computer and also retrieved whenever required.
• Versatility Computer is versatile in nature. It can perform different types of tasks
with the same ease.

Computers have several limitations too. Computer can only perform tasks that it has been
programmed to do. Computer cannot do any work without instructions from the user. It
executes instructions as specified by the user and does not take its own decisions.

1.3 GENERATIONS OF COMPUTER

The computer has evolved from a large—sized simple calculating machine to a smaller
but much more powerful machine. The evolution of computer to the current state is
defined in terms of the generations of computer. In the following subsections, we will
discuss the generations of computer.

1.3.1 First Generation (1940 to 1956): Using Vacuum Tubes

4
• Hardware Technology The first generation of computers used vacuum tubes for
circuitry and magnetic drums for memory. The input to the computer was through
punched cards and paper tapes. The output was displayed as printouts.
• Software Technology The instructions were written in machine language.
Machine language uses 0s and 1s for coding of the instructions. The first
generation computers could solve one problem at a time.
• Computing Characteristics The computation time was in milliseconds.
• Application They were used for scientific applications as they were the fastest
computing device of their time.
• Examples UNIVersal Automatic Computer (UNIVAC), Electronic Numerical
Integrator And Calculator (ENIAC), and Electronic Discrete Variable Automatic
Computer (EDVAC).

1.3.2 Second Generation (1956 to 1963): Using Transistors

• Hardware Technology Transistors replaced the vacuum tubes of the first


generation of computers. Transistors allowed computers to become smaller,
faster, cheaper, energy efficient and reliable. The second generation computers
used magnetic core technology for primary memory. They used magnetic tapes
and magnetic disks for secondary storage. The input was still through punched
cards and the output using printouts.
• Software Technology The instructions were written using the assembly language.
Assembly language is easier to write instructions compared to machine language.
High-level programming languages, such as early versions of COBOL and
FORTRAN were also developed during this period.
• Computing Characteristics The computation time was in microseconds.
• Examples PDP-8, IBM 1401 and CDC 1604.

1.3.3 Third Generation (1964 to 1971): Using Integrated Circuits

• Hardware Technology The third generation computers used the Integrated Circuit
(IC) chips. The use of IC chip increased the speed and the efficiency of computer,
manifold. The keyboard and monitor were used to interact with the third
generation computer, instead of the punched card and printouts.
• Software Technology The keyboard and the monitor were interfaced through the
operating system. Operating system allowed different applications to run at the
same time. High-level languages were used extensively for programming, instead
of machine language and assembly language.
• Computing Characteristics The computation time was in nanoseconds.
• Examples IBM 370, PDP 11.

5
1.3.4 Fourth Generation (1971 to present): Using Microprocessors

• Hardware Technology They use the Large Scale Integration (LSI) and the Very
Large Scale Integration (VLSI) technology. Microprocessor is a chip containing
millions of transistors and components. Semiconductor memory replaced the
earlier magnetic core memory, resulting in fast memory. Secondary storage
device like magnetic disks became smaller in physical size. The computers were
linked to form networks that led to the emergence of the Internet. This generation
also saw the development of pointing devices like mouse, and handheld devices.
and larger in capacity.
• Software Technology Several new operating systems like the MS-DOS and
MSWindows developed during this time. This generation of computers supported
Graphical User Interface (GUI). GUI is a user-friendly interface that allows user
to interact with the computer via menus and icons. High-level programming
languages are used for the writing of programs.
• Computing Characteristics The computation time is in picoseconds.
• Examples The Intel 4004 chip was the first microprocessor.

1.3.5 Fifth Generation (Present and Next): Using Artificial Intelligence

The goal of fifth generation computing is to develop computers that are capable of
learning and self-organization. The fifth generation computers use Super Large Scale
Integrated (SLSI) chips that are able to store millions of components on a single chip.
These computers have large memory requirements.

This generation of computers uses parallel processing that allows several instructions to
be executed in parallel. Parallel processing results in faster processing speed.

The fifth generation computers are based on Artificial Intelligence (AI). They try to
simulate the human way of thinking and reasoning. Artificial Intelligence includes areas
like Expert System (ES), Natural Language Processing (NLP), speech recognition, voice
recognition, robotics, etc.

1.4 CLASSIFICATION OF COMPUTER

The computers are broadly classified into four categories (Figure 1.1) based on their size
and type—(1) Microcomputers, (2) Minicomputers, (3) Mainframe computers, and (4)
Supercomputer.

6
Figure 1.1 Classification of computers based on size and type

1.4.1 Microcomputers
Microcomputers are small, low-cost and single-user digital computer. They can be
connected together to create a network of computers that can serve more than one user.
Microcomputers include desktop computers, notebook computers or laptop, tablet
computer, handheld computer, smart phones and netbook.

1.4.2 Minicomputers
Minicomputers are digital computers, generally used in multi-user systems. They have
high processing speed and high storage capacity than the microcomputers.
Minicomputers can support 4–200 users simultaneously. The users can access the
minicomputer through their PCs or terminal. They are used for real-time applications in
industries, research centers.

1.4.3 Mainframe Computers


Mainframe computers are multi-user, multi-programming and high performance
computers. They operate at a very high speed, have very large storage capacity and can
handle the workload of many users. The user accesses the mainframe computer via a
terminal. Mainframe computers are used in organizations like banks or companies.

1.4.4 Supercomputers
Supercomputers are the fastest and the most expensive machines. The speed of a
supercomputer is generally measured in FLOPS (FLoating point Operations Per Second).
Some of the faster supercomputers can perform trillions of calculations per second.
Supercomputers are built by interconnecting thousands of processors that can work in
parallel.
Supercomputers are used for highly calculation-intensive tasks, such as, weather
forecasting, climate research (global warming), molecular research, biological research,
nuclear research and aircraft design. They are also used in major universities, military
agencies and scientific research laboratories.

7
1.5 THE COMPUTER SYSTEM
Computer is an electronic device that accepts data as input, processes the input data by
performing mathematical and logical operations on it, and gives the desired output. The
computer system consists of four parts•(1) Hardware, (2) Software, (3) Data, and (4)
Users.
• Hardware Consists of physical devices of the computer. The devices are required
for input (Keyboard), output (monitor), storage (hard disk drive, floppy disk drive
and printer), processor and motherboard are some of the hardware devices.
• Software is a set of instructions, written in a language understood by the
computer, that tells the computer about the tasks to be performed and how these
tasks are to be performed.
• Data is provided as input to the computer, which is processed to generate some
meaningful information.
• Users are people who write computer programs or interact with the computer.
They are also known as skinware, liveware, humanware or peopleware.
Programmers, data entry operators, system analyst and computer hardware
engineers fall into this category.

1.5.1 The Input-Process-Output Concept

A computer is an electronic device that (1) accepts data, (2) processes data, (3) generates
output, and (4) stores data. The concept of generating output information from the input 4
data is also referred to as input-process-output concept.

• Input The computer accepts input data from the user via an input device like
keyboard. The input data can be number, characters, word, text, sound, images,
document, etc.
• Process The computer processes the input data. For this, it performs some actions
on the data by using the instructions or program given by the user of the data. The
action could be an arithmetic or logic calculation, editing, modifying a document,
etc. During processing, the data, instructions and the output are stored temporarily
in the computer’s main memory.
• Output The output is the result generated after the processing of data. The output
may be in the form of text, sound, image, document, etc. The computer may
display the output on a monitor, send output to the printer for printing, play the
output, etc.
• Storage The input data, instructions and output are stored permanently in the
secondary storage devices like disk or tape. The stored data can be retrieved later,
whenever needed.

8
1.5.2 Components of Computer Hardware

The computer system hardware comprises of three main components —

a) Input/Output (I/O) Unit,


b) Central Processing Unit (CPU), and
c) Memory Unit.

Figure 1.2 illustrates the typical interaction among the different components of the
computer.

Figure 1.2 The computer system interaction

• Input/Output Unit The user interacts with the computer via the I/O unit. The
Input unit accepts data from the user and the Output unit provides the processed
data to the user. The Input unit converts the data that it accepts from the user, into
a form that is understandable by the computer. Similarly, the Output unit provides
the output in a form that is understandable by the user. Input devices like
keyboard and mouse. Output devices are monitor and printer.
• Central Processing Unit CPU is responsible for processing of the input data. CPU
consists of Arithmetic Logic Unit (ALU) and Control Unit (CU).
o ALU performs all the arithmetic and logic operations on the input data.
o CU controls the overall operations of the computer.

Additionally, CPU also has a set of registers for temporary storage of data,
instructions, addresses and intermediate results of calculation.

• Memory Unit Memory unit stores the data, instructions, intermediate results and
output, temporarily, during the processing of data. This memory is also called the
main memory or primary memory of the computer.

9
QUESTIONS
1. List the main characteristics of the computer.
2. Describe the characteristics of the computer.
3. List three significant limitations of the computer.
4. The first generation computers used_____for circuitry.
5. Describe the first generation computer based on the (a) Hardware (b) Software (c)
Computing characteristics (d) Physical appearance, and (e) Their applications.
6. The second generation computers used_____for circuitry.
7. Describe the second generation computer based on the (a) Hardware (b) Software (c)
Computing characteristics (d) Physical appearance and (e) Their applications.
8. The third generation computers used_____for circuitry.
9. Describe the third generation computer based on the (a) Hardware (b) Software (c)
Computing characteristics (d) Physical appearance, and (e) Their applications.
10. The fourth generation computers used_____for circuitry.
11. Describe the fourth generation computer based on the (a) Hardware (b) Software (c)
Computing characteristics (d) Physical appearance and (e) Their applications.
12. The fifth generation computers used_____for circuitry.
13. Describe the fifth generation computer based on the (a) Hardware (b) Software (c)
Computing characteristics (d) Physical appearance and (e) Their applications.
14. Define microcomputer.
15. Define minicomputers.
16. Define mainframe computer.
17. Define a supercomputer.
18. The speed of supercomputer is generally measured in_____.
19. Define a computer.
20. Define (1) Program (2) Software (3) Hardware (4) ALU (5) CU (6) CPU (7) Data.
21. Differentiate between software, data and hardware.
22. List the components of computer hardware.
23. Explain in detail the components of computer hardware.
24. List the steps in the working of the computer.
25. Explain the working of the computer.
26. Explain the input-process-output cycle.

10
CHAPTER 2

THE COMPUTER SYSTEM


HARDWARE

11
CHAPTER 2: THE COMPUTER SYSTEM HARDWARE
The computer as a machine consists of different components that interact with each other
to provide the desired functionality of the computer. As a user of the computer, we need
to be aware of the main components of the computer, their functions, and the
interconnection between the different components of the computer.

2.1 INTRODUCTION

A computer consists of three main components—(1) Input/Output (I/O) Unit, (2) Central
Processing Unit (CPU), and (3) Memory Unit. This chapter discusses the hardware
components of the computer and the interaction between them.

2.2 CENTRAL PROCESSING UNIT

Central Processing Unit (CPU) or the processor is also often called the brain of computer.
CPU executes the stored program instructions, i.e. instructions and data are stored in
memory before execution. CPU gets data and instructions from the memory. It interprets
the program instructions and performs the arithmetic and logic operations required for the
processing of data. Then, it sends the processed data or result to the memory.

The CPU is fabricated as a single Integrated Circuit (IC) chip, and is also known as the
microprocessor. The microprocessor is plugged into the motherboard of the computer
(Motherboard is a circuit board that has electronic circuit etched on it and connects the
microprocessor with the other hardware components).

CPU consists of Arithmetic Logic Unit (ALU), Control Unit (CU) and a set of registers
which are temporary storage areas for holding data, and instructions as shown in Figure
2.1.

Figure 2.1 CPU

2.2.1 Arithmetic Logic Unit

ALU consists of two units—arithmetic unit and logic unit. The arithmetic unit performs
arithmetic operations on the data that is made available to it. Some of the arithmetic
operations supported by the arithmetic unit are—addition, subtraction, multiplication, and
division. The logic unit of ALU is responsible for performing logic operations. Logic unit
performs comparisons of numbers, letters, and special characters. Logic operations

12
include testing for greater than, less than or equal to condition. ALU performs arithmetic
and logic operations, and uses registers to hold the data that is being processed.

2.2.2 Registers

Registers are high-speed storage areas within the CPU, but have the least storage
capacity. Registers store data, instructions, and intermediate results of processing.
Registers are often referred to as the CPU’s working memory. Registers are used for
different purposes, with each register serving a specific purpose. The number of registers
and the size of each (number of bits) register in a CPU helps to determine the power and
the speed of a CPU. The size of register, also called word size, indicates the amount of
data with which the computer can work at any given time. The bigger the size, the more
quickly it can process data. The size of a register may be 8, 16, 32 or 64 bits. For
example, a 32–bit CPU is one in which each register is 32 bits wide and its CPU can
manipulate 32 bits of data at a time. Nowadays, PCs have 32–bit or 64–bit registers.

32-bit processor and 64-bit processor are the terms used to refer to the size of the
registers. Other factors remaining the same, a 64-bit processor can process the data twice
as fast as one with 32-bit processor.

2.2.3 Control Unit

The control unit of a computer does not do any actual processing of data. It organizes the
processing of data and instructions. It acts as a supervisor and, controls and coordinates
the activity of the other units of computer.

The function of a (CU) can be considered synonymous with that of a conductor of an


orchestra. The conductor in an orchestra does not perform any work by itself but manages
the orchestra and ensures that the members of orchestra work in proper coordination.

2.3 MEMORY UNIT

The memory unit consists of cache memory and primary memory. Primary memory or
main memory of the computer is used to store the data and instructions during execution
of the instructions. Random Access Memory (RAM) and Read Only Memory (ROM) are
the primary memory. In addition to the main memory, there is another kind of storage
device known as the secondary memory. Secondary memory is non-volatile and is used
for permanent storage of data and programs. A program or data that has to be executed is
brought into the RAM from the secondary memory.

2.3.1 Cache Memory

Cache memory is a very high speed memory placed in between RAM and CPU. Cache
memory increases the speed of processing. To access the cache memory, CPU does not

13
have to use the motherboard’s system bus for data transfer. (The data transfer speed
slows to the motherboard’s capability, when data is passed through system bus. CPU can
process data at a much faster rate by avoiding the system bus.). Cache memory is built
into the processor, and may also be located next to it on a separate chip between the CPU
and RAM. Cache built into the CPU is faster than separate cache, running at the speed of
the microprocessor itself. However, separate cache is roughly twice as fast as RAM. The
CPU has a built-in Level 1 (L1) cache and Level2 (L2) cache, as shown in Figure 2.2. In
addition to the built-in L1 and L2 cache, some CPUs have a separate cache chip on the
motherboard. This cache on the motherboard is called Level 3 (L3) cache. Nowadays,
high-end processor comes with built-in L3 cache, like in Intel core i7. The L1, L2 and L3
cache store the most recently run instructions, the next ones and the possible ones,
respectively. Typically, CPUs have cache size varying from 256KB (L1), 6 MB (L2), to
12MB (L3) cache.

Figure 2.2 Illustration of cache memory

Cache memory is very expensive, so it is smaller in size. Generally, computers have


cache memory of sizes 256 KB to 2 MB.

2.3.2 Primary Memory

Primary memory is the main memory of computer. It is used to store data and instructions
during the processing of data. Primary memory is semiconductor memory. Primary
memory is of two kinds—Random Access Memory (RAM) and Read Only Memory
(ROM). RAM is volatile. It stores data when the computer is on. The information stored
in RAM gets erased when the computer is turned off. RAM provides temporary storage
for data and instructions. ROM is non-volatile memory, but is a read only memory. The
storage in ROM is permanent in nature, and is used for storing standard processing
programs that permanently reside in the computer. ROM comes programmed by the
manufacturer. RAM stores data and instructions during the execution of instructions. The
data and instructions that require processing are brought into the RAM from the storage
devices like hard disk. CPU accesses the data and the instructions from RAM, as it can
access it at a fast speed than the storage devices connected to the input and output unit.
RAM provides a limited storage capacity, due to its high cost.

14
2.3.2.1 Memory capacity (size)

Bits are the building blocks of digital memory. Of course, a single bit (0 or 1) is not very
useful for storing information. Memory capacity is usually specified in bytes (1 byte = 8
bits). A group of bytes can be further combined to form a word. A word can be a group of
2, 4 or 8 bytes. Memory size can be identified using: a kilobyte (KB = 210 bytes), a
megabyte (MB = 210 KB ), a gigabyte (GB = 210 MB ), and a terabyte (TB = 210 GB ).
Byte represents a character. A megabyte is capable of storing more than one million
characters of text (e.g., a book).

2.3.3 Secondary Memory

The secondary memory stores data and instructions permanently. The information can be
stored in secondary memory for a long time (years), and is generally permanent in nature
unless erased by the user. It is a non-volatile memory. It provides back-up storage for
data and instructions. Hard disk drive, floppy drive and optical disk drives are some
examples of storage devices. Secondary memory has a high storage capacity than the
primary memory. Secondary memory is also cheaper than the primary memory. It takes
longer time to access the data and instructions stored in secondary memory than in
primary memory.

2.3.3.1 Magnetic Hard disk (HDD)

Metal platter coated with a magnetic medium that stores bits as magnetized and non-
magnetized spots. Disk rotates under a sensor, which detects the magnetized spots. Its
capacity usually measured in GB and TB.

2.3.3.2 Solid-state drive (SSD)

A solid-state drive (SSD) is a solid-state storage device that uses integrated circuit
assemblies to store data persistently, typically using flash memory, and functioning as
secondary storage in the hierarchy of computer storage. SSDs are typically more resistant
to physical shock, run silently, and have quicker access time. SSDs store data in
semiconductor cells.

2.3.3.3 Optical disk technologies (CD or DVD)

In optical disk data is written and read by leaser beams not affected by magnetic fields.
Its slower than HDD. It includes different types such as, CD or CD-ROM (Compact
Disk–Read Only Memory) has a storage capacity 700 MB. Another type of optical disk is
DVD "Digital Versatile Disk”, it transfer the data from the disk to the computer far faster
than CD. It has a storage capacity range from 4.7 GB to 17 GB.

15
2.3.3.4 Flash memory

Flash memory is non-volatile computer storage chip that can be electrically erased with
(USB) interface. Its removable, rewritable, much smaller, and less weight (light). Its size
can reach TB size. Its durable because they don’t contain internal moving parts. It has
high-speed, and low-energy consumption. Its used in devices such as digital camera,
mobile phone, printer, and laptop computer.

2.4 INSTRUCTION CYCLE

A computer program is a set of instructions that describe the steps to be performed for
carrying out a computational task. The program and the data, on which the program
operates, are stored in main memory, waiting to be processed by the processor.

An Instruction Set is the set of all the basic operations that a processor can accomplish.
All programs written in a high-level language are compiled and translated into machine
code before execution, which is understood by the processor for which the program has
been coded.

The primary responsibility of a computer processor is to execute a sequential set of


instructions that constitute a program. CPU executes each instruction in a series of steps,
called instruction cycle. A instruction cycle involves four steps.

• Fetching The processor fetches the instruction from the memory. The fetched
instruction is placed in the Instruction Register. Program Counter holds the
address of next instruction to be fetched and is incremented after each fetch.
• Decoding The instruction that is fetched is broken down into parts or decoded.
The instruction is translated into commands so that they correspond to those in the
CPU’s instruction set. The instruction set architecture of the CPU defines the way
in which an instruction is decoded.
• Executing The decoded instruction or the command is executed. CPU performs
the operation implied by the program instruction. For example, if it is an ADD
instruction, addition is performed.
• Storing CPU writes back the results of execution, to the computer’s memory.

2.5 INTERCONNECTING THE UNITS OF A COMPUTER

The different components of computer, i.e., CPU, I/O unit, and memory unit are
connected with each other by a bus. Bus is a set of electronic signal pathways that allows
information and signals to travel between components inside or outside of a computer.
The features and functionality of a bus are as follows

• A bus is a set of wires used for interconnection, where each wire can carry one bit
of data.

16
• A bus width is defined by the number of wires in the bus.
• A computer bus can be divided into two types—Internal Bus and External Bus.
• The Internal Bus connects components inside the motherboard like, CPU and
system memory. It is also called the System Bus. Figure 2.3 shows interaction
between processor and memory.

Figure 2.3 Interaction between CPU and memory

• The External Bus connects the different external devices, peripherals, expansion
slots, I/O ports and drive connections to the rest of computer. The external bus
allows various devices to be attached to the computer. It allows for the expansion
of computer’s capabilities. It is generally slower than the system bus. It is also
referred to as the Expansion Bus.
• A system bus or expansion bus comprise of three kinds of buses — data bus,
address bus and control bus.
• The interaction of CPU with memory and I/O devices involves all the three buses.
o The command to access the memory or the I/O device is carried by the
control bus.
o The address of I/O device or memory is carried by the address bus.
o The data to be transferred is carried by the data bus.

Figure 2.4 shows interaction between processor, memory and the peripheral devices.

Figure 2.4 Interaction between CPU, memory and peripheral devices

2.6 PERFORMANCE OF A COMPUTER

17
There are a number of factors involved that are related to the CPU and have an effect on
the overall speed and performance of the computer. Some of the factors that affect the
performance of the computer include:

• Registers The size of the register (word size) indicates the amount of data with
which the computer can work at any given time. The bigger the size, the more
quickly it can process data. A 32–bit CPU is one in which each register is 32 bits
wide.
• RAM It is used to store data and instructions during execution of the instructions.
Anything you do on your computer requires RAM. When the computer is
switched on, the operating system, device drivers, the active files and running
programs are loaded into RAM. If RAM is less, then the CPU waits each time the
new information is swapped into memory from the slower devices. Larger the
RAM size, the better it is. PCs nowadays usually have 1 GB to 8 GB of RAM.
• System Clock The clock speed of a CPU is defined as the frequency with which a
processor executes instructions or the data is processed. Higher clock frequencies
mean more clock ticks per second. The computer’s operating speed is linked to
the speed of the system clock. The clock frequency is measured in millions of
cycles per second or megahertz (MHz) or gigahertz (GHz) which is billions of
cycles per second. PCs nowadays come with a clock speed of more than 2.4 GHz.
In Windows OS, you can select the System Information dialog box to see the
processor name and clock frequency, as shown in figure 2.5.
• Bus Data The bus speed is measured in MHz. Higher the bus speed the better it is.
Address bus connects CPU and RAM with a set of wires similar to data bus. The
address bus width determines the maximum number of memory locations the
computer can address.
• Cache Memory Two of the main factors that affect a cache’s performance are its
size (amount of cache memory) and level L1, L2 and L3. Larger the size of cache,
the better it is. PCs nowadays have a L1 cache of 256KB and L2 cache of 1MB.

18
Figure 2.13 System properties in Windows 10.

2.7 INSIDE A COMPUTER CABINET

The computer cabinet encloses the components that are required for the running of the
computer. The components inside a computer cabinet include the power supply,
motherboard, memory chips, expansion slots, ports and interface, processor, cables and
storage devices.

2.7.1 Motherboard

The motherboard is the most important component in the PC. It is a large Printed Circuit
Board (PCB), having many chips, connectors and other electronics mounted on it. The
RAM, hard drive, disk drives and optical drives are all plugged into interfaces on the
motherboard. The motherboard contains the processor, memory chips, interfaces and
sockets, etc. The motherboard may be characterized by the form factor, chipset and type
of processor socket used. Advanced Technology Extended (ATX) is the most common
form factor design of motherboard for desktop computers. Chipset is a circuit, which
controls the majority of resources. It is important to choose a motherboard, which
includes a recent chipset, in order to maximize the computer’s upgradeability. The Basic
Input Output System (BIOS) and Complementary Metal-Oxide Semiconductor (CMOS)
are present on the motherboard.

• BIOS It is the basic program used as an interface between the operating system
and the motherboard. BIOS contain the instructions for the starting up of the
computer. It performs a Power On Self Test (POST) that checks that the hardware
is functioning properly and the hardware devices are present. It checks whether

19
the operating system is present on the hard drive. BIOS can be configured using
an interface named. BIOS setup, which can be accessed when the computer is
booting up (by pressing the DEL key).
• CMOS Chip BIOS ROMs are accompanied by a smaller CMOS (CMOS is a type
of memory technology) memory chip. This is because the CMOS chip saves some
system information, such as time, system date and essential system settings.
CMOS is kept powered by a button battery located on the motherboard.

2.7.2 Ports and Interfaces

Motherboard has a certain number of I/O sockets that are connected to the ports and
interfaces found on the rear side of a computer. You can connect external devices to the
ports and interfaces, which get connected to the computer’s motherboard.

• Serial Port— to connect old peripherals.


• Parallel Port— to connect old printers.
• USB Ports—to connect newer peripherals like cameras, scanners and printers to
the computer. It uses a thin wire to connect to the devices, and many devices can
share that wire simultaneously.
• RJ45 connector (called LAN or Ethernet port) is used to connect the computer to
a network. It corresponds to a network card integrated into the motherboard.
• VGA connector for connecting a monitor. This connector interfaces with the built-
in graphics card.
• Audio plugs (line-in, line-out and microphone), for connecting sound speakers
and the microphone. This connector interfaces with the built-in sound card.
• PS/2 port to connect mouse and keyboard into PC.
• SCSI port for connecting the hard disk drives and network connectors.

2.7.3 Expansion Slots

The expansion slots are located on the motherboard. The expansion cards are inserted in
the expansion slots. These cards give the computer new features or increased
performance. There are several types of slots.

20
QUESTIONS
1. CPU is also often called the_____of computer.

2. Define a microprocessor.

3. Define a motherboard.

4. The different parts of the CPU are_____, _____ and _____.

5. _____ and _____ are the main memory.

6. What is the purpose of the main memory?

7. List the main functions of the CPU.

8. ALU consists of the _____ unit and _____ unit.

9. What are the functions of the ALU?

10. _____ is also called the working memory of the CPU.

11. Why are Registers used in the CPU?

12. Define word size.

13. “This is a 64–bit processor”. Explain its meaning.

14. The size of the register is also the _____ size.

15. Which is faster—a 32-bit processor or a 64-bit- processor?

16. What are the functions of the control unit?

17. Explain the need of the cache memory?

18. The _____ memory is placed between the RAM and the CPU.

19. There are _____ levels of cache memory.

20. State three important features of the cache memory.

21. The size of the cache memory is generally in the range _____.

22. What is the purpose of RAM?

23. List the features of the primary memory.

24. List the key features of the secondary memory.

21
25. Define the stored program concept.

26. Define an Instruction set.

27. What is the significance of the Instruction set in the CPU?

28. Define an instruction cycle.

29. Give a detailed working of the instruction cycle.

30. Name the four steps involved in an instruction cycle.

31. The number of instructions executed in a second by the CPU, is measured in _____.

32. The microprocessors are classified as _____ and _____ on the basis of the instruction
set.

33. Define a bus.

34. Define a system bus.

35. Define an expansion bus.

36. Why is a bus used?

37. Define—control bus, address bus and data bus.

38. A system bus or expansion bus comprises of three kinds of buses _____, _____ and
_____.

39. The _____ of data bus affects the speed of computer.

40. Name the bus whose width affects the speed of computer?

41. The _____ of address bus determines the maximum number of memory locations the
computer can address.

42. Name the bus whose width determines the maximum number of memory locations
the computer can address?

43. What are the functions of data bus, address bus and control bus in the expansion bus?

43. Where is the expansion card fixed on the motherboard?

44. What is an expansion slot?

45. List the factors that affect the performance of the computer.

46. Explain in detail the factors that affect the performance of the computer.

22
47. What is the use of the system clock?

48. The clock frequency is measured in _____.

49. “The motherboard is characterized by the form factor, chipset and the type of
processor socket used”. Explain.

50. Define form factor.

51. Define chipset.

52. _____ is the most common design of the motherboard for desktop computers.

53. What is the significance of the chipset?

54. What is the function of the BIOS?

55. What is the function of the CMOS chip?

56. Explain the booting process when the computer is switched on.

57. What is POST?

58 . List five ports and interfaces available on the backside of the computer to connect the
devices.

59. What devices are attached to—(a) Serial Port, (b) Parallel Port, (c) USB Port, (d)
RJ45 connector, (e) VGA connector, (f) Audio plugs (Line-In, Line-Out and
microphone), (g) PS/2 Port, and (h) SCSI Port.

60. List five expansion slots available in the computer.

61. What devices are attached to—(a) ISA slots, (b) PCI slot, (c) AGP slot, (d) PCI
Express slot, and (e) PC Card.

23
CHAPTER 3

DATA REPRESENTATION

24
CHAPTER 3: DATA REPRESENTATION
We use computer to process the data and get the desired output. The data input can be in
the form of alphabets, digits, symbols, audio, video, magnetic cards, finger prints, etc.
Since computer can only understand 0 and 1, the data must be represented in the
computer in 0s and 1s. The purpose of this chapter is to introduce you to the data
representation in the computer.

3.1 INTRODUCTION

The data stored in the computer may be of different kinds, as follows

• Numeric data (0, 1, 2, …, 9)


• Alphabetic data (A, B, C, …, Z)
• Alphanumeric data—Combination of any of the symbols—(A, B, C… Z), (0, 1…
9), or special characters (+,−, Blank), etc.

All kinds of data is represented in terms of 0s and 1s, in the computer. Each symbol is
represented as a unique combination of 0s and 1s.

3.2 NUMBER SYSTEM

A number system in base r or radix r uses unique symbols for r digits. One or more digits
are combined to get a number. The base of the number decides the valid digits that are
used to make a number. In a number, the position of digit starts from the right-hand side
of the number. The rightmost digit has position 0, the next digit on its left has position 1,
and so on. The digits of a number have two kinds of values:

• Face value, face value of a digit is the digit located at that position. For example,
in decimal number 52, face value at position 0 is 2 and face value at position 1 is
5.
• Position value, The position value of a digit is (baseposition). For example, in
decimal number 52, the position value of digit 2 is 100 and the position value of
digit 5 is 101. Decimal numbers have a base of 10.

The number is calculated as the sum of, face value * baseposition, of each of the digits. For
decimal number 52, the number is 5*101 + 2*100 = 50 + 2 = 52.

In computers, we are concerned with four kinds of number systems, as follows:

• Decimal Number System —Base 10


• Binary Number System —Base 2
• Octal Number System —Base 8
• Hexadecimal Number System—Base 16

25
The numbers given as input to computer and the numbers given as output from the
computer, are generally in decimal number system, and are most easily understood by
humans. However, computer understands the binary number system, i.e., numbers in
terms of 0s and 1s. The binary data is also represented, internally, as octal numbers and
hexadecimal numbers due to their ease of use.

A number in a particular base is written as (number)base of number For example, (23)10 means
that the number 23 is a decimal number, and (345)8 shows that 345 is an octal number.

3.2.1 Decimal Number System

It consists of 10 digits—0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. The position value and quantity of a


digit at different positions in a number are as follows:

Position 3 2 1 0 . -1 -2 -3
Position value 103 102 101 100 10-1 10-2 10-3
Quantity 1000 100 10 1 1/10 1/100 1/1000

3.2.2 Binary Number System

The binary number system consists of two digits—0 and 1. The position value and
quantity of a digit at different positions in a number are as follows:

Position 3 2 1 0 . -1 -2 -3
Position value 23 22 21 20 2-1 2-2 2-3
Quantity 8 4 2 1 1/2 1/4 1/8

3.2.3 Octal Number System

The octal number system consists of eight digits—0 to 7. The position value and quantity
of a digit at different positions in a number are as follows:

Position 3 2 1 0 . -1 -2 -3
Position value 83 82 81 80 8-1 8-2 8-3
Quantity 512 64 8 1 1/8 1/64 1/512

3.2.4 Hexadecimal Number System

The hexadecimal number system consists of sixteen digits—0 to 9, A, B, C, D, E, F,


where (A is for 10, B is for 11, C-12, D-13, E-14, F-15). The position value and quantity
of a digit at different positions in a number are as follows:

26
Position 3 2 1 0 . -1 -2 -3
Position value 163 162 161 160 16-1 16-2 16-3
Quantity 4096 256 16 1 1/16 1/256 1/4096

Table 3.1 summarizes the base, digits and largest digit for the above discussed number
systems. Table 3.2 shows the binary, octal and hexadecimal equivalents of the decimal
numbers 0–16.

Table 3.1 Summary of number system

Table 3.2 Decimal, binary, octal and hexadecimal equivalents

3.3 CONVERSION FROM DECIMAL TO BINARY, OCTAL, HEXADECIMAL

A decimal number has two parts—integer part and fraction part. For example, in the
decimal number 23.0786, 23 is the integer part and .0786 is the fraction part. The method
used for the conversion of the integer part of a decimal number is different from the one
used for the fraction part. In the following subsections, we shall discuss the conversion of

27
decimal integer, decimal fraction and decimal integer.fraction number into binary, octal
and hexadecimal number.

3.3.1 Converting Decimal Integer to Binary, Octal, Hexadecimal

A decimal integer is converted to any other base, by using the division operation. To
convert a decimal integer to—

• binary-divide by 2,
• octal-divide by 8, and,
• hexadecimal-divide by 16.

Let us now understand this conversion with the help of some examples.

Example 3.1: Convert (25)10 from Base 10 to Base 2.

1. Make a table as shown below. Write the number in center and toBase on the left
side.
2. Divide the number with toBase. After each division, write the remainder on right-
side column and quotient in the next line in the middle column. Continue dividing
till the quotient is 0.
3. Write the digits in remainder column starting from downwards to upwards,

To Base Number (Quotient) Reminder


2 25
2 12 1
2 6 0
2 3 0
2 1 1
0 1
The binary equivalent of number (25)10 is (11001)2. The steps shown above are followed
to convert a decimal integer to a number in any other base.

Example 3.2: Convert 23 from Base 10 to Base 2, 8, 16.

28
Example 3.3: Convert 147 from Base 10 to Base 2, 8 and 16.

Example 3.4: Convert 94 from Base 10 to Base 2, 8 and 16.

3.3.2 Converting Decimal Fraction to Binary, Octal, Hexadecimal

A fractional number is a number less than 1. It may be .5, .00453, .564, etc. We use the
multiplication operation to convert decimal fraction to any other base. To convert a
decimal fraction to—

• binary-multiply by 2,
• octal-multiply by 8, and,
• hexadecimal-multiply by 16.

Steps for conversion of a decimal fraction to any other base are—

29
1. Multiply the fractional number with the to Base, to get a resulting number.
2. The resulting number has two parts, non-fractional part and fractional part.
3. Record the non-fractional part of the resulting number.
4. Repeat the above steps till the fractional part become 0 or near zero.
5. Write the digits in the non-fractional part starting from upwards to downwards.

Example 3.5: Convert 0.2345 from Base 10 to Base 2.

toBase Fraction number after non-fractional part


multiplication
2 0.2345
2 0.4690 0
2 0.9380 0
2 0.8760 1
2 0.7520 1
2 0.5040 1
0.0080 1
The binary equivalent of (0.2345)10 is (0.001111)2

Example 3.6: Convert 0.865 from Base 10 to Base 2,8 and 16.

3.4 CONVERSION OF BINARY, OCTAL, HEXADECIMAL TO DECIMAL

The method used for the conversion of integer part and fraction part of binary, octal or
hexadecimal number to decimal number is the same; multiplication operation is used for
the conversion. The conversion mechanism uses the face value and position value of
digits.

30
Example 3.7: Convert 1011 from Base 2 to Base 10. Convert 62 from Base 8 to Base 10.
Convert C15 from Base 16 to Base 10.

Example 3.8: Convert .1101 from Base 2 to Base 10. Convert .345 from Base 8 to Base
10. Convert .15 from Base 16 to Base 10.

Example 3.9: Convert 1011.1001 from Base 2 to Base 10. Convert 24.36 from Base 8 to
Base 10. Convert 4D.21 from Base 16 to Base 10.

31
3.5 CONVERSION OF BINARY TO OCTAL, HEXADECIMAL

A binary number can be converted into octal or hexadecimal number using a shortcut
method. The shortcut method is based on the following information—

• An octal digit from 0 to 7 can be represented as a combination of 3 bits, since 23 =


8.
• A hexadecimal digit from 0 to 15 can be represented as a combination of 4 bits,
since 24 = 16.

The Steps for Binary to Octal Conversion are—

1. Partition the binary number in groups of three bits, starting from the right-most
side.
2. For each group of three bits, find its octal number.
3. The result is the number formed by the combination of the octal numbers.

The Steps for Binary to Hexadecimal Conversion are—

1. Partition the binary number in groups of four bits, starting from the right-most
side.
2. For each group of four bits, find its hexadecimal number.
3. The result is the number formed by the combination of the hexadecimal numbers.

Example 3.10: Convert the binary number 1110101100110 to octal.

Given Binary number (1110101100110)2


3 bits partitions 1 110 101 100 110
Octal number 1 6 5 4 6
Converted number (16546)8

Example 3.11: Convert the binary number 1110101100110 to hexadecimal

Given Binary number (1110101100110)2


4 bits partitions 1 1101 0110 0110
hexadecimal number 1 D 6 6
Converted number (1D66)16

3.6 BINARY ARITHMETIC

32
The arithmetic operations—addition, subtraction, multiplication and division, performed
on the binary numbers is called binary arithmetic. In computer, the basic arithmetic
operations performed on the binary numbers are:

• Binary addition, and


• Binary subtraction.

In the following subsections, we discuss the binary addition and the binary subtraction
operations.

3.6.1 Binary Addition

Binary addition involves addition of two or more binary numbers. The binary addition
rules are used while performing the binary addition. Table 3.3 shows the binary addition
rules.

Table 3.3 Binary addition rules

Binary addition of three inputs follows the rule shown in Table 3.4.

Table 3.4 Binary addition of three inputs

Addition of the binary numbers involves the following steps:

1. Start addition by adding the bits in unit column (the right-most column). Use the
rules of binary addition.
2. The result of adding bits of a column is a sum with or without a carry.

33
3. Write the sum in the result of that column.
4. If a carry is present, the carry is carried-over to the addition of the next left
column.
5. Repeat steps 2–4 for each column, i.e., the tens column, hundreds column and so
on.

Let us now understand binary addition with the help of some examples.

Example 3.12: Add (10)2 and (01)2. Verify the answer with the help of decimal addition.

Example 3.13: Add (01)2 and (11)2. Verify the answer with the help of decimal addition.

Example 3.14: Add (11)2 and (11)2. Verify the answer with the help of decimal addition.

34
Example 3.15: Add (1101)2 and (1111)2. Verify the answer with the help of decimal
addition.

Example 3.16: Add (10111)2, (11100)2 and (111)2. Verify the answer with the help of
decimal addition.

3.6.2 Binary Subtraction

Binary subtraction involves subtracting of two binary numbers. The binary subtraction
rules are used while performing the binary subtraction. The binary subtraction rules are
shown in Table 3.5, where “Input 2” is subtracted from “Input 1.”

Table 3.5 Binary subtraction rules

The steps for performing subtraction of the binary numbers are as follows:

35
1. Start subtraction by subtracting the bit in the lower row from the upper row, in the
unit column.
2. Use the binary subtraction rules. If the bit in the upper row is less than lower row,
borrow 1 from the upper row of the next column (on the left side). The result of
subtracting two bits is the difference.
3. Write the difference in the result of that column.
4. Repeat steps 2 and 3 for each column, i.e., the tens column, hundreds column and
so on.

Let us now understand binary subtraction with the help of some examples.

Example 3.17: Subtract (01)2 from (11)2. Verify the answer with the help of decimal
subtraction.

Example 3.18: Subtract (01)2 from (10)2. Verify the answer with the help of decimal
subtraction.

Example 3.19: Subtract (0111)2 from (1110)2. Verify the answer with the help of
decimal subtraction.

36
Example 3.20: Subtract (100110)2 from (110001)2. Verify the answer with the help of
decimal subtraction.

3.7 SIGNED AND UNSIGNED NUMBERS


The sign of a binary number must be represented using 0 and 1, in the computer. An n-
bit signed binary number consists of two parts—sign bit and magnitude. The left most
bit, also called the Most Significant Bit (MSB) is the sign bit. The remaining n-1 bits
denote the magnitude of the number. In signed binary numbers, the sign bit is 0 for a
positive number and 1 for a negative number.
For example, 01100011 is a positive number since its sign bit is 0, and 11001011 is a
negative number since its sign bit is 1.

3.7.1 Complement of Binary Numbers


Complements are used in computer for the simplification of the subtraction operation.
For any number in base r, there exist two complements—(1) r’s complement and (2) r-1
’s complement.

37
There are two types of complements for the binary number system—1’s complement
and 2’s complement.
1’s Complement of Binary Number is computed by changing the bits 1 to 0 and the
bits 0 to 1. For example,1’s complement of 101 is 010
2’s Complement of Binary Number is computed by adding 1 to the 1’s complement
of the binary number. For example, 2’s complement of 101 is 010 + 1 = 011
The rule to find the complement of any number N in base r having n digits is
(r - 1)’s complement—(rn - 1) - N
(r’s) complement2—(rn - 1) - N + 1 = (rn - N)

3.8 BINARY DATA REPRESENTATION


The binary point is used for representing fractions, integers and integer-fraction
numbers. There are two ways of representing the position of the binary point in the
register—fixed point number representation and floating point number representation.
The fixed point number representation assumes that the binary point is fixed at one
position either at the extreme left to make the number a fraction, or at the extreme right
to make the number an integer.
The floating point number representation uses two registers. The first register stores
the number without the binary point. The second register stores a number that indicates
the position of the binary point in the first register.

3.8.1 Fixed Point Number Representation


The integer binary signed number is represented as follows—
• For a positive integer binary number, the sign bit is 0 and the magnitude is a
positive binary number.
• For a negative integer binary number, the sign bit is 1. The magnitude is
represented in any one of the three ways:
o Signed Magnitude Representation—The magnitude is the positive
binary number itself.
o Signed 1 ’s Complement Representation—The magnitude is the 1’s
complement of the positive binary number.
o Signed 2’s Complement Representation—The magnitude is the 2’s
complement of the positive binary number.

38
Example 3.21: Show fixed point representation of the signed number 18, -18.

Addition of Signed Binary Numbers:


The addition of any two signed binary numbers is performed as follows—
o Represent the positive number in binary form.
o Represent the negative number in ’s complement form.
o Add the bits of the two signed binary numbers.
o Ignore any carry out from the sign bit position.

Example 3.22: Add +5 and +10.


+5 in binary form, i.e., 0000 0101. +10 in binary form, i.e., 0000 1010.

Example 3.23: Add +5 and -10.


+5 in binary form is 0000 0101. -10 in ’s complement form is 1111 0110.
1111 1011.

The result is in 2’s complement form. To find its decimal equivalent—


Find the 2’s complement of 1111 1011, i.e., 0000 0100 + 1 = 0000 0101.
This is binary equivalent of + 5. Attaching a negative sign to the obtained
result gives us -5.

39
Subtraction of Signed Binary Numbers—The subtraction of signed binary numbers is
changed to the addition of two signed numbers. For this, the sign of the second number is
changed before performing the addition operation.
(-A) - (+B) = (-A) + (-B) (+B in subtraction is changed to -B in addition)
(+A) - (+B) = (+A) + (-B) (+B in subtraction is changed to -B in addition)
(-A) - (-B) = (-A) + (+B) (-B in subtraction is changed to +B in addition)
(+A) - (-B) = (+A) + (+B) (-B in subtraction is changed to +B in addition)
We see that the subtraction of signed binary numbers is performed using the addition
operation.

3.8.2 Floating Point Number Representation


The floating point representation of a number has two parts—mantissa and exponent.
The mantissa is a signed fixed point number. The exponent shows the position of the
binary point in the mantissa.
For example, the binary number +11001.11 with an 8-bit mantissa and 6 bit exponent is
represented as follows—
• Mantissa is 01100111. The left most 0 indicates that the number is positive.
• Exponent is 000101. This is the binary equivalent of decimal number +5.
• The floating point number is Mantissa x 2exponent, i.e., + (.1100111) x 2+5.

3.9 BINARY CODING SCHEMES


Binary Coding schemes represent the data such as alphabets, digits 0-9, and symbols
in a standard code. A combination of bits represents a unique symbol in the data. The
standard code enables any programmer to use the same combination of bits to represent
a symbol in the data.
The binary coding schemes that are most commonly used are—
• Extended Binary Coded Decimal Interchange Code (EBCDIC),
• American Standard Code for Information Interchange (ASCII), and
• Unicode

3.9.1 EBCDIC
•The Extended Binary Coded Decimal Interchange Code (EBCDIC) uses 8 bits (4 bits for
zone, 4 bits for digit) to represent a symbol in the data.
• EBCDIC allows 28 = 256 combinations of bits.
• 256 unique symbols are represented using EBCDIC code.
• EBCDIC codes are mainly used in the mainframe computers.

3.9.2 ASCII
• The American Standard Code for Information Interchange (ASCII) is widely used in
computers of all types.
• ASCII codes are of two types—ASCII-7 and ASCII-8.

40
• ASCII-7 is a 7-bit standard ASCII code. In ASCII-7, the first 3 bits are the zone bits
and the next 4 bits are for the digits.
• ASCII-8 is an extended version of ASCII-7. ASCII-8 is an 8-bit code having 4 bits for
zone and 4 bits for the digit.
• The ASCII-8 code represents 256 symbols.

3.9.3 Unicode
• Unicode is a universal character encoding standard for the representation of text which
includes letters, numbers and symbols in multi-lingual environments.
• Unicode uses 32 bits to represent a symbol in the data.
• Unicode allows 232 = 4164895296 (~ 4 billion) combinations.
• Unicode can uniquely represent any character or symbol present in any language. In
addition to the letters; mathematical and scientific symbols are
also represented
• It is compatible with the ASCII-8 codes and implemented by different character
encodings.

Unicode character encoding in MS-Word 2007

3.10 LOGIC GATES:


Binary information is represented using signals in two states off or on which
correspond to 0 or 1, respectively. The manipulation of the binary information is done
using logic gates. Logic gates are the hardware electronic circuits which operate on the

41
input signals to produce the output signals. Each logic gate has a
unique symbol and its operation is described using algebraic expression. For each gate,
the truth table shows the output that will be outputted for the different possible
combinations of the input signal. The AND, OR and NOT are the basic logic gates. Some
of the basic combination of gates that are widely used are—NAND, NOR, XOR and
XNOR.
The following table shows the different logic gates, their symbols, their algebraic
function and the truth table for each logic gate.

42
43
QUESTIONS
1. What is the significance of the base of the number?
2. Explain the significance of the face value and position value of a number. Give an
example.
3. What is the position value of a digit?
4. The decimal number system is in base _____.
5. The binary number system is in base _____.
6. The octal number system is in base _____.
7. The hexadecimal number system is in base _____.
8. Give the valid digits in the number systems—(a) decimal, (b) binary, (c) octal, and
(d) hexadecimal.
9. Write the largest digit in the number systems—(a) decimal, (b) binary, (c) octal, and
(d)hexadecimal.
10. How many valid digits are there in the number systems—(a) decimal, (b) binary,
(c) octal, and (d) hexadecimal?
11. Show the octal, binary and hexadecimal equivalent of the decimal number 11.
12. Convert the following decimal numbers into binary, octal and hexadecimal.
a) 24
b) 47
c) 675
d) 89
e) 34.24
f) 150.64
g) .98
h) 29
i) 24.14
j) 16.1
k) 22.33

13. Convert the following binary numbers into decimal numbers.


a) 110000111
b) 110011
c) 1001111
d) 11000001
e) 1100110.1110
f) 11110.0000
g) 01001.0101
h) 1010.10101
i) 11000011.111
j) 11001.1101

44
k) 100.111
L) 101.0111
14. Convert the following octal numbers into decimal numbers.
a) 234
b) 36
c) 456
d) 217
e) 25.33
f) 65.34
g) 34.56
h) 267.12
15. Convert the following hexadecimal numbers into decimal numbers.
a) E16
b) 389
c) 2AB
d) FF
e) E4.16
f) 2A.1B
g) 23.89
h) AC.BD
16. Convert the following binary into octal.
a) 1100011
b) 110011001100
c) 100111100
d) 110000011
e) 110011011
f) 1111000
g) 0010101
h) 101010101
17. Convert the following binary into hexadecimal.
a) 11000011111
b) 1100110011
c) 100111100
d) 1100000100
e) 11001101110
f) 111100000
g) 010010101
h) 101010101
18. Convert the following octal into binary
a) 25
b) 65

45
c) 34
d) 267
e) 45
f) 71
g) 150
h) 111
19. Convert the following hexadecimal into binary.
a) A1
b) 2AB
c) 239
d) CCD
e) 45C
f) 71D
g) 150
h) AAA
20. Perform binary addition on the following binary numbers.
a) 111100, 011011
b) 1001, 1111
c) 0110, 1100
d) 1100, 1010
21. Perform binary subtraction on the following binary numbers.
a) 111000, 011010
b) 1111, 1001
c) 0110, 0010
d) 1100, 1010
22. Find 1’s complement of the following binary numbers.
a) 11000011111
b) 1100110011
c) 100111100
d) 1100000100
23. Find ’s complement of the following binary numbers.
a) 11000011111
b) 1100110011
c) 100111100
d) 1100000100
24. What is the relation between the 1’s complement and ’s complement of a binary
number?
25. In addition to the digits, a number may contain a _____ and _____.
26. What is a sign bit?
27. Which bit is considered as a sign bit when representing a number?
28. What is the value of sign bit for a positive number?

46
29. What is the value of sign bit for a negative number?
30. What is the range of data that can be represented using an 8-bit signed number?
31. What is the range of data that can be represented using an 8-bit unsigned number?
32. _____ representation and _____ representation are the two ways of representing
the position of the binary point in the register.
33. Represent the following as 8-bit numbers in (a) Signed Magnitude representation,
(b) Signed 1’s complement representation, and (c) Signed ’s complement
representation
a) -22
b) -55
c) -34
d) -67
34. Represent the following as 8-bit numbers in Fixed Point number representation.
a) +22
b) +55
c) +34
d) +67
35. Perform binary addition of the following numbers.
a) (+7) + (-9)
b) (+3) + (+15)
c) (-12) + (+15)
d) (-14) + (+25)
e) (-7) + (-7)
f) (-9) + (-23)
g) (-2) + (+4)
h) (+34) + (-2)
36. Perform binary subtraction of the following numbers
a) (+7) - (-19)
b) (+13) - (+15)
c) (-12) - (+15)
d) (-14) - (+25)
e) (-7) - (-7)
f) (-9) - (-23)
g) (-2) - (+4)
h) (+34) - (-2)
37. Represent the following binary numbers in Floating Point number representation.
a) 1100.011
b) 110.001
c) 11.110
d) 1010.011
38. Why are binary coding schemes needed?

47
39. List any four commonly used binary coding schemes.
40. What number of bits is used to represent the following codes—(a) EBCDIC, (b)
ASCII-7, and (c) ASCII-8?
41. How many characters can be represented in the following codes—(a) EBCDIC, (b)
ASCII-7, and (c) ASCII-8?
42. Name the basic logic gates.
43. Draw the symbols of the following logic gates—
(a) AND (b) OR (c) NOT, (d) NAND, (e)NOR, (f) XOR, and (g) XNOR.
44. Write the truth table of the following logic gates—
(a) AND (b) OR (c) NOT, (d) NAND, (e) NOR, (f) XOR, and (g) XNOR.
45. Write the algebraic function of the following logic gates-
(a) AND (b) OR, (c) NOT, (d)NAND, (e) NOR, (f) XOR, and (g) XNOR.

48
CHAPTER 4

COMPUTER SOFTWARE

49
CHAPTER 4: COMPUTER SOFTWARE
4.1 INTRODUCTION
The computer hardware cannot perform any task on its own. It needs to be instructed
about the tasks to be performed. Software is a set of programs that instructs the
computer about the tasks to be performed. Software tells the computer how the tasks
are to be performed; hardware carries out these tasks. Different sets of software can be
loaded on the same hardware to perform different kinds of tasks.

4.2 TYPES OF SOFTWARE


Software can be broadly classified in two categories:
1. System Software, and
2. Application Software.
System software provides the basic functions that are performed by the computer. It is
necessary for the functioning of a computer. Application software is used by the users
to perform specific tasks. The user may choose the appropriate application software, for
performing a specific task, which provides the desired functionality. The system
software interacts with hardware at one end and with application software at the other
end. The application software interacts with the system software and the users of the
computer.

Software hierarchy

4.3 SYSTEM SOFTWARE


System software provides basic functionality to the computer. System software is
required for the working of computer itself. The user of computer does not need to be
aware about the functioning of system software, while using the computer. The purposes
of the system software are:

50
• To provide basic functionality to computer,
• To control computer hardware, and
• To act as an interface between user, application software and computer
hardware.

Based on their functionality, system software may be broadly divided into two categories:
• System software for the management and functionality of computer relates to the
functioning of different components of the computer, like, processor, input and
output devices etc. System software is required for managing the operations
performed by the components of computer and the devices attached to the
computer. It provides support for various services, as requested by the application
software. Operating system, device drivers, and system utilities constitute the
system software for management of computer and its resources.
• System software for the development of application software provides services
required for the development and execution of application software. System
software provides the software tools required for the development of application
software. The programming language software, translator software, loader, and
linker are also categorized as system software, and are required for the application
software development.

System software

4.3.1 Operating System


Operating System (OS) is an important part of a computer. OS intermediates between
the user of a computer and the computer hardware. Different kinds of application
software use specific hardware resources of a computer like CPU, I/O devices and
memory, as needed by the application software. OS controls and coordinates the use of
hardware among the different application software and the users. It provides an interface

51
that is convenient for the user to use and facilitates efficient operations of the computer
system resources. The key functions of OS are—
• It provides an environment in which users and application software can do work.
• It manages different resources of the computer like the CPU time, memory space,
file storage, I/O devices etc.
• It controls the execution of different programs to prevent occurrence of error.
• It provides a convenient interface to the user in the form of commands and
graphical interface, which facilitates the use of computer.

Some available operating systems are Microsoft Disk Operating System (MS-DOS),
Windows 7, Windows XP, Linux, UNIX, and Mac OS X Snow Leopard.

4.3.2 FUNCTIONS OF OS
Operating system is a large and complex software consisting of several components.
Each component of the operating system has its own set of defined inputs and outputs.
Different components of OS perform specific tasks to provide the overall functionality of
the operating system. Main functions of the operating system are as follows:

Functions of OS
• Process Management—The process management activities handled by the
OS are—(1) control access to shared resources like file, memory, I/O and
CPU, (2) control execution of applications, (3) create, execute and delete a
process (system process or user process), (4) cancel or resume a process
(5) schedule a process, and (6) synchronization, communication and deadlock
handling for processes.
• Memory Management—The activities of memory management handled by
OS are—(1) allocate memory, (2) free memory, (3) re-allocate memory to

52
a program when a used block is freed, and (4) keep track of memory usage.
• File Management—The file management tasks include—(1) create and delete
both files and directories, (2) provide access to files, (3) allocate space for files, (4)
keep back-up of files, and (5) secure files.
• Device Management—The device management tasks handled by OS are— (1)
open, close and write device drivers, and (2) communicate, control and monitor the
device driver.
• Protection and Security—OS protects the resources of system. User
authentication, file attributes like read, write, encryption, and back-up of data are
used by OS to provide basic protection.
• User Interface or Command Interpreter—Operating system provides an
interface between the computer user and the computer hardware.

4.3.3 TYPES OF OS
OS are classified into different types depending on their capability of processing:
• Single User and Single Task OS is for use by a single user for a stand alone single
computer for performing a single task.
• Single User and Multitasking OS allows execution of more than one task or process
concurrently. For this, the processor time is divided amongst different tasks. This
division of time is also called time sharing
• Multiuser OS is used in computer networks that allow same data and applications to
be accessed by multiple users at the same time.
• Multiprocessing OS have two or more processors for a single running process.
Processing takes place in parallel and is also called parallel processing.
• Real Time OS are designed to respond to an event within a predetermined time.
These operating systems are used to control processes. Processing is done within a
time constraint.
• Embedded OS is embedded in a device in the ROM. They are specific to
a device and are less resource intensive. They are used in appliances like
microwaves, washing machines, traffic control systems etc.

4.3.4 Device Driver


A device driver acts as a translator between the hardware and the software that uses the
devices. In other words, it intermediates between the device and the software, in order
to use the device.

4.3.5 System Utilities


System utility software is required for the maintenance of computer. System utilities
are used for supporting and enhancing the programs and the data in computer. Some
system utilities may come embedded with OS and others may be added later. Some
examples of system utilities are:

53
• Anti-virus
utility to scan computer for viruses.
• Data Compression utility to compress the files.
• Cryptographic utility to encrypt and decrypt files.
• Disk Compression utility to compress contents of a disk
• Disk Partitioning to divide a single drive into multiple logical drives.
• Disk Cleaners to find files that have not been used for a long time.

4.3.6 Programming Languages


A Programming Language consists of a set of vocabulary and grammatical rules, to
express the computations and tasks that the computer must perform. Programming
languages are used to write a program, which controls the behavior of computer, codify
the algorithms precisely, or enables the human-computer interface. Each language has a
unique set of keywords (words that it understands) and a special syntax for organizing
program instructions. The programming language should be understood, both by the
programmer (who is writing the program) and the computer. Programming languages
fall into three categories:
• Machine Language is what the computer can understand but it is difficult for
the programmer to understand.
• Assembly Language falls in between machine language and high-level
language. They are like machine language, but easier to program in,
• High-level Language is easier to understand and use for the programmer but
difficult for the computer.

Regardless of the programming language used, the program needs to be converted into
machine language so that the computer can understand it. In order to do this a program is
either compiled or interpreted.
The choice of programming language for writing a program depends on the functionality
required from the program and the kind of program to be written. Machine languages
and assembly languages are also called low-level languages and are generally used to
write the system software. Application software is usually written in high-level
languages. The program written in a programming language is also called the source
code.

54
A program in machine language

4.4 TRANSLATOR SOFTWARE


Translator software converts a program written in assembly language, and high-level
language to a machine-level language program. The translated program is called the
object code. There are three different kind of translator software:
• Assembler.
• Compiler.
• Interpreter.
Assembler converts a program written in assembly language to machine language.
Compiler and interpreter convert a program written in high-level language to machine
language.

4.4.1 Assembler
Assembly language is also referred to as a symbolic representation of the machine
code. Assembler is a software that converts a program written in assembly language into
machine code.

Assembler

55
4.4.2 Compiler
A program written in a high-level language must be converted to a language that the
computer can understand, i.e. binary form. Compiler is the software that translates the
program written in a high-level language to machine language. The program written in
high-level language is referred to as the source code and compiled program is referred as
the object code. The object code is the executable code, which can run as a stand-alone
code. It does not require the compiler to be present during execution. Each programming
language has its own compiler. Some languages that use a compiler are C++, COBOL,
Pascal, and FORTRAN.

4.4.3 Interpreter
The purpose of interpreter is like that of a compiler. The interpreter is used to convert
the high-level language program into computer understandable form. However, the
interpreter functions in a different way than a compiler. Interpreter performs line-by-line
execution of the source code during program execution. Interpreter reads the source code
line-by-line, converts it into machine understandable form, executes the line, and then
proceeds to the next line. Some languages that use an interpreter are BASIC and Python.

4.5 The hierarchy of program


Linker is a program that links several object modules and libraries to a single
executable program. A source code of a program is often very large consisting of several
hundred or more lines. The source code may also include reference to libraries. All these
independent modules may not be stored in a single object file. The code is broken down
into many independent modules for easy debugging and maintenance. Before execution
of the program, these modules and the required libraries are linked together using the
linker software. The compiled and the
linked program are called the executable code.
loader software is used to load and re-locate the executable program in the main
memory. Software must be loaded into the main memory during execution. Loader
assigns storage space to the program in the main memory for execution.

Hierarchy of program execution

56
4.6 APPLICATION SOFTWARE
The software that a user uses for accomplishing a specific task is the application
software. Application software may be a single program or a set of programs. A set of
programs that are written for a specific purpose and provide the required functionality is
called software package. Application software is written for different kinds of
applications—graphics, word processors, media players, database applications,
telecommunication, accounting purposes etc.
Some examples of application software packages are as follows:
• Word Processing Software: For writing letter, reports, documents etc. (e.g.
MS-WORD).
• Image Processing Software: For assisting in drawing and manipulating
graphics (e.g.Adobe Photoshop).
• Accounting Software: For assisting in accounting information, salary, tax
returns (Tallysoftware).
• Web Browser Software: To access the World Wide Web to search
documents, sounds, images etc. (e.g. Internet Explorer, Netscape
Communicator, Chrome).

4.6.1 SOFTWARE ACQUISITION


Different kinds of software are made available for use to users in different ways. The
different ways in which the software is made available to users are:
• Retail Software is off-the-shelf software sold in retail stores.
• OEM Software stands for “Original Equipment Manufacturer” software. It refers
to software which is sold and bundled with hardware.
• Demo Software is designed to demonstrate what a purchased version of the
software can do and provides a restricted set of features.
• Shareware is a program that the user can try for free, for a specified period, as
defined in the license.
• Freeware is software that is free for personal use.
• Public Domain Software is free software. Unlike freeware, public domain
software does not have a copyright owner or license restrictions.
• Open-Source Software is software whose source code is available and can be
customized and altered within the specified guidelines laid down by the creator.

57
QUESTIONS
1. _____ and _____ are the two main categories of software.
2. What is the purpose of system software?
3. What is system software?
4. Give two examples of system software.
5. Describe the two categories of system software.
5.What is the need of an operating system?
6.Describe the functions of an operating system.
7.Explain the objective of OS.
8.Classify the OS into different types based on their processing capability.
9.What is Single user and Single Task OS?
10. What is Single user and Multitasking OS?
11. What is time sharing?
12. What is a Multiuser OS?
13. What is a Multiprocessing OS.
14. Define parallel processing.
15. What is the purpose of Real time OS?
16. What is the purpose of Embedded OS?
17. Name any three operating systems.
18. What are the uses of system utilities?
19. Why are programming languages used?
20. What is the need for programming languages?
21. Name the three categories of programming languages.
22. What are low-level languages?
23. Define source code?
24. Define object code?
25. Machine language is hardware dependent—True or False.
26. Why is it easier to write a program in high-level language than the assembly
language?
27. Name two high-level languages.
28. What is the purpose of an assembler?
29. What is an executable code?
30. What is the purpose of a compiler?
31. How does an interpreter work?
32. What is the purpose of linker?
33. What is the purpose of loader?
34. Draw the cycle from the writing of the program in a high-level language to its
execution.
35. What is the use of application software?
36. What are the different ways of acquiring software?

58
CHAPTER 5

COMPUTER PROGRAMMING
FUNDAMENTALS

59
CHAPTER 5: COMPUTER PROGRAMMING FUNDAMENTALS
5.1 INTRODUCTION

Computer is an electronic device that accepts data, processes it, and generates the
relevant output. It can perform both simple and complex tasks with very high speed and
accuracy. However, a computer cannot perform any task—simple or complex, of its own.
Computers need to be instructed about “how” the task is to be performed. The set of
instructions that instruct the computer about the way the task is to be performed is called
a program. A program is required for processing all kind of tasks—simple tasks like
addition of two numbers, and complex tasks like gaming etc.

A program is a set of instructions written for performing a specific task. However,


writing a good program is not a straightforward task. For writing a program, we must
follow the program development life cycle which includes choosing a programming
paradigm and selecting a computer programming language in which to write the program.
With practice, you can easily acquire the skill of program writing. The purpose of this
chapter is to introduce you to the fundamentals of Computer Programming.

5.2 PROGRAM DEVELOPMENT LIFE CYCLE

A person who writes the program (computer programmer) must follow the Program
Development Life Cycle. Let us now discuss the steps that are followed by the
programmer for writing a program:

Program Details
Development Life
Cycle Steps
Problem Analysis The programmer first understands the problem to be solved. The
programmer determines the various ways in which the problem
can be solved and decides upon a single solution which will be
followed to solve the problem. Can be summarized as follow:
• Understand the problem
• Have multiple solutions
• Select a solution
Program Design The selected solution is represented in a form, so that it can be
coded. This requires three steps:
• An algorithm is written, which is an English-like
explanation of the solution.
• A flowchart is drawn, which is a diagrammatic
representation of the solution. The solution is represented
diagrammatically, for easy understanding and clarity.
• A pseudo code is written for the selected solution. Pseudo
code uses the structured programming constructs. The
pseudo code becomes an input to the next phase.

60
Which can be summarized as follow:
• Write an algorithm
• Draw a flowchart
• Write a pseudo code
Program The computer programming languages are of different kinds—
Development low-level languages, and high- level languages like C, C++ and
Java. The pseudo code is coded using a suitable programming
language.
The coded pseudo code or program is compiled for any syntax
errors. Syntax errors arise due to the incorrect use of programming
language or due to the grammatical errors with respect to the
programming language used. During compilation, the syntax
errors, if any, are removed.
The successfully compiled program is now ready for execution.
The executed program generates the output result, which may be
correct or incorrect. The program is tested with various inputs, to
see that it generates the desired results. If incorrect results are
displayed, then the program has semantic error (logical error). The
semantic errors are removed from the program to get the correct
results.
The successfully tested program is ready for use and is installed on
the user’s machine.
All the above can be summarized as follow:
• Choose a programming language
• Write the program
• Compile the program and remove syntax errors if any
• Execute the program
• Test the program. If the output is incorrect (logical / semantic
errors), modify the program to get correct results.
• Install the tested program on the user’s computer.
Program The program is properly documented, so that later, anyone can use
Documentation it and understand its working. Any changes made to the program,
and Maintenance after installation, forms part of the maintenance of program. The
program may require updating, fixing of errors etc. during the
maintenance phase.
Can be summarized as follow:
• Document the program, for later use.
• Maintain the program for updating, removing errors, changing
requirements etc.

5.3 ALGORITHM

Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for


completing a task. Algorithm is an English-like representation of the logic which is used

61
to solve the problem. It is a step- by-step procedure for solving a task or a problem. The
steps must be ordered, unambiguous and finite in number.

For accomplishing a particular task, different algorithms can be written. The different
algorithms differ in their requirements of time and space. The programmer selects the
best-suited algorithm for the given task to be solved.

Let us now look at two simple algorithms to find the greatest among three numbers, as
follows:

Algorithm to find the greatest among three numbers—

ALGORITHM 1.

Step 1: Start

Step 2: Read the three numbers A, B, C

Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.

Step 4: Compare A and C. If A is greater, output “A is greatest” else output “C is


greatest”. Perform step 6.

Step 5: Compare B and C. If B is greater, output “B is greatest” else output “C is


greatest”.

Step 6: Stop

ALGORITHM 2.

Step1: Start

Step 2: Read the three numbers A, B, C

Step 3: Compare A and B. If A is greater, store A in MAX, else store B in MAX.

Step 4: Compare MAX and C. If MAX is greater, output “MAX is greatest” else output
“C is greatest”.

Step 5: Stop

Both the algorithms accomplish the same goal, but in different ways. The programmer
selects the algorithm based on the advantages and disadvantages of each algorithm. For
example, the first algorithm has more number of comparisons, whereas in the second
algorithm an additional variable MAX is required.

62
5.4 CONTROL STRUCTURES

The logic of a program may not always be a linear sequence of statements to be executed
in that order. The logic of the program may require execution of a statement based on a
decision. It may repetitively execute a set of statements unless some condition is met.
Control structures specify the statements to be executed and the order of execution of
statements.

Flowchart and Pseudo code use control structures for representation. There are three
kinds of control structures:

• Sequential—instructions are executed in linear order


• Selection (branch or conditional)—it asks a true/false question and then selects
the next instruction based on the answer
• Iterative (loop)—it repeats the execution of a block of instructions.

The flowchart and the pseudo code control structures are explained in their respective
sections.

5.5 FLOWCHART

A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart


is drawn using boxes of different shapes with lines connecting them to show the flow of
control. The purpose of drawing a flowchart is to make the logic of the program clearer in
a visual form. There is a famous saying “A photograph is equivalent to thousand words”.

5.5.1 Flowchart Symbols

A symbol used in a flowchart is for a specific purpose. Figure 5.1 shows the different
symbols of the flowchart along with their names and description. The flowchart symbols
are available in most word processors including MS-WORD, facilitating the programmer
to draw a flowchart on the computer using the word processor.

5.5.2 Preparing a Flowchart

A flowchart may be simple or complex. The most common symbols that are used to draw
a flowchart are—Process, Decision, Data, Terminator, Connector and Flow lines. While
drawing a flowchart, some rules need to be followed—

(1) A flowchart should have a start and end,


(2) The direction of flow in a flowchart must be from top to bottom and left to right,
(3) The relevant symbols must be used while drawing a flowchart. While preparing
the flowchart, the sequence, selection or iterative structures may be used wherever
required. Figure 5.2 shows the sequence, selection and iteration structures.

63
Figure 5.1 Flowchart symbols

Figure 5.2 Control structures in flowchart

We see that in a sequence, the steps are executed in linear order one after the other. In a
selection operation, the step to be executed next is based on a decision taken. If the
condition is true (yes) a different path is followed than if the condition evaluates to false
(no). In case of iterative operation, a condition is checked. Based upon the result of this
conditional check, true or false, different paths are followed. Either the next step in the
sequence is executed or the control goes back to one of the already executed steps to
make a loop.

64
Here, we will illustrate the method to draw flowchart, by discussing three different
examples. To draw the flowcharts, relevant boxes are used and are connected via flow
lines. The flowchart for the examples is shown in Figure 5.3.

Figure 5.3 Examples of flowchart

• The first flowchart computes the product of any two numbers and gives the result.
The flowchart is a simple sequence of steps to be performed in a sequential order.
• The second flowchart compares three numbers and finds the maximum of the
three numbers. This flowchart uses selection. In this flowchart, decision is taken
based upon a condition, which decides the next path to be followed, i.e. If A is
greater than B then the true (Yes) path is followed else the false (No) path is
followed. Another decision is again made while comparing MAX with C.
• The third flowchart finds the sum of first 100 integers. Here, iteration (loop) is
performed so that some steps are executed repetitively until they fulfill some
condition to exit from the repetition. In the decision box, the value of I is
compared with 100. If it is false (No), a loop is created which breaks when the
condition becomes true (Yes). Flowcharts have their own benefits; however, they
have some limitations too. A complex and long flowchart may run into multiple

65
pages, which becomes difficult to understand and follow. Moreover, updating a
flowchart with the changing requirements is a challenging job.

5.6 PSEUDO CODE

Pseudo code consists of short, readable and formally-styled English language used for
explaining an algorithm. Pseudo code does not include details like variable declarations,
subroutines etc. Pseudo code is a short-hand way of describing a computer program.
Using pseudo code, it is easier for a programmer or a non-programmer to understand the
general working of the program, since it is not based on any programming language. It is
used to give a sketch of the structure of the program before the actual coding. It uses the
structured constructs of the programming language but is not machine-readable. Pseudo
code cannot be compiled or executed. Thus, no standard for the syntax of pseudo code
exists. For writing the pseudo code, the programmer is not required to know the
programming language in which the pseudo code will be implemented later.

5.6.1 Preparing a Pseudo Code

• Pseudo code is written using structured English.


• In a pseudo code, some terms are commonly used to represent the various actions. For
example, for inputting data the terms may be (INPUT, GET, READ), for outputting
data (OUTPUT,PRINT, DISPLAY), for calculations (COMPUTE, CALCULATE), for
incrementing (INCREMENT), in addition to words like ADD, SUBTRACT,
INITIALIZE used for addition, subtraction, and initialization, respectively.
• The control structures—sequence, selection, and iteration are also used while writing
the pseudo code.
• Figure 4.4 shows the different pseudo code structures. The sequence structure is simply
a sequence of steps to be executed in linear order. There are two main selection
constructs—if statement and case statement. In the if-statement, if the condition is true
then the THEN part is executed otherwise the ELSE part is executed. There can be
variations of the if-statement also, like there may not be any ELSE part or there may be
nested ifs. The case statement is used where there are a number of conditions to be
checked. In a case statement, depending on the value of the expression, one of the
conditions is true, for which the corresponding statements are executed. If no match for
the expression occurs, then the OTHERS option which is also the default option, is
executed.
• WHILE and DO-WHILE are the two iterative statements. The WHILE loop and the
DO- WHILE loop, both execute while the condition is true. However, in a WHILE loop
the condition is checked at the start of the loop, whereas, in a DO-WHILE loop the
condition is checked at the end of the loop. So the DO-WHILE loop executes at least
once even if the condition is false when the loop is entered.

66
Figure 4.4 Control structures for pseudo code

In Figure 4.5, the pseudo code is written for the same three tasks for which the flowchart
was shown in the previous section. The three tasks are—(i) compute the product of any
two numbers, (ii) find the maximum of any three numbers, and (iii) find the sum of first
100 integers.

Figure 4.5 Examples of pseudo code

67
5.6.2 Difference between Algorithm, Flowchart, and Pseudo Code:

An algorithm is a sequence of instructions used to solve a particular problem. Flowchart


and Pseudo code are tools to document and represent the algorithm. In other words, an
algorithm can be represented using a flowchart or a pseudo code. Flowchart is a graphical
representation of the algorithm. Pseudo code is a readable, formally styled English like
language representation of the algorithm. Both flowchart and pseudo code use structured
constructs of the programming language for representation. The user does not require the
knowledge of a programming language to write or understand a flowchart or a pseudo
code.

5.7 Examples on Flowchart

1) Flowchart of a program that computes the smallest number out of three numbers

2) Flowchart of a program that sums 1+2+3+...+10

68
3) Flowchart of a program that computes the roots of a second-order polynomial

4) Flowchart of a program that reads N numbers and prints the largest number

69
5) Pay with overtime (rate*1.5) for hours greater than 40.

70
6) Trace the Flowchart

71
QUESTIONS
1. Define a program.
2. Explain the program development life cycle in detail.
3. Define algorithm.
4. What are control structures?
5. Name the three kinds of control structures.
6. State the purpose of each of the control structures:
1. Sequence,
2. Selection, and
3. Iteration.
7. Define flowchart.
8. Draw the flowchart symbol for the following—(i) Process, (ii) Decision, (iii)
Document, (iv) Connector, and (v) Magnetic Disk.
9. Draw the control structures (Sequence, Selection and Iteration) for the flowchart.
10. Define pseudo code.
11. Write the pseudo code control structures (sequence, selection, and iteration).
12. What is the difference between WHILE and DO- WHILE statements?
13. Trace the following flowcharts:

a)

72
b)

73
CHAPTER 6

BASICS OF C++

74
CHAPTER 6: BASICS OF C++
6.1 INTRODUCTION

In any language there are some fundamentals you need to know before you can write
even the most elementary programs. This chapter introduces three such fundamentals:
basic program construction, variables, and input/output (I/O). It also touches on a variety
of other language features, including comments, arithmetic operators, the increment
operator, data conversion, and library functions. You can use either a Microsoft, Borland
or Code blocks compiler. Code blocks can be downloaded from

http://www.codeblocks.org/downloads/26

Compilers take source code and transform it into executable files, which your computer
can run as it does other programs. Source files are text files (extension .CPP) that
correspond with the listings printed in this book. Executable files have the .EXE
extension, and can be executed either from within your compiler, or, if you’re familiar
with MS-DOS, directly from a DOS window.

6.2 Basic Program Construction

Probably the best way to start learning a programming language is by writing a program.
Therefore, here is our first program. It simply prints a sentence "Hello World!" on the
screen.

// my first program in C++


/* It prints a statement
on the screen*/
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
It is one of the simplest programs that can be written in C++, but it already contains the
fundamental components that every C++ program has. We are going to look line by line
at the code we have just written:

// my first program in C++


/* It prints a statement
on the screen*/
• This is a comment line. All lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behavior of the program. The

75
programmer can use them to include short explanations or observations within the
source code itself. In this case, the line is a brief description of what our program
is. There are two types way of writing comments.
o Line comments using (//)
o Block comments for multiple lines of comments using (/*) at the
beginning of the comments and (*/) at the end, all what exist between (/*)
and (*/) is considered as comments.

#include <iostream>

• Lines beginning with a hash sign (#) are directives for the preprocessor. They are
not regular code lines with expressions but indications for the compiler's
preprocessor. In this case the directive #include <iostream> tells the preprocessor
to include the iostream standard file. This specific file (iostream) includes the
declarations of the basic standard input-output library in C++, and it is included
because its functionality is going to be used later in the program.

using namespace std;

• All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std. So in order to access its
functionality we declare with this expression that we will be using these entities.
This line is very frequent in C++ programs that use the standard library, and in
fact it will be included in most of the source codes included in these tutorials.

int main ()

• This line corresponds to the beginning of the definition of the main function. The
main function is the point by where all C++ programs start their execution,
independently of its location within the source code. It does not matter whether
there are other functions with other names defined before or after it – the
instructions contained within this function's definition will always be the first
ones to be executed in any C++ program. For that same reason, it is essential that
all C++ programs have a main function.
• The word main is followed in the code by a pair of parentheses (()). That is
because it is a function declaration: In C++, what differentiates a function
declaration from other types of expressions are these parentheses that follow its
name. Optionally, these parentheses may enclose a list of parameters within them.
• Right after these parentheses we can find the body of the main function enclosed
in braces ({}). What is contained within these braces is what the function does
when it is executed.

76
cout << "Hello World!";

• This line is a C++ statement. A statement is a simple or compound expression that


can actually produce some effect. In fact, this statement performs the only action
that generates a visible effect in our first program.
• cout represents the standard output stream in C++, and the meaning of the entire
statement is to insert a sequence of characters (in this case the Hello World
sequence of characters) into the standard output stream (which usually is the
screen).
• cout is declared in the iostream standard file within the std namespace, so that's
why we needed to include that specific file and to declare that we were going to
use this specific namespace earlier in our code.
• Notice that the statement ends with a semicolon character (;). This character is
used to mark the end of the statement and in fact it must be included at the end of
all expression statements in all C++ programs (one of the most common syntax
errors is indeed to forget to include some semicolon after a statement).

return 0;

• The return statement causes the main function to finish. Return may be followed
by a return code (in our example is followed by the return code 0). A return code
of 0 for the main function is generally interpreted as the program worked as
expected without any errors during its execution. This is the most usual way to
end a C++ console program.

Whitespace

We mentioned that the end of a line isn’t important to a C++ compiler. Actually, the
compiler ignores whitespace almost completely. Whitespace is defined as spaces,
carriage returns, linefeeds, tabs, vertical tabs, and formfeeds. These characters are
invisible to the compiler.

In C++, the separation between statements is specified with an ending semicolon (;) at the
end of each one, so the separation in different code lines does not matter at all for this
purpose. We can write many statements per line or write a single statement that takes
many code lines. The division of code in different lines serves only to make it more
legible and schematic for the humans that may read it. Thus the FIRST program could be
written this way:

int main () { cout << " Hello World!"; return 0; }

All in just one line and this would have had exactly the same meaning as the previous
code. We don’t recommend this syntax—it’s nonstandard and hard to read—but it does

77
compile correctly. There are several exceptions to the rule that whitespace is invisible to
the compiler. The first line of the program, starting with #include, is a preprocessor
directive, which must be written on one line. Also, string constants, such as " Hello
World!", cannot be broken into separate lines. (If you need a long string constant, you
can insert a backslash (\n) at the line break or divide the string into two separate strings,
each surrounded by quotes.)

6.3 Basic Language Feature

Token is the minimal chunk of a program that has a meaning to the compiler. Table 6.1
gives an example for the different token types in C++, its meaning, and an example for it.

Table 6.1 An example for the different token types in C++

6.3.1 Keywords

Keywords are reserved words in any language which have a special predefined meaning
and cannot be used for any other purpose such as:

• include, main, return, int , for, if, … etc.

6.3.2 Identifiers

Identifiers are the name of variables, functions, arrays, … , etc. There are certain rules to
name identifiers in C++.

• Identifiers can contain combinations of digits, letters and underscore (_).


• Identifier names cannot start with a digit.

78
• Keyword cannot be used as an identifier name.
• Upper case and lower case are distinct (case sensitive).

6.4 Variables and Data Types.

In order to go a little further on and to become able to write programs that perform useful
tasks that really save us work we need to introduce the concept of variable.

Variables are the most fundamental part of any language. A variable has a symbolic name
(Identifier) and can be given a variety of values. Variables are located in particular places
in the computer’s memory. When a variable is given a value, that value is actually placed
in the memory space assigned to the variable. Most popular languages use the same
general variable types, such as integers, floating-point numbers, and characters, so you
are probably already familiar with the ideas behind them.

6.4.1 Fundamental data types

When programming, we store the variables in our computer's memory, but the computer
has to know what kind of data we want to store in them, since it is not going to occupy
the same amount of memory to store a simple number than to store a single letter or a
large number, and they are not going to be interpreted the same way.

The memory in our computers is organized in bytes. A byte is the minimum amount of
memory that we can manage in C++. A byte can store a relatively small amount of data:
one single character or a small integer (generally an integer between 0 and 255). In
addition, the computer can manipulate more complex data types that come from grouping
several bytes, such as long numbers or non-integer numbers.

Table 6.2 have a summary of the basic fundamental data types in C++, as well as the
range of values that can be represented with each one:

Table 6.2 A summary of the basic fundamental data types in C++,

79
6.4.2 Declaration of variables

In order to use a variable in C++, we must first declare it specifying which data type we
want it to be. You can place variable declarations anywhere in a program. It’s not
necessary to declare variables before the first executable statement. The syntax to declare
a new variable is to write the specifier of the desired data type (like int, bool, float...)
followed by a valid variable identifier. For example:

Int a;
float mynumber;

These are two valid declarations of variables. The first one declares a variable of type int
with the identifier a. The second one declares a variable of type float with the identifier
mynumber. Once declared, the variables a and mynumber can be used within the rest of
their scope in the program.

If you are going to declare more than one variable of the same type, you can declare all of
them in a single statement by separating their identifiers with commas. For example:

int a, b, c;

The integer data types char, short, long and int can be either signed or unsigned
depending on the range of numbers needed to be represented. Signed types can represent
both positive and negative values, whereas unsigned types can only represent positive
values (and zero). This can be specified by using either the specifier signed or the
specifier unsigned before the type name. For example:

unsigned short int NumberOfSisters;


signed int MyAccountBalance;

By default, if we do not specify either signed or unsigned most compiler settings will
assume the type to be signed.

To see what variable declarations look like in action within a program, we are going to
see the C++ code of the example about your mental memory proposed at the beginning of
this section:

Program Code Run outputs


// operating with variables 4
#include <iostream>
using namespace std;
int main ()
{
// declaring variables:

80
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
Do not worry if something else than the variable declarations themselves looks a bit
strange to you. You will see the rest in detail in coming sections.

6.4.3 Scope of variables

A variable can be either of global or local scope. A global variable is a variable declared
in the main body of the source code, outside all functions, while a local variable is one
declared within the body of a function or a block. Global variables can be referred from
anywhere in the code, even inside functions, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) where they are
declared. For example, if they are declared at the beginning of the body of a function
(like in function main) their scope is between its declaration point and the end of that
function. In the example below, this means that if another function existed in addition to
main, the local variables declared in main could not be accessed from the other function
and vice versa.

#include <iostream>
Using namespace std;
cnt intvar;
char carver;
char string [20]; Global Variable
unsigned int Number0fsons;
int main ()
{
unsigned short Age;
float ANumber, Anotherone; Local Variable

cout << "Enter your age:"


cin >> Age; Instructions

81
Global variables can be referred from anywhere in the code, even inside functions,
whenever it is after its declaration.

6.4.4 Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you
may want a variable to store a concrete value at the same moment that it is declared. In
order to do that, you can initialize the variable. There are two ways to do this in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value
to which the variable will be initialized:

type identifier = initial_value ;

For example, if we want to declare an int variable called a initialized with a value of 0 at
the moment in which it is declared, we could write:

int a = 0;

The other way to initialize variables, known as constructor initialization, is done by


enclosing the initial value between parentheses (()):

type identifier (initial_value) ;

For example:

int a (0);

Both ways of initializing variables are valid and equivalent in C++

Program Code Run outputs


// initialization of variables 6
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}

82
6.5 Introduction to strings

Variables that can store non-numerical values that are longer than one single character
are known as strings.

The C++ language library provides support for strings through the standard string class.
This is not a fundamental type, but it behaves in a similar way as fundamental types do in
its most basic usage.

A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an additional header file in our source code:
<string> and have access to the std namespace (which we already had in all our previous
programs thanks to the using namespace statement).

Program Code Run outputs


// my first string This is a string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}

As you may see in the previous example, strings can be initialized with any valid string
literal just like numerical type variables can be initialized to any valid numerical literal.
Both initialization formats are valid with strings:

string mystring = "This is a string";


string mystring ("This is a string");

6.6 Constants

Constants are expressions with a fixed value which cannot change. Literals are used to
express particular values within the source code of a program. We have already used
these previously to give concrete values to variables or to express messages we wanted
our programs to print out. Literal constants can be divided in Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean Values.

83
6.6.1 Integer Numerals

1776
707
-273
They are numerical constants that identify integer decimal values. Notice that to express a
numerical constant we do not have to write quotes (") nor any special character. In
addition to decimal numbers C++ allows the use as literal constants of octal numbers
(base 8) and hexadecimal numbers (base 16). If we want to express an octal number we
have to precede it with a 0 (zero character). And in order to express a hexadecimal
number we have to precede it with the characters 0x (zero, x). For example, the following
literal constants are all equivalent to each other:

75 // decimal

0113 // octal representation of the decimal number 75

0x4b // hexadecimal representation of the decimal number 75

Literal constants, like variables, are considered to have a specific data type. By default,
integer literals are of type int. However, we can force them to either be unsigned by
appending the u character to it, or long by appending l:

75 // int
75u // unsigned int
75l // long
75ul // unsigned long

In both cases, the suffix can be specified using either upper or lowercase letters.

6.6.2 Floating Point Numbers

They express numbers with decimals and/or exponents. They can include either a decimal
point, an e character (that expresses "by ten at the Xth height", where X is an integer
value that follows the e character), or both a decimal point and an e character:

3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0

The default type for floating point literals is double. If you explicitly want to express a
float or long double numerical literal, you can use the f or l suffixes respectively:

84
3.14159L // long double
6.02e23f // float

Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be
written using either lower or uppercase letters without any difference in their meanings.

6.6.3 Character and string literals

There also exist non-numerical constants, like:

'z'
'p'
"Hello world"
"How do you do?"

The first two expressions represent single character constants, and the following two
represent string literals composed of several characters. Notice that to represent a single
character we enclose it between single quotes (') and to express a string (which generally
consists of more than one character) we enclose it between double quotes (").

Character and string literals have certain peculiarities, like the escape codes. These are
special characters that are difficult or impossible to express otherwise in the source code
of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\).
Here you have a list of some of such escape codes:

\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)

String literals can extend to more than a single line of code by putting a backslash sign (\)
at the end of each unfinished line.

"string expressed in \
two lines"

85
6.6.4 Boolean literals

There are only two valid Boolean values: true and false. These can be expressed in C++
as values of type bool by using the Boolean literals true and false.

6.6.5 Defined constants (#define)

You can define your own names for constants that you use very often without having to
resort to memory consuming variables, simply by using the #define preprocessor
directive. Its format is:

#define identifier value

For example:

#define PI 3.14159
#define NEWLINE '\n'

This defines two new constants: PI and NEWLINE. Once they are defined, you can use
them in the rest of the code as if they were any other regular constant, for example:

Program Code Run outputs


// defined constants: calculate circumference 31.4159
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}

The #define directive is not a C++ statement but a directive for the preprocessor;
therefore it assumes the entire line as the directive and does not require a semicolon (;) at
its end. If you append a semicolon character (;) at the end, it will also be appended in all
occurrences within the body of the program that the preprocessor replaces.

86
6.6.6 Declared constants (const)

With the const prefix you can declare constants with a specific type in the same way as
you would do with a variable:

const int pathwidth = 100;


const char tabulator = '\t';

Here, pathwidth and tabulator are two typed constants. They are treated just like regular
variables except that their values cannot be modified after their definition.

6.7 Operators

Once we know of the existence of variables and constants, we can begin to operate with
them. For that purpose, C++ integrates operators. Unlike other languages whose
operators are mainly keywords, operators in C++ are mostly made of signs that are not
part of the alphabet but are available in all keyboards. This makes C++ code shorter and
more international, since it relies less on English words, but requires a little of learning
effort in the beginning. You do not have to memorize all the content of this page. Most
details are only provided to serve as a later reference in case you need it.

6.7.1 Assignment (=)

The assignment operator assigns a value to a variable.

a = 5;

This statement assigns the integer value 5 to the variable a. The part at the left of the
assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue
(right value). The lvalue has to be a variable whereas the rvalue can be either a constant,
a variable, the result of an operation or any combination of these. The most important
rule when assigning is the right-to-left rule: The assignment operation always takes place
from right to left, and never the other way:

a = b;

This statement assigns to variable a (the lvalue) the value contained in variable b (the
rvalue). The value that was stored until this moment in a is not considered at all in this
operation, and in fact that value is lost.

Consider also that we are only assigning the value of b to a at the moment of the
assignment operation. Therefore, a later change of b will not affect the new value of a.

For example, let us have a look at the following code - I have included the evolution of
the content stored in the variables as comments:

87
Program Code Run outputs
// assignment operator a:4 b:7
#include <iostream>
using namespace std;
int main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
return 0;
}

6.7.2 Arithmetic operators ( +, -, *, /, %)

As you have probably gathered by this time, C++ uses the four normal arithmetic
operators +, -, *, and / for addition, subtraction, multiplication, and division. These
operators work on all the data types, both integer and floating-point. They are used in
much the same way that they are used in other languages, and are closely analogous to
their use in algebra. However, there are some other arithmetic operators whose use is not
so obvious. The only one that you might not be so used to see is modulo; whose operator
is the percentage sign (%). Modulo is the operation that gives the remainder of a division
of two values. For example, if we write:

a = 11 % 3;

the variable a will contain the value 2, since 2 is the remainder from dividing 11 between
3.

6.7.3 Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment operators:

88
and the same for all other operators. For example:

Program Code Run outputs


// compound assignment operators 5
#include <iostream>
using namespace std;
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
return 0;
}

6.7.4 Increase and decrease (++, --)

Shortening even more some expressions, the increase operator (++) and the decrease
operator (--) increase or reduce by one the value stored in a variable. They are equivalent
to +=1 and to -=1, respectively. Thus:

c++;

c+=1;

c=c+1;

are all equivalent in its functionality: the three of them increase by one the value of c.

A characteristic of this operator is that it can be used both as a prefix and as a suffix. That
means that it can be written either before the variable identifier (++a) or after it (a++). In
the case that the increase operator is used as a prefix (++a) the value is increased before
the result of the expression is evaluated and therefore the increased value is considered in
the outer expression; in case that it is used as a suffix (a++) the value stored in a is

89
increased after being evaluated and therefore the value stored before the increase
operation is evaluated in the outer expression. Notice the difference:

In Example 1, B is increased before its value is copied to A. While in Example 2, the


value of B is copied to A and then B is increased.

6.7.5 Relational and equality operators ( ==, !=, >, <, >=, <= )

In order to evaluate a comparison between two expressions we can use the relational and
equality operators. The result of a relational operation is a Boolean value that can only be
true or false, according to its Boolean result.

We may want to compare two expressions, for example, to know if they are equal or if
one is greater than the other is. Here is a list of the relational and equality operators that
can be used in C++:

6.7.6 Logical operators ( !, &&, || )

The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only
one operand, located at its right, and the only thing that it does is to inverse the value of
it, producing false if its operand is true and true if its operand is false. Basically, it returns
the opposite Boolean value of evaluating its operand.

The logical operators && and || are used when evaluating two expressions to obtain a
single relational result. The operator && corresponds with Boolean logical operation
AND. The operator || corresponds with Boolean logical operation OR.

6.7.7 Conditional operator ( ? )

The conditional operator evaluates an expression returning a value if that expression is


true and a different one if the expression is evaluated as false. Its format is:

90
condition ? result1 : result2

If condition is true the expression will return result1, if it is not it will return result2.

Program Code Run outputs


// conditional operator 7
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}

6.7.8 Bitwise Operators ( &, |, ^, ~, <<, >> )

Bitwise operators modify variables considering the bit patterns that represent the values
they store.

6.8 Precedence of operators

When writing complex expressions with several operands, we may have some doubts
about which operand is evaluated first and which later. For example, in this expression:

a=5+7%2

we may doubt if it really means:

a = 5 + (7 % 2) // with a result of 6, or

91
a = (5 + 7) % 2 // with a result of 0

The correct answer is the first of the two expressions, with a result of 6. There is an
established order with the priority of each operator, and not only the arithmetic ones
(those whose preference come from mathematics) but for all the operators which can
appear in C++. From greatest to lowest priority, the priority order is as follows:

priority Operator Grouping


Highest () nested expressions evaluated inside out
*, /, % If there are several, then evaluate from left-to-
right
Lowest +, - If there are several, then evaluate from left-to-
right

Grouping defines the precedence order in which operators are evaluated in the case that
there are several operators of the same level in an expression. All these precedence levels
for operators can be manipulated or become more legible by removing possible
ambiguities using parentheses signs. So if you want to write complicated expressions and
you are not completely sure of the precedence levels, always include parentheses. It will
also become a code easier to read.

6.9 Basic Input/Output

C++ uses a convenient abstraction called streams to perform input and output operations
in sequential media such as the screen or the keyboard. A stream is an object where a
program can either insert or extract characters to/from it. We do not really need to care
about many specifications about the physical media associated with the stream - we only
need to know it will accept or provide characters sequentially.

The standard C++ library includes the header file iostream, where the standard input and
output stream objects are declared (cout, cin).

6.9.1 Standard Output (cout)

By default, the standard output of a program is the screen, and the C++ stream object
defined to access it is cout. cout is used in conjunction with the insertion operator, which
is written as << (two "less than" signs).

cout << "Output sentence"; // prints Output sentence on screen


cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

The << operator inserts the data that follows it into the stream preceding it. Notice that
the sentence in the first instruction is enclosed between double quotes (") because it is a

92
constant string of characters. Whenever we want to use constant strings of characters we
must enclose them between double quotes (") so that they can be clearly distinguished
from variable names. For example, these two sentences have very different results:

cout << "Hello"; // prints Hello


cout << Hello; // prints the content of Hello variable

The insertion operator (<<) may be used more than once in a single statement:

cout << "Hello, " << "I am " << "a C++ statement";
This last statement would print the message Hello, I am a C++ statement on the screen.
The utility of repeating the insertion operator (<<) is demonstrated when we want to print
out a combination of variables and constants or more than one variable:

cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;

If we assume the age variable to contain the value 24 and the zipcode variable to contain
90064 the output of the previous statement would be:

Hello, I am 24 years old and my zipcode is 90064

It is important to notice that cout does not add a line break after its output unless we
explicitly indicate it. In order to perform a line break on the output we must explicitly
insert a new-line character into cout. In C++ a new-line character can be specified as \n
(backslash, n):

cout << "First sentence.\n ";


cout << "Second sentence.\nThird sentence.";

This produces the following output:

First sentence.
Second sentence.
Third sentence.

Additionally, to add a new-line, you may also use the endl manipulator. For example:

cout << "First sentence." << endl;


cout << "Second sentence." << endl;

93
would print out:

First sentence.
Second sentence.

6.9.2 Standard Input (cin).

The standard input device is usually the keyboard. Handling the standard input in C++ is
done by applying the overloaded operator of extraction (>>) on the cin stream. The
operator must be followed by the variable that will store the data that is going to be
extracted from the stream. For example:

int age;
cin >> age;

cin can only process the input from the keyboard once the RETURN key has been
pressed. Therefore, even if you request a single character, the extraction from cin will not
process the input until the user presses RETURN after the character has been introduced.

You must always consider the type of the variable that you are using as a container with
cin extractions. If you request an integer you will get an integer, if you request a character
you will get a character and if you request a string of characters you will get a string of
characters.

Program Code Run outputs


// i/o example Please enter an integer value: 702
#include <iostream> The value you entered is 702 and its
using namespace std; double is
int main () 1404.
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}

The user of a program may be one of the factors that generate errors even in the simplest
programs that use cin (like the one we have just seen). Since if you request an integer

94
value and the user introduces a name (which generally is a string of characters), the result
may cause your program to misoperate since it is not what we were expecting from the
user. So when you use the data input provided by cin extractions you will have to trust
that the user of your program will be cooperative and that he/she will not introduce
his/her name or something similar when an integer value is requested. A little ahead,
when we see the stringstream class we will see a possible solution for the errors that can
be caused by this type of user input.

You can also use cin to request more than one datum input from the user:

cin >> a >> b;

is equivalent to:

cin >> a;

cin >> b;

In both cases the user must give two data, one for variable a and another one for variable
b that may be separated by any valid blank separator: a space, a tab character or a
newline.

We can use cin to get strings with the extraction operator (>>) as we do with fundamental
data type variables:

cin >> mystring;

However, as it has been said, cin extraction stops reading as soon as if finds any blank
space character, so in this case we will be able to get just one word for each extraction.
This behavior may or may not be what we want; for example if we want to get a sentence
from the user, this extraction operation would not be useful.

In order to get entire lines, we can use the function getline, which is the more
recommendable way to get user input with cin:

Program Code Run outputs


// cin with strings What's your name? Juan SouliÃ‾¿½
#include <iostream> Hello Juan SouliÃ‾¿½.
#include <string> What is your favorite team? The Isotopes
using namespace std; I like The Isotopes too!
int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);

95
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}

96
QUESTIONS

1. Assuming there are 7.481 gallons in a cubic foot, write a program that asks the user to
enter a number of gallons, and then displays the equivalent in cubic feet.

2. Write a program that generates the following table:

1990 135

1991 7290

1992 11300

1993 16200

Use a single cout statement for all output.

3. Write a program that generates the following output:

10

20

19

Use an integer constant for the 10, an arithmetic assignment operator to generate the 20,
and a decrement operator to generate the 19.

4. Write a program that displays your favorite poem. Use an appropriate escape sequence
for the line breaks. If you don’t have a favorite poem, you can borrow this one by Ogden
Nash:

Candy is dandy,

But liquor is quicker.

5. On a certain day the British pound was equivalent to $1.487 U.S., the French franc was
$0.172, the German deutschemark was $0.584, and the Japanese yen was $0.00955.
Write a program that allows the user to enter an amount in dollars, and then displays this
value converted to these four other monetary units.

6. You can convert temperature from degrees Celsius to degrees Fahrenheit by


multiplying by 9/5 and adding 32. Write a program that allows the user to enter a
floating-point number representing degrees Celsius, and then displays the corresponding
degrees Fahrenheit.

7. If you have two fractions, a/b and c/d, their sum can be obtained from the formula

97
For example, 1/4 plus 2/3 is

Write a program that encourages the user to enter two fractions, and then displays their
sum in fractional form. (You don’t need to reduce it to lowest terms.) The interaction
with the user might look like this:

Enter first fraction: 1/2

Enter second fraction: 2/5

Sum = 9/10

You can take advantage of the fact that the extraction operator (>>) can be chained to
read in more than one quantity at once:

cin >> a >> dummychar >> b;

8. In the heyday of the British empire, Great Britain used a monetary system based on
pounds, shillings, and pence. There were 20 shillings to a pound, and 12 pence to a
shilling. The notation for this old system used the pound sign, £, and two decimal points,
so that, for example, £5.2.8 meant 5 pounds, 2 shillings, and 8 pence. (Pence is the plural
of penny.) The new monetary system, introduced in the 1950s, consists of only pounds
and pence, with 100 pence to a pound (like U.S. dollars and cents). We’ll call this new
system decimal pounds. Thus £5.2.8 in the old notation is £5.13 in decimal pounds
(actually £5.1333333). Write a program to convert the old pounds-shillings-pence format
to decimal pounds. An example of the user’s interaction with the program would be

Enter pounds: 7

Enter shillings: 17

Enter pence: 9

Decimal pounds = £7.89

98
In most compilers you can use the decimal number 156 (hex character constant ‘\x9c’) to
represent the pound sign (£). In some compilers, you can put the pound sign into your
program directly by pasting it from the Windows Character Map accessory.

9. Write the inverse of Exercise 8, so that the user enters an amount in Great Britain’s
new decimal-pounds notation (pounds and pence), and the program converts it to the old
pounds-shillings-pence notation. An example of interaction with the program might be

Enter decimal pounds: 3.51

Equivalent in old notation = £3.10.2.

Make use of the fact that if you assign a floating-point value (say 12.34) to an integer
variable, the decimal fraction (0.34) is lost; the integer value is simply 12. Use a cast to
avoid a compiler warning. You can use statements like

float decpounds; // input from user (new-style pounds)

int pounds; // old-style (integer) pounds

float decfrac; // decimal fraction (smaller than 1.0)

pounds = static_cast<int>(decpounds); // remove decimal fraction

decfrac = decpounds - pounds; // regain decimal fraction

You can then multiply decfrac by 20 to find shillings. A similar operation obtains pence.

99
CHAPTER 7

CONTROL STRUCTURES

100
CHAPTER 7: CONTROL STRUCTURES
Not many programs execute all their statements in strict order from beginning to end.
Most programs (like many humans) decide what to do in response to changing
circumstances. The flow of control jumps from one part of the program to another,
depending on calculations performed in the program. Program statements that cause such
jumps are called control statements. There are two major categories: loops and decisions.

With the introduction of control structures we are going to have to introduce a new
concept: the compound statement or block. A block is a group of statements which are
separated by semicolons (;) like all C++ statements, but grouped together in a block
enclosed in braces: { }:

{ statement1; statement2; statement3; }

Most of the control structures that we will see in this section require a generic statement
as part of its syntax. A statement can be either a simple statement (a simple instruction
ending with a semicolon) or a compound statement (several instructions grouped in a
block), like the one just described. In the case that we want the statement to be a simple
statement, we do not need to enclose it in braces ({}). But in the case that we want the
statement to be a compound statement it must be enclosed between braces ({}), forming a
block.

7.1 Conditional structure: if and else

The if keyword is used to execute a statement or block only if a condition is fulfilled. Its
form is:

if (condition) statement

Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the program
continues right after this conditional structure. For example, the following code fragment
prints x is 100 only if the value stored in the x variable is indeed 100:

if (x == 100)
cout << "x is 100";
If we want more than a single statement to be executed in case that the condition is true
we can specify a block using braces { }:

if (x == 100)
{
cout << "x is ";
cout << x;

101
}

We can additionally specify what we want to happen if the condition is not fulfilled by
using the keyword else. Its form used in conjunction with if is:

if (condition) statement1 else statement2

For example:

if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

The if + else structures can be concatenated with the intention of verifying a range of
values. The following example shows its use telling if the value currently stored in x is
positive, negative or none of them (i.e. zero):

if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

Remember that in case that we want more than a single statement to be executed, we
must group them in a block by enclosing them in braces { }.

7.2 Iteration structures (loops)

Loops cause a section of your program to be repeated a certain number of times. The
repetition continues while a condition is true. When the condition becomes false, the loop
ends and control passes to the statements following the loop.

7.2.1 The while loop

The for loop does something a fixed number of times. What happens if you don’t know
how many times you want to do something before you start the loop? In this case a
different kind of loop may be used: the while loop.

Its format is:

while (expression) statement

102
and its functionality is simply to repeat statement while the condition set in expression is
true. For example, we are going to make a program to countdown using a while-loop:

Program Code Run outputs


// custom countdown using while Enter the starting number > 8
#include <iostream> 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0)
{
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
return 0;
}

When creating a while-loop, we must always consider that it has to end at some point,
therefore we must provide within the block some method to force the condition to
become false at some point, otherwise the loop will continue looping forever. In this case
we have included --n; that decreases the value of the variable that is being evaluated in
the condition (n) by one - this will eventually make the condition (n>0) to become false
after a certain number of loop iterations: to be more specific, when n becomes 0, that is
where our while-loop and our countdown end.

Of course this is such a simple action for our computer that the whole countdown is
performed instantly without any practical delay between numbers.

7.2.2 The do-while loop

In a while loop, the test expression is evaluated at the beginning of the loop. If the test
expression is false when the loop is entered, the loop body won’t be executed at all. In
some situations, this is what you want. But sometimes you want to guarantee that the
loop body is executed at least once, no matter what the initial state of the test expression.
When this is the case you should use the do loop, which places the test expression at the
end of the loop.

Its format is:

103
do statement while (condition);

The following example program echoes any number you enter until you enter 0.

Program Code Run outputs


// number echoer Enter number (0 to end): 12345
#include <iostream> You entered: 12345
using namespace std; Enter number (0 to end): 160277
int main () You entered: 160277
{ Enter number (0 to end): 0
unsigned long n; You entered: 0
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
}
while (n != 0);
return 0;
}

The do-while loop is usually used when the condition that has to determine the end of the
loop is determined within the loop statement itself, like in the previous case, where the
user input within the block is what is used to determine if the loop has to end. In fact, if
you never enter the value 0 in the previous example you can be prompted for more
numbers forever.

7.2.3 The for loop

The for loop is (for many people, anyway) the easiest C++ loop to understand. All its
loop control elements are gathered in one place, while in the other loop constructions
they are scattered about the program, which can make it harder to unravel how these
loops work. The for loop executes a section of code a fixed number of times. It’s usually
(although not always) used when you know, before entering the loop, how many times
you want to execute the code.

Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while
loop. But in addition, the for loop provides specific locations to contain an initialization

104
statement and an increase statement. So this loop is specially designed to perform a
repetitive action with a counter which is initialized and increased on each iteration.

It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a counter


variable. This is executed only once.

2. condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).

3. statement is executed. As usual, it can be either a single statement or a block


enclosed in braces { }.

4. finally, whatever is specified in the increase field is executed and the loop gets
back to step 2.

Here is an example of countdown using a for loop:

Program Code Run outputs


// countdown using a for loop 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

The initialization and increase fields are optional. They can remain empty, but in all cases
the semicolon signs between them must be written. For example we could write: for
(;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if
we wanted to include an increase field but no initialization (maybe because the variable
was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any
of the fields included in a for loop, like in initialization, for example. The comma
operator (,) is an expression separator, it serves to separate more than one expression
where only one is generally expected. For example, suppose that we wanted to initialize
more than one variable in our loop:

105
for ( n=0, i=100 ; n!=i ; n++, i-- )
{
// whatever here...
}

This loop will execute for 50 times if neither n or i are modified within the loop:

n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i).
Because n is increased by one and i decreased by one, the loop's condition will become
false after the 50th loop, when both n and i will be equal to 50.

7.2.4 When to Use Which Loop

The for loop is appropriate when you know in advance how many times the loop will be
executed. The while and do loops are used when you don’t know in advance when the
loop will terminate (the while loop when you may not want to execute the loop body even
once, and the do loop when you’re sure you want to execute the loop body at least once).

Which loop type to use is more a matter of style than of hard-and-fast rules. You can
actually make any of the loop types work in almost any situation. You should choose the
type that makes your program the clearest and easiest to follow.

7.3 Jump statements.

7.3.1 The break statement

Using break we can leave a loop even if the condition for its end is not fulfilled. It can be
used to end an infinite loop, or to force it to end before its natural end. For example, we
are going to stop the count down before its natural end (maybe because of an engine
check failure?)

Program Code Run outputs


// break loop example 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)

106
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}

7.3.2 The continue statement

The continue statement causes the program to skip the rest of the loop in the current
statement block had been reached, causing it to jump to the start of the following
iteration. For example, we are going to skip the number 5 in our countdown:

Program Code Run outputs


// continue loop example 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

7.3.3 The goto statement

goto allows to make an absolute jump to another point in the program. You should use
this feature with caution since its execution causes an unconditional jump ignoring any
type of nesting limitations. The destination point is identified by a label, which is then
used as an argument for the goto statement. A label is made of a valid identifier followed
by a colon (:).

107
Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may find for it. For
example, here is our countdown loop using goto:

Program Code Run outputs


// goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
#include <iostream>
using namespace std;
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
return 0;
}

7.3.4 The exit function

exit is a function defined in the cstdlib library. The purpose of exit is to terminate the
current program with a specific exit code. Its prototype is:

void exit (int exitcode);

The exitcode is used by some operating systems and may be used by calling programs.
By convention, an exit code of 0 means that the program finished normally and any other
value means that some error or unexpected results happened.

7.4 The selective structure: switch.

The syntax of the switch statement is a bit peculiar. Its objective is to check several
possible constant values for an expression. Something similar to what we did at the
beginning of this section with the concatenation of several if and else if instructions. Its
form is the following:

switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;

108
break;
.
.
.
default:
default group of statements
}

It works in the following way: switch evaluates expression and checks if it is equivalent
to constant1, if it is, it executes group of statements 1 until it finds the break statement.
When it finds this break statement the program jumps to the end of the switch selective
structure.

If expression was not equal to constant1 it will be checked against constant2. If it is equal
to this, it will execute group of statements 2 until a break keyword is found, and then will
jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants
(you can include as many case labels as values you want to check), the program will
execute the statements included after the default: label, if it exists (since it is optional).

Both of the following code fragments have the same behavior:

The switch statement is a bit peculiar within the C++ language because it uses labels
instead of blocks. This forces us to put break statements after the group of statements that
we want to be executed for a specific condition. Otherwise the remainder statements -
including those corresponding to other labels- will also be executed until the end of the
switch selective block or a break statement is reached.

109
For example, if we did not include a break statement after the first group for case one, the
program will not automatically jump to the end of the switch selective block and it would
continue executing the rest of statements until it reaches either a break instruction or the
end of the switch selective block. This makes unnecessary to include braces { }
surrounding the statements for each of the cases, and it can also be useful to execute the
same block of instructions for different possible values for the expression being
evaluated. For example:

switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}
Notice that switch can only be used to compare an expression against constants.
Therefore we cannot put variables as labels (for example case n: where n is a variable) or
ranges (case (1..3):) because they are not valid C++ constants.

If you need to check ranges or values that are not constants, use a concatenation of if and
else if statements.

110
QUESTIONS

1. A relational operator

a. assigns one operand to another.


b. yields a Boolean result.
c. compares two operands.
d. logically combines two operands.
2. Write an expression that uses a relational operator to return true if the variable george
is not equal to sally.

3. Is –1 true or false?

4. Name and describe the usual purpose of three expressions in a for statement.

5. In a for loop with a multi statement loop body, semicolons should appear following

a. the for statement itself.


b. the closing brace in a multi statement loop body.
c. each statement within the loop body.
d. the test expression.
6. True or false: The increment expression in a for loop can decrement the loop variable.

7. Write a for loop that displays the numbers from 100 to 110.

8. A block of code is delimited by ________________.

9. A variable defined within a block is visible

a. from the point of definition onward in the program.


b. from the point of definition onward in the function.
c. from the point of definition onward in the block.
d. throughout the function.
10. Write a while loop that displays the numbers from 100 to 110.

11. True or false: Relational operators have a higher precedence than arithmetic
operators.

12. How many times is the loop body executed in a do loop?

13. Write a do loop that displays the numbers from 100 to 110.

14. Write an if statement that prints Yes if a variable age is greater than 21.

15. The library function exit() causes an exit from

a. the loop in which it occurs.


b. the block in which it occurs.

111
c. the function in which it occurs.
d. the program in which it occurs.
16. Write an if...else statement that displays Yes if a variable age is greater than 21, and
displays No otherwise.

17. What is the character obtained from cin when the user presses the Enter key?

18. An else always matches the _________ if, unless the if is _________.

19. The else...if construction is obtained from a nested if...else by ________________.

20. Write a switch statement that prints Yes if a variable ch is ‘y’, prints No if ch is ‘n’,
and prints Unknown response otherwise.

21. Write a statement that uses a conditional operator to set ticket to 1 if speed is greater
than 55, and to 0 otherwise.

22. The && and || operators

a. compare two numeric values.


b. combine two numeric values.
c. compare two Boolean values.
d. combine two Boolean values.
23. Write an expression involving a logical operator that is true if limit is 55 and speed is
greater than 55.

24. Arrange in order of precedence (highest first) the following kinds of operators:
logical, unary, arithmetic, assignment, relational, conditional.

25. The break statement causes an exit

a. only from the innermost loop.


b. only from the innermost switch.
c. from all loops and switches.
d. from the innermost loop or switch.
26. Executing the continue operator from within a loop causes control to go to ________.

27. The goto statement causes control to go to

a. an operator.
b. a label.
c. a variable.
d. a function.
28. Assume that you want to generate a table of multiples of any given number. Write a
program that allows the user to enter the number and then generates the table, formatting
it into 10 columns and 20 lines. Interaction with the program should look like this (only
the first three lines are shown):

112
Enter a number: 7

29. Write a temperature-conversion program that gives the user the option of converting
Fahrenheit to Celsius or Celsius to Fahrenheit. Then carry out the conversion. Use
floating-point numbers. Interaction with the program might look like this:

Type 1 to convert Fahrenheit to Celsius,

2 to convert Celsius to Fahrenheit: 1

Enter temperature in Fahrenheit: 70

In Celsius that’s 21.111111

30. Create the equivalent of a four-function calculator. The program should ask the user
to enter a number, an operator, and another number. (Use floating point.) It should then
carry out the specified arithmetical operation: adding, subtracting, multiplying, or
dividing the two numbers. Use a switch statement to select the operation. Finally, display
the result.

When it finishes the calculation, the program should ask whether the user wants to do
another calculation. The response can be ‘y’ or ‘n’. Some sample interaction with the
program might look like this:

Enter first number, operator, second number: 10 / 3


Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n

31. Use for loops to construct a program that displays a pyramid of Xs on the screen. The
pyramid should look like this

X
XXX
XXXXX
XXXXXXX
XXXXXXXXX

113
except that it should be 20 lines high, instead of the 5 lines shown here. One way to do
this is to nest two inner loops, one to print spaces and one to print Xs, inside an outer
loop that steps down the screen from line to line.

32. Modify the FACTOR program in this chapter so that it repeatedly asks for a number
and calculates its factorial, until the user enters 0, at which point it terminates. You can
enclose the relevant statements in FACTOR in a while loop or a do loop to achieve this
effect.

33. Write a program that calculates how much money you’ll end up with if you invest an
amount of money at a fixed interest rate, compounded yearly. Have the user furnish the
initial amount, the number of years, and the yearly interest rate in percent. Some
interaction with the program might look like this:

Enter initial amount: 3000


Enter number of years: 10
Enter interest rate (percent per year): 5.5
At the end of 10 years, you will have 5124.43 dollars.

At the end of the first year you have 3000 + (3000 * 0.055), which is 3165. At the end of
the second year you have 3165 + (3165 * 0.055), which is 3339.08. Do this as many
times as there are years. A for loop makes the calculation easy.

34. Suppose you give a dinner party for six guests, but your table seats only four. In how
many ways can four of the six guests arrange themselves at the table? Any of the six
guests can sit in the first chair. Any of the remaining five can sit in the second chair. Any
of the remaining four can sit in the third chair, and any of the remaining three can sit in
the fourth chair. (The last two will have to stand.) So the number of possible
arrangements of six guests in four chairs is 6*5*4*3, which is 360. Write a program that
calculates the number of possible arrangements for any number of guests and any number
of chairs. (Assume there will never be fewer guests than chairs.) Don’t let this get too
complicated. A simple for loop should do it.

35. Write another version of the program from Exercise 6 so that, instead of finding the
final amount of your investment, you tell the program the final amount and it figures out
how many years it will take, at a fixed rate of interest compounded yearly, to reach this
amount. What sort of loop is appropriate for this problem? (Don’t worry about fractional
years; use an integer value for the year.)

114
CHAPTER 8

FUNCTIUONS

115
CHAPTER 8: FUNCTIUONS
8.1 INTRODUCTION

A function groups a number of program statements into a unit and gives it a name. This
unit can then be invoked from other parts of the program.

The most important reason to use functions is to aid in the conceptual organization of a
program. Dividing a program into functions is one of the major principles of structured
programming. (However, object-oriented programming provides additional, more
powerful ways to organize programs.)

Another reason to use functions (and the reason they were invented, long ago) is to
reduce program size. Any sequence of instructions that appears in a program more than
once is a candidate for being made into a function. The function’s code is stored in only
one place in memory, even though the function is executed many times in the course of
the program.

The function format is as following:

type name ( parameter1, parameter2, ...) { statements }

where:

• type is the data type specifier of the data returned by the function.
• name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data type specifier
followed by an identifier, like any regular variable declaration (for example: int x)
and which acts within the function as a regular local variable. They allow to pass
arguments to the function when it is called. The different parameters are separated
by commas.
• statements is the function's body. It is a block of statements surrounded by braces
{ }.

Here you have the first function example:

Program Code Run outputs


// function example The result is 8
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;

116
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}

Scope of variables

The scope of variables declared within a function or any other inner block is only their
own function or their own block and cannot be used outside of them. For example, in the
previous example it would have been impossible to use the variables a, b or r directly in
function main since they were variables local to function addition. Also, it would have
been impossible to use the variable z directly within function addition, since this was a
variable local to the function main.

8.2 The Function Declaration

Just as you can’t use a variable without first telling the compiler what it is, you also can’t
use a function without telling the compiler about it. There are two ways to do this. The
approach we show here is to declare the function before it is called. (The other approach
is to define it before it’s called; we’ll examine that next.).

The function starline() is declared in the line

void starline();

The declaration tells the compiler that at some later point we plan to present a function
called starline. The keyword void specifies that the function has no return value, and the
empty parentheses indicate that it takes no arguments. We’ll have more to say about
arguments and return values soon.

Notice that the function declaration is terminated with a semicolon. It is a complete


statement in itself.

8.3 Calling the Function

Here is another example about functions:

Program Code Run outputs

117
// function example The first result is 5
#include <iostream> The second result is 5
using namespace std; The third result is 2
int subtraction (int a, int b) The fourth result is 6
{
int r;
r=a-b;
return (r);
}
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) << '\n';
cout << "The third result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
return 0;
}

Nevertheless, if we examine function main we will see that we have made several calls to
function subtraction. We have used some different calling methods so that you see other
ways or moments when a function can be called.

In order to fully understand these examples you must consider once again that a call to a
function could be replaced by the value that the function call itself is going to return. For
example, the first case (that you should already know because it is the same pattern that
we have used in previous examples):

z = subtraction (7,2);
cout << "The first result is " << z;

If we replace the function call by the value it returns (i.e., 5), we would have:

z = 5;
cout << "The first result is " << z;

As well as

cout << "The second result is " << subtraction (7,2);

118
has the same result as the previous call, but in this case, we made the call to subtraction
directly as an insertion parameter for cout. Simply consider that the result is the same as
if we had written:

cout << "The second result is " << 5;

since 5 is the value returned by subtraction (7,2).

In the case of:

cout << "The third result is " << subtraction (x,y);

The only new thing that we introduced is that the parameters of subtraction are variables
instead of constants. That is perfectly valid. In this case the values passed to function
subtraction are the values of x and y, that are 5 and 3 respectively, giving 2 as result.

The fourth case is more of the same. Simply note that instead of:

z = 4 + subtraction (x,y);

we could have written:

z = subtraction (x,y) + 4;

with exactly the same result. I have switched places so you can see that the semicolon
sign (;) goes at the end of the whole statement. It does not necessarily have to go right
after the function call. The explanation might be once again that you imagine that a
function can be replaced by its returned value:

z = 4 + 2;

z = 2 + 4;

8.4 Passing Arguments to Functions

An argument is a piece of data (an int value, for example) passed from a program to the
function. Arguments allow a function to operate with different values, or even to do
different things, depending on the requirements of the program calling it.

119
When calling a function with parameters, what we have passed to the function were
copies of their values but never the variables themselves.

For example, suppose that we called our first function addition using the following code:

int x=5, y=3, z;


z = addition ( x , y );

What we did in this case was to call to function addition passing the values of x and y, i.e.
5 and 3 respectively, but not the variables x and y themselves.

Int addition(int a, int b);

z = addition ( 5 , 3 );

This way, when the function addition is called, the value of its local variables a and b
become 5 and 3 respectively, but any modification to either a or b within the function
addition will not have any effect in the values of x and y outside it, because variables x
and y were not themselves passed to the function, but only copies of their values at the
moment the function was called.

But there might be some cases where you need to manipulate from inside a function the
value of an external variable. For that purpose, we can use arguments passed by
reference, as in the function duplicate of the following example:

Program Code Run outputs


/ passing parameters by reference x=2, y=6, z=14
#include <iostream>
using namespace std;
void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;

120
}

The first thing that should call your attention is that in the declaration of duplicate the
type of each parameter was followed by an ampersand sign (&). This ampersand is what
specifies that their corresponding arguments are to be passed by reference instead of by
value.

When a variable is passed by reference we are not passing a copy of its value, but we are
somehow passing the variable itself to the function and any modification that we do to
the local variables will have an effect in their counterpart variables passed as arguments
in the call to the function.

Passing by reference is also an effective way to allow a function to return more than one
value. For example, here is a function that returns the previous and next numbers of the
first parameter passed.

Program Code Run outputs


// more than one returning value Previous=99, Next=101
#include <iostream>
using namespace std;
void prevnext (int x, int& prev, int& next)
{
prev = x-1;
next = x+1;
}
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}

8.5 Default values in parameters.

When declaring a function we can specify a default value for each of the last parameters.
This value will be used if the corresponding argument is left blank when calling to the
function. To do that, we simply have to use the assignment operator and a value for the
arguments in the function declaration. If a value for that parameter is not passed when the
function is called, the default value is used, but if a value is specified this default value is
ignored and the passed value is used instead. For example:

121
Program Code Run outputs
// default values in functions 6
#include <iostream> 5
using namespace std;
int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}
int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}

As we can see in the body of the program there are two calls to function divide. In the
first one:

divide (12)

we have only specified one argument, but the function divide allows up to two. So the
function divide has assumed that the second parameter is 2 since that is what we have
specified to happen if this parameter was not passed (notice the function declaration,
which finishes with int b=2, not just int b). Therefore the result of this function call is 6
(12/2).

In the second call:

divide (20,4)

there are two parameters, so the default value for b (int b=2) is ignored and b takes the
value passed as argument, that is 4, making the result returned equal to 5 (20/4).

8.6 Overloaded functions.

In C++ two different functions can have the same name if their parameter types or
number are different. That means that you can give the same name to more than one
function if they have either a different number of parameters or different types in their
parameters. For example:

Program Code Run outputs

122
// overloaded function 10
#include <iostream> 2.5
using namespace std;
int operate (int a, int b)
{
return (a*b);
}
float operate (float a, float b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
}

Notice that a function cannot be overloaded only by its return type. At least one of its
parameters must have a different type.

123
QUESTIONS

1. A function’s single most important role is to

a. give a name to a block of code.


b. reduce program size.
c. accept arguments and provide a return value.
d. help organize a program into conceptual units.
2. A function itself is called the function d_________.

3. Write a function called foo() that displays the word foo.

4. A one-statement description of a function is referred to as a function d_________ or a


p_________.

5. The statements that carry out the work of the function constitute the function
_________.

6. A program statement that invokes a function is a function _________.

7. The first line of a function definition is referred to as the _________.

8. A function argument is

a. a variable in the function that receives a value from the calling program.
b. a way that functions resist accepting the calling program’s values.
c. a value sent to the function by the calling program.
d. a value returned by the function to the calling program.
9. True or false: When arguments are passed by value, the function works with the
original arguments in the calling program.

10. What is the purpose of using argument names in a function declaration?

11. Which of the following can legitimately be passed to a function?

a. A constant
b. A variable
c. A structure
d. A header file
12. What is the significance of empty parentheses in a function declaration?

13. How many values can be returned from a function?

14. True or false: When a function returns a value, the entire function call can appear on
the right side of the equal sign and be assigned to another variable.

15. Where is a function’s return type specified?

124
16. A function that doesn’t return anything has return type _________.

17. Here’s a function:

int times2(int a)
{
return (a*2);
}
Write a main() program that includes everything necessary to call this function.

18. When an argument is passed by reference

a. a variable is created in the function to hold the argument’s value.


b. the function cannot access the argument’s value.
c. a temporary variable is created in the calling program to hold the argument’s
value.
d. the function accesses the argument’s original value in the calling program.
19. What is a principal reason for passing arguments by reference?

20. Overloaded functions

a. are a group of functions with the same name.


b. all have the same number and types of arguments.
c. make life simpler for programmers.
d. may fail unexpectedly due to stress.
21. Write declarations for two overloaded functions named bar(). They both return type
int. The first takes one argument of type char, and the second takes two arguments of type
char. If this is impossible, say why.

22. A default argument has a value that

a. may be supplied by the calling program.


b. may be supplied by the function.
c. must have a constant value.
d. must have a variable value.
23. Write a declaration for a function called blyth() that takes two arguments and returns
type char. The first argument is type int, and the second is type float with a default value
of 3.14159.

24. Write a function called circarea() that finds the area of a circle. It should take an
argument of type float and return an argument of the same type. Write a main() function
that gets a radius value from the user, calls circarea(), and displays the result.

25. Raising a number n to a power p is the same as multiplying n by itself p times. Write
a function called power() that takes a double value for n and an int value for p, and
returns the result as a double value. Use a default argument of 2 for p, so that if this

125
argument is omitted, the number n will be squared. Write a main() function that gets
values from the user to test this function.

26. Write a function called zeroSmaller() that is passed two int arguments by reference
and then sets the smaller of the two numbers to 0. Write a main() program to exercise this
function.

27. Write a function that takes two Distance values as arguments and returns the larger
one. Include a main() program that accepts two Distance values from the user, compares
them, and displays the larger.

28. Write a function called hms_to_secs() that takes three int values—for hours, minutes,
and seconds—as arguments, and returns the equivalent time in seconds (type long).
Create a program that exercises this function by repeatedly obtaining a time value in
hours, minutes, and seconds from the user (format 12:59:59), calling the function, and
displaying the value of seconds it returns.

29. Start with the power() function of Exercise 2, which works only with type double.
Create a series of overloaded functions with the same name that, in addition to double,
also work with types char, int, long, and float. Write a main() program that exercises
these overloaded functions with all argument types.

30. Write a function called swap() that interchanges two int values passed to it by the
calling program. (Note that this function swaps the values of the variables in the calling
program, not those in the function.) You’ll need to decide how to pass the arguments.
Create a main() program to exercise the function.

31. Write a function that, when you call it, displays a message telling how many times it
has been called: “I have been called 3 times”, for instance. Write a main() program that
calls this function at least 10 times. Try implementing this function in two different ways.
First, use a global variable to store the count. Second, use a local static variable. Which is
more appropriate? Why can’t you use a local variable?

126
CHAPTER 9

ARRAYS

127
CHAPTER 9: ARRAYS
9.1 INTRODUCTION

Arrays are used to store a collection of variables all of the same type placed in contiguous
memory locations that can be individually referenced by adding an index to a unique
identifier. That means that, for example, we can store 5 values of type int in an array
without having to declare 5 different variables, each one with a different identifier.
Instead of that, using an array we can store 5 different values of the same type, int for
example, with a unique identifier.

For example, an array to contain 5 integer values of type int called billy could be
represented like this:

where each blank panel represents an element of the array, that in this case are integer
values of type int. These elements are numbered from 0 to 4 since in arrays the first index
is always 0, independently of its length.

Like a regular variable, an array must be declared before it is used. A typical declaration
for an array in C++ is:

type name [elements];

where type is a valid type (like int, float...), name is a valid identifier and the elements
field (which is always enclosed in square brackets []), specifies how many of these
elements the array has to contain.

Therefore, in order to declare an array called billy as the one shown in the above diagram
it is as simple as:

int billy [5];

NOTE: The elements field within brackets [] which represents the number of elements
the array is going to hold, must be a constant value, since arrays are blocks of non-
dynamic memory whose size must be determined before execution.

9.2 Initializing arrays.

When declaring a regular array of local scope (within a function, for example), if we do
not specify otherwise, its elements will not be initialized to any value by default, so their
content will be undetermined until we store some value in them. The elements of global

128
and static arrays, on the other hand, are automatically initialized with their default values,
which for all fundamental types this means they are filled with zeros.

In both cases, local and global, when we declare an array, we have the possibility to
assign initial values to each one of its elements by enclosing the values in braces { }. For
example:

int billy [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:

The amount of values between braces { } must not be larger than the number of elements
that we declare for the array between square brackets [ ]. For example, in the example of
array billy we have declared that it has 5 elements and in the list of initial values within
braces { } we have specified 5 values, one for each element.

When an initialization of values is provided for an array, C++ allows the possibility of
leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the
array that matches the number of values included between braces { }:

int billy [] = { 16, 2, 77, 40, 12071 };

After this declaration, array billy would be 5 ints long, since we have provided 5
initialization values.

9.3 Accessing the values of an array.

In any point of a program in which an array is visible, we can access the value of any of
its elements individually as if it was a normal variable, thus being able to both read and
modify its value. The format is as simple as:

name[index]

Following the previous examples in which billy had 5 elements and each of those
elements was of type int, the name which we can use to refer to each element is the
following:

129
For example, to store the value 75 in the third element of billy, we could write the
following statement:

billy[2] = 75;

and, for example, to pass the value of the third element of billy to a variable called a, we
could write:

a = billy[2];

Therefore, the expression billy[2] is for all purposes like a variable of type int.

Notice that the third element of billy is specified billy[2], since the first one is billy[0],
the second one is billy[1], and therefore, the third one is billy[2]. By this same reason, its
last element is billy[4]. Therefore, if we write billy[5], we would be accessing the sixth
element of billy and therefore exceeding the size of the array.

In C++ it is syntactically correct to exceed the valid range of indices for an array. This
can create problems, since accessing out-of-range elements do not cause compilation
errors but can cause runtime errors.

Here is an example of using array:

Program Code Run outputs


// arrays example 12206
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}

9.4 Multidimensional arrays

Multidimensional arrays can be described as "arrays of arrays". For example, a


bidimensional array can be imagined as a bidimensional table made of elements, all of
them of a same uniform data type.

130
jimmy represents a bidimensional array of 3 per 5 elements of type int. The way to
declare this array in C++ would be:

int jimmy [3][5];

and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:

jimmy[1][3]

Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can
contain as many indices as needed. But be careful! The amount of memory needed for an
array rapidly increases with each dimension. For example:

char century [100][365][24][60][60];

Take as example these two pieces of code, with both exactly the same result. One uses a
bidimensional array and the other one uses a simple array:

9.5 Arrays as parameters

At some moment we may need to pass an array to a function as a parameter. In C++ it is


not possible to pass a complete block of memory by value as a parameter to a function,
but we are allowed to pass its address. In practice this has almost the same effect and it is

131
a much faster and more efficient operation. In order to accept arrays as parameters the
only thing that we have to do when declaring the function is to specify in its parameters
the element type of the array, an identifier and a pair of void brackets []. For example, the
following function:

void procedure (int arg[])

accepts a parameter of type "array of int" called arg. In order to pass to this function an
array declared as:

int myarray [40];

it would be enough to write a call like this:

procedure (myarray);

Here you have a complete example:

Program Code Run outputs


// arrays as parameters 5 10 15
#include <iostream> 2 4 6 8 10
using namespace std;
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n";
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}

As you can see, the first parameter (int arg[]) accepts any array whose elements are of
type int, whatever its length. For that reason we have included a second parameter that
tells the function the length of each array that we pass to it as its first parameter. This
allows the for loop that prints out the array to know the range to iterate in the passed
array without going out of range.

132
9.6 Character Sequences

As you may already know, the C++ Standard Library implements a powerful string class,
which is very useful to handle and manipulate strings of characters. However, because
strings are in fact sequences of characters, we can represent them also as plain arrays of
char elements. For example, the following array:

char jenny [20];

is an array that can store up to 20 elements of type char. Therefore, in this array, in
theory, we can store sequences of characters up to 20 characters long. But we can also
store shorter sequences. For example, jenny could store at some point in a program either
the sequence "Hello" or the sequence "Merry christmas", since both are shorter than 20
characters. Therefore, since the array of characters can store shorter sequences than its
total length, a special character is used to signal the end of the valid sequence: the null
character, whose literal constant can be written as '\0' (backslash, zero).

Our array of 20 elements of type char, called jenny, can be represented storing the
characters sequences "Hello" and "Merry Christmas" as:

Notice how after the valid content a null character ('\0') has been included in order to
indicate the end of the sequence. The panels in gray color represent char elements with
undetermined values.

133
QUESTIONS

1. An array element is accessed using

a. a first-in-first-out approach.
b. the dot operator.
c. a member name.
d. an index number.
2. All the elements in an array must be the _________ data type.

3. Write a statement that defines a one-dimensional array called doubleArray of type


double that holds 100 elements.

4. The elements of a 10-element array are numbered from ________ to ________.

5. Write a statement that takes element j of array doubleArray and writes it to cout with
the insertion operator.

6. Element doubleArray[7] is which element of the array?

a. The sixth
b. The seventh
c. The eighth
d. Impossible to tell
7. Write a statement that defines an array coins of type int and initializes it to the values
of the penny, nickel, dime, quarter, half-dollar, and dollar.

8. When a multidimensional array is accessed, each array index is

a. separated by commas.
b. surrounded by brackets and separated by commas.
c. separated by commas and surrounded by brackets.
d. surrounded by brackets.
9. Write an expression that accesses element 4 in subarray 2 in a two-dimensional
arraycalled twoD.

10. True or false: In C++ there can be an array of four dimensions.

11. For a two-dimensional array of type float, called flarr, write a statement that declares
the array and initializes the first subarray to 52, 27, 83; the second to 94, 73, 49; and the
third to 3, 6, 1.

12. An array name, used in the source file, represents the ________ of the array.

13. When an array name is passed to a function, the function

a. accesses exactly the same array as the calling program.


b. accesses a copy of the array passed by the program.

134
c. refers to the array using the same name as that used by the calling program.
d. refers to the array using a different name than that used by the calling
program.
14. Tell what this statement defines:

employee emplist[1000];

15. Write a statement that defines an array called manybirds that holds 50 objects of type
bird.

16. True or false: The compiler will complain if you try to access array element 14 in a
10-element array.

17. A string in C++ is an _________ of type _________.

18. Write a statement that defines a string variable called city that can hold a string of up
to 20 characters (this is slightly tricky).

19. Write a statement that defines a string constant, called dextrose, that has the value
“C6H12O6-H2O”.

20. True or false: The extraction operator (>>) stops reading a string when it encounters a
space.

21. You can read input that consists of multiple lines of text using

a. the normal cout << combination.


b. the cin.get() function with one argument.
c. the cin.get() function with two arguments.
d. the cin.get() function with three arguments.
25. Write a statement that uses a string library function to copy the string name to the
string blank.

26. Write a function called reversit() that reverses a C-string (an array of char). Use a for
loop that swaps the first and last characters, then the second and next-to-last characters,
and so on. The string should be passed to reversit() as an argument. Write a program to
exercise reversit(). The program should get a string from the user, call reversit(), and
print out the result. Use an input method that allows embedded blanks. Test the program
with Napoleon’s famous phrase, “Able was I ere I saw Elba.”

27. Start with a program that allows the user to input a number of integers, and then
stores them in an int array. Write a function called maxint() that goes through the array,
element by element, looking for the largest one. The function should take as arguments
the address of the array and the number of elements in it, and return the index number of
the largest element. The program should call this function and then display the largest
element and its index number.

135

You might also like