Introduction to Programming I
Introduction to Programming I
Chapter One
Introduction and Programming Basics
I. Basics of computers
Computer is an electronic device, operating under the control of instructions called programs .It
is a device which can accept data, manipulate the data according to specified rules, produce
information from the processing, and store the results for future use.
Characteristics of computers
Speed: - computers can calculate at very high speed. Their speed is measured in
milliseconds, microseconds, nanoseconds
Accuracy: errors in computing (data processing) is mostly due to human factor
Storage:-can store large amount of data
Versatility: can be programmed and applied for different purposes
Diligence:-can handle very routine and repetitive tasks
Information and data processing
Data is a collection of raw facts used to generate information.
Hence information can be defined as data that has been transformed into a meaningful and useful
context for specific end users .i.e. It is a refined or processed data.
Data processing is the manipulation of data into a more useful form (information).
Hence to produce information raw data is collected, the collected data is processed, output is
produced and the output is transmitted to concerned users
Data processing has a cycle consists of three parts
Input Process Output
Data processing consists of a number of operations like Recording, duplicating verifying data,
classifying data, sorting, storing, merging, retrieving, calculating data, summarizing and reporting.
Data processing can be performed manually, mechanically, or electrically
Getaneh.T[UU] Page 1
Introduction To Computer And Programming
Computer hardware is
- a physical part of a computer
- a part we can see and touch
- composed of a number of electronic and electromechanical parts, which interact with each other
to perform a given task
- the different parts are interrelated by a cable like device called Bus , which is used to facilitate
communication between parts
Computer is in general does is it takes an input in various forms, it process the input
according to a given set of instructions and produces an output in various forms.
The different hardware parts of a computer which are responsible for this operation are illustrated
by the following diagram
Getaneh.T[UU] Page 2
Introduction To Computer And Programming
- fetch data : the execution of instruction may required reading of data from memory or input
devices
- to process data : the execution of instruction may require performing arithmetic or logic
operations on the data .
- write data : the result of execution may require writing a data to memory or output devices
Registers
- they are memories , when an instruction loaded from memory it is placed first in the register,
to wait signal from the control unit and data also placed in register prior to execution in the ALU .
Storage Devices
Storage Devices: there are two types of storages primary/main storage (memories) and
secondary/Auxiliary storages (memory)
Primary storages are of two types RAM and ROM
Getaneh.T[UU] Page 3
Introduction To Computer And Programming
ROM
- it referred to read only memory
- it provides permanent storage
- ROM in a PC contains a basic set of instructions, called the basic input output system (BIOS).
the PC uses the BIOS to start up the OS
- data can be read from ROM , but can’t be written on ROM
Note nowadays there is erasable ROM like EPROM (Erasable programmable ROM)
- are normally used to store information that are the computer the computer may need frequently
for its own operations
Secondary Storage (Auxiliary storages)
Since RAM is expensive and volatile it is not possible to store data permanently, hence we
need other storage devices secondary storages.
There are two types of secondary storages magnetic storage and optical storage.
Getaneh.T[UU] Page 4
Introduction To Computer And Programming
- it has an advantage of being able to hold enormous amount of data :for this reason it is used to
store information on the largest computer systems
- is sequential access media
- data access time is slow compared to other forms of storage media
Magnetic drum
- it is a metallic cylinder ranging from few inches to a few feet s coated with a special magnetic
alloy
- data is recorded as magnetic spots arranged in binary form
- data is recorded by read /write head and one for each truck
- magnetic drum provides random access for selecting a truck but once the truck is identified , the
information is recorded sequentially
Magnetic disks
Hard Disk
- it is a random access media i.e. it permits direct addressing of data location
- consists of one or more metal plates coated with ferric oxide
- the circular platters sealed in a metal box with associated read/ write heads
- a data is recorded in the form of magnetic spot on the platters
a spot presence indicate a 1’s and its absence indicate a 0
- it remains in the system unit it is removed when damaged or when you want to upgrade it with
a larger capacity
- the surface of a magnetic disk is divided into a number invisible concentric circles called truck.
The truck further subdivided into sectors (blocks). each block or sector have a unique address
- it is possible to read or write a block of data at a time
Floppy Disk
- is a portable(removable ) , inexpensive storage medium
- Consists of a thin, circular, flexible plastic disk with a magnetic coating enclosed in a square –
shaped plastic shell, the disk jacket.
- has different sizes 5 ¼ and 3 ½
- use magnetic patterns to store items
- possible to access data and write data on a magnetic disk any number of times
- They must be inserted into a compatible disk drive in order to be read from or written to.
Getaneh.T[UU] Page 5
Introduction To Computer And Programming
Optical storage
Optical storage devices use the principle of light rather than magnetism to store information
CD-ROM (Compact Disk Read Only Memory)
- it is optical storage media
- it is possible to read from the disk but you can’t write onto it
- is a rigid plastic disk that store s a large amount of data through the use of laser optic
technology
- since CD-ROM store data optically ,they have much higher memory capacity than disks that
store data magnetically
- its underside is coated with a very thin layer of aluminum that reflects light
- data is written to the CD-ROM is by burning microscopic pits into the reflective surface of the
disk with powerful laser
DVD -ROMs (digital video disc-ROM)
- is a very high capacity compact disk
- is used to store large amount of data even videos
Input devices
Input devices are
- Parts of the computer hardware that are used to convert data or information into electronic
machine readable form
- used to gather data for the microprocessor so that it can be processed
Examples of input devices
Keyboard, mouse, image scanner, disk drives, microphone etc.
1. Keyboard
- is an input device with buttons or keys that the user presses to enter data characters and
commands into a computer
- is most widely used input device
Keyboard contain the letters of the alphabet, numbers and frequently used symbols like
$,%,& etc..
The size of the keyboard depends on the number of keys that are included in the keyboard
Getaneh.T[UU] Page 6
Introduction To Computer And Programming
The normal PC keyboard includes 105 keys .These keys can be divided in to five sections
1. Typing keys:- These keys work just like conventional type writer. These keys include
Alphabet A-Z, digits 0-9, the Enter key, Space, the Back space, the Shift key etc
2. Numeric keypad
Is used to enter numeric data more easily when you are working number intensive tasks. Num
lock is used to switch the light of numeric keypad to use the pad.
3. Function keys
There are 12 function keys labeled F1 to F12 arranged at the top .when any of the keys is
pressed, it performs a certain task. For instance, in many programs F1 is pressed to display
help information.
4. Navigation keys
These are keys that are used to navigate (move) through your document.
5. Computer keys
These are not found on typewriter.
They are performs different tasks when used alone or in conjunction with other keys.
Example: Esc, Alt, Ctrl, print screen Insert etc
2. Mouse
- is the pointing device that is used to move the insertion point around the screen.
- is an inverted trackball device that has a number of selection buttons associated with it
- the hand moves it across a flat surface , and its position is displayed on the screen
- the buttons are used to select items and make choices on the screen
3. Image scanner
Is used to input images and words directly into a computer using a visible light or electromagnetic
radiation like laser. Is image processing device.
Image processing is an activity of converting visual information into a format that can be managed
with in a computer system.
There are two types of scanners flatbed scanner and handheld scanner
Flat scanner: - which is similar to an office photocopier
A hand held scanner, is a scanner passed manually across the image to be processed.
Getaneh.T[UU] Page 7
Introduction To Computer And Programming
4. Disk drives
Disk drives are devices that input data from the storage devices for further processing
Examples hard disk drives and floppy disk drives
5. Microphone
Microphone converts sound into signals that can be stored, manipulated and played by the
computer.
is used to gather information to the computer when the computer is a multi media system .a
computer is said to be a multimedia system if it processes multiple types of information ( such as text
, images and voices ) simultaneously.
Output devices
Out put hardware consists of external devices that used to get information (data) out of a computer’s
CPU to the computer user so that it can be examined, analyzed, or distributed to others
These are devices that are used to display the processed information to the user either in Soft copy of
hard copy
- Soft copy: is temporary output such as that produced by a monitor (unprinted copy / document)
- Hard copy: permanent output such as that produced by a printer (printed copy / document )
- Outputs convert the result of processing to a form that is easy to understand by human beings.
- Examples of output devices Monitor (screen), printers, overhead projectors, (LCD), disk drives
,speakers etc..
Monitor (screen)
- Converts information gathered by then computer into visual information.
- It looks like a television screen
- Is the most widely used output device
- It displays the output of the processing activity for the user
- The monitor (screen) attached to the computer gives the user feedback while the user types a
character from the keyboard
- It is used to display both text and graphics data
Getaneh.T[UU] Page 8
Introduction To Computer And Programming
LCD projector
LCD projector is an output device used for displaying the output of the computer into a large
screen, mostly used in conferences and class room for presentations.
Printer
- Printer produces a permanent hardcopy output from the computer by converting digital information
into marks on a paper
A printer allows the user to print out on paper a copy of the screen or the data that is being
processed by the computer
- Printers are available in both color and black and white. color printers are slower and more
expensive than black and white printers
- Printers can be categorized into impact and non impact
Impact printers
Impact printers are printers which are physically strike the paper. i.e. the paper and the
characters being printed come in contact with one another .
Impact printers has hammering parts, hence printing is noisy.
Examples of impact printers are Dot matrix, line and character printers
Dot matrix printer: is most common and versatile. The character it prints consists of dots
arranged in a pattern. It is possible to print graphics images and variety of type styles.
Wire rods pushed against a ribbon and paper form the characters.
The quality of output from a dot matrix printer depends largely on the number of dots in the
matrix .dot matrix printers are low cost and they are also simple to use.
Non-impact printers
These printers do not physically strike papers. One advantage of these printers is that it can
print higher quality text and graphics than impact printers. Here the characters of the print
material are produced on the paper through a heat, chemical or spraying process
Examples are laser printers and ink jet printers
Laser printers
Laser printers are the best, the most expensive and versatile printer’s .laser printers are very
fast in printing and the quality of the print is also very good .laser printers work similarly to a copying
machine by converting data from the computer into a beam of light is focused on a photoconductor
drum, forming the images to be printed. The photoconductor attracts particles of toner that are fused
by heat and pressure onto paper to produce an image. The laser printer prints an entire page at a time.
Getaneh.T[UU] Page 9
Introduction To Computer And Programming
Hence the speed of laser printer is measured in terms of the number of pages that it can print per
minute.
Inkjet printers
These printers spray tiny streams of ink from holes in the print mechanism onto the paper. These
printers are highly used to print graphs and charts.
Plotters
These devices are similar to printers, but are generally vector based in the way they drew lines and
information on the paper. Plotters draw images information, such as charts and graphs, line drawings,
and blue prints of buildings. Plotters are able to produce every line that drawers use as if they are
drawing by hand. They also produce shadows and patterns. There are two types of plotter, one where
the paper moves, and the other where the paper is stationary.
When you choose printers consider the paper size the printer uses, whether it is automatic feed (to
print several pages continuously), fonts and the print quality.
Computer software
Software
- is the invisible part of the computer system
- is collection of programs and routines that the computer needs to perform a task
- is a serious of instructions that tells the hardware what to do
- Usually software also includes documentation, rules and operational procedures.
Software is in general classified into two system software and application software
System software
- General purpose SW that is used to facilitate the utilization of the hardware.
- consists of instructions or programs that are used to manage the hardware resources of a
computer and perform required information processing tasks
- it provides the interface between the hardware and the user
System software includes operating systems and system development (language software)
Getaneh.T[UU] Page 10
Introduction To Computer And Programming
Chapter Three
A numeral system (or system of numeration) is a writing system for expressing numbers, that is, a
mathematical notation for representing numbers of a given set, using digits or other symbols in a
consistent manner. It can be seen as the context that allows the symbols "11" to be interpreted as the
binary symbol for three, the decimal symbol for eleven, or a symbol for other numbers in different
bases.
Getaneh.T[UU] Page 11
Introduction To Computer And Programming
= 16 + 0 + 0 + 2 + 1
= 19
The same principle applies to any number base. For example, the number 2132 base 8 corresponds to
2 1 3 2 number in base8
8^3 8^2 8^1 8^0 place values
Getaneh.T[UU] Page 12
Introduction To Computer And Programming
To avoid the additional problem of performing arithmetic in other number systems, the following
algorithm can be used for the conversion of one base into another:
Convert a given number to a decimal number.
Convert the obtained result decimal number to a required base.
Getaneh.T[UU] Page 13
Introduction To Computer And Programming
Solution
Here B = 2
Fractional part Integral part
.65 x 2 .30 1
.30 x 2 .60 0
.60 x 2 .20 1
.20 x 2 .40 0
.40 x 2 .80 0
.80 x 2 .60 1
.60 x 2 .20 1
Hence (.65) 10 = (.1010011…) 2
Getaneh.T[UU] Page 14
Introduction To Computer And Programming
Conversion from binary (base2) to Octal (base 8) or hexadecimal (base16) and vice versa
• To convert a number in binary to octal group three binary digits together starting from the last digit
(right) and if there are no enough digits add zeros to the front end (left) and find the corresponding
Octal of each group.
Binary to Hexa
To convert binary to hexadecimal group four binary digits together starting from right and if there
are no enough digits add zeros at the left.
Examples
Convert 111100100 to hexadecimal
111100100 =0001 1110 0100
=1 14 4
=1 E 4
=> (1E4)16
Convert 111001111 to Hexadecimal
111001111 =0001 1100 1111
=1 12 15
=1 B F
=>(1BF)16
Multiply the fractional part by 2 and take out the integer value
Getaneh.T[UU] Page 15
Introduction To Computer And Programming
And again multiply the fractional part of the result by 2 and take out the integer
part
Continue this until the product is 0.
• Collect the integer values from top to bottom & concatenate with the integer part.
Examples
A) Convert 3.1875 to binary
– Convert 3 to binary >> (11)2
– Convert 0.1875 to binary
• To convert a binary number Y1Y2Y3Y4…Yn.d1d2d3…dm to decimal first convert the integer part
to decimal by using
– Y1Y2Y3Y4…Yn = Y1*2n-1+Y2*2n-2+….yj*2n-j+….+Yn-1 *21+Yn*20 = Q
• and convert the fractional part to decimal by using – d1d2d3…dm=
d1*2-1+ d2*2-2 + d3*2-3 + … +dj*2-j + … + dm* 2-m = R
• then decimal equivalence of Y1Y2Y3Y4…Yn.d1d2d3…dm will be Q+R where Q is the integer part
and R is the fractional part.
Example
• Convert 11001.0101 to decimal
11001 = 1x2^4 + 1x2^3 +0x2^2+0x2^1+1x2^0= 16+8+1= 25= Q
0101 =0x2^-1+1x2^-2+0x2^-3+1x2^-4
= 0+¼+0+1/16 = 0.3125 = R
=>11001.0101 = 25.3125.
• Convert 1000.1 to decimal
1000 = 1+2^3 + 0 + 0 + 0 = 8
1= 1x2^-1=½ = 0.5
=> 1000.1 = 8.5
Group three/four digits together starting from the last digit of the integer part, and if there is less
number of digits add some zeros in the beginning.
Group three/ four digits together starting from the first digit of the fractional part, and if there is less
number of digits add some zeros to the end.
Covert each group of the integer and the fractional part to their equivalent Octal/hexadecimal and
collect the results by adding point (.) to separate integer part fractional part the from the part.
Getaneh.T[UU] Page 16
Introduction To Computer And Programming
Examples
• Ex 1:- Convert (1010.0111) 2 to octal
001,010.011, 100
(12.34)8
• Ex2:- Convert (1110101.1011)2 to hexadecimal
0111,0101.1011
=> ( 75.B)16
Convert to binary
0.10101011
Hence (0.526)8
Binary Arithmetic’s
Binary Addition
0+0=0
0+1=1
1+0=1
1 + 1 = 0, with a carry of 1
1 + 1 + 1 = 1, with a carry of 1
Using only the above sums, we are able to do binary addition, as shown below. We compute the
binary sum of 11011011 and 1001110 as follows:
11011011
Getaneh.T[UU] Page 17
Introduction To Computer And Programming
1001110
100101001
We add more than two binary numbers by accumulating them to a running total one at a time. For
example,
11101
10110
1100
11011
+1001 is obtained as follows:
First Step Second Step
11101 First number 110011 Sum
10110 Second number 1100 Third number
110011 Sum 111111 Sum
Binary Subtraction
Binary subtraction can be accomplished similar to the decimal subtraction. First we need to know the
following subtraction facts:
0–0=0
1–0=1
1 –1 = 0
0 –1 = 1, with a borrow of a form the next column
Example a): here there is no borrowing.
1111011
- 101001
1010010
b) Here we borrow 1 from the third column because of the difference 0-1 in the second column.
111101
- 10010
101011
Multiplication
Example 1
1 0 1 1 (A)
× 1 0 1 0 (B)
0 0 0 0 ← Corresponds to a zero in B
+ 1 0 1 1 ← Corresponds to a one in B
+ 0 0 0 0
Getaneh.T[UU] Page 18
Introduction To Computer And Programming
+ 1 0 1 1
= 1 1 0 1 1 1 0
Example 2
1 0 1.1 0 1 (A) (5.625 in decimal)
× 1 1 0.0 1 (B) (6.25 in decimal)
1 0 1 1 0 1 ← Corresponds to a one in B
+ 0 0 0 0 0 0 ← Corresponds to a zero in B
+ 0 0 0 0 0 0
+ 1 0 1 1 0 1
+ 1 0 1 1 0 1
Division
1 0 1 ) 1 1 0 1 1
− 1 0 1
0 1 1
The procedure is then repeated with the new sequence, continuing until the digits in the dividend have
been exhausted:
1 0 1
1 0 1 ) 1 1 0 1 1
− 1 0 1
0 1 1
− 0 0 0
1 1 1
− 1 0 1
1 0
Getaneh.T[UU] Page 19
Introduction To Computer And Programming
Thus, the quotient of 110112 divided by 1012 is 1012, as shown on the top line, while the remainder,
shown on the bottom line, is 102. In decimal, 27 divided by 5 is 5, with a remainder of 2’s
Complements
Complements are used in the digital computers in order to simplify the subtraction operation and for
the logical manipulations. For each radix-r system (radix r represent base of number system) there are
two types of complements
As the binary system has base r = 2. So the two types of complements for the binary system are 2's
complement and 1's complement.
1's complement
The 1's complement of a number is found by changing all 1's to 0's and all 0's to 1's. This is called as
taking complement or 1's complement. Example of 1's Complement is as follows.
2's complement
The 2's complement of binary number is obtained by adding 1 to the Least Significant Bit (LSB) of
1's complement of the number.
Getaneh.T[UU] Page 20
Introduction To Computer And Programming
Data representation
Units of Data Representation
A digital computer is based on two-state technology, that is, computers are built from components
that are – and + charges.
The binary number system, which has only two digits, 0 and 1, is conveniently to express – and +
charges.
When data is stored, processed, or communicated within the computer system, it is “packed” in units.
Arranged from the smallest to the largest, the units are called bits, bytes, and words. These
Any information input in the computer in order to be processed or stored in a computer is first
converted to a series of binary codes (e.g., 01101001) using only these two digits.
Bits
Getaneh.T[UU] Page 21
Introduction To Computer And Programming
is abbreviation for binary digit, the smallest unit of information that can be stored and manipulated
by a computer. A bit is represented by the numbers 1 and 0, which correspond to the states on and off,
true and false, or yes and no.
Bits are the building block for all information processing that goes on in digital electronics and
computers.
Bits actually represent the state of a transistor in the logic circuits of a computer.
The number 1 (meaning on, yes, or true) is used to represent a transistor with current flowing throughit—
essentially a closed switch.
The number 0 (meaning off, no, or false) is used to represent a transistor with no current flowing
through it—an open switch.
Eight bits is called a byte; a byte has 256 possible combinations of 0s and 1s.
Bytes
A byte is the basic unit of information in a computer’s memory.
It usually contains 8 bits. Since each bit has two states and there are 8 bits in a byte.
The total amount of information that can be conveyed is 2 8 or 256 possible combinations. These
combinations can provides enough possible patterns to represent the entire alphabet, in lower and upper
cases, as well as numeric digits, punctuation marks, and several character-sized graphicssymbols,
including non-English characters such as .
A byte also can be interpreted as a pattern that represents a number between 0 and 255.
A kilobyte—1,024 bytes—can store about 1,000 characters;
A megabyte can store about 1 million characters;
A gigabyte can store about 1 billion characters; and
A terabyte can store about 1 trillion characters.
For example, you can say that the computer’s memory is 1,000,000 bytes, 1000 kilobytes, or 1
megabyte. Today’s computers’ storage capacity has already been raised to a magnitude of gigabytes (1
gigabyte = 1 billion bytes).
Most references to computer’s memory capacity, processing power (Speed), and communication
speed are measured (or expressed) in terms of bytes.
A regular, floppy disk normally holds 1.44 megabytes of data, which equates to approximately
1,400,000 keyboard characters, among other types of data.
Words
Bytes are combined into groups of 1 to 8 bytes called words. Words refer to the number of bits that a
computer processes at once. Although bytes speed the transmission of messages, they can be conveyed
even faster by sending more than one byte at a time. These larger units are called words.
The larger word length a computer has, the more powerful it is.
Getaneh.T[UU] Page 22
Introduction To Computer And Programming
The size of the words used by a computer’s central processing unit (CPU) depends on the bit- processing
ability of the CPU. A 32-bit processor, for example, can use words that are up to four bytes long (32
bits).
Computers are often classified by the number of bits they can process at one time, as well as by the
number of bits used to represent addresses in their main memory (RAM). Computer graphics are
described by the number of bits used to represent pixels (short for picture elements), the smallest
identifiable parts of an image.
In monochrome images, each pixel is made up of one bit.
In 256-color and gray-scale images, each pixel is made up of one byte (eight bits).
Coding systems
When characters are used in the computer, they must be converted into computer code (binary string,
i.e. sequence of 0’s or 1’s). There are several codes for converting character data into binary strings of
which
ASCII (American Standard Code for Information Interchange) pronounced “Ace-key”
and
EBCDIC (Extended Binary Coded Decimal Interchange Code), pronounced
“Eb-see_Dick”, are the most popular codes.
BCD codes
Binary coded decimal is one of the codes used for representing a numerical value. BCD is a 4-bit
code used for coding numerical values. In BCD code, each decimal digit is coded into groups of four
bits.
Getaneh.T[UU] Page 23
Introduction To Computer And Programming
Decimal 0 1 2 3 4 5 6 7 8 9
BCD code 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001
To convert a decimal number to its BCD code represents each digit with a corresponding 4 bit binary
representation.
To change a BCD coded number to its decimal representation group in 4- bit and take the
corresponding decimal digit .
1 2 9
EBCDIC
EBCDIC, acronym for Extended Binary Coded Decimal Interchange Code. A coding scheme
developed by IBM for use with its computers as a standard method of assigning binary (numeric) values
to alphabetic, numeric, punctuation, and transmission-control characters. EBCDIC is analogous to the
ASCII coding scheme more or less universally accepted in the micro computing environment. It differs
in using 8 bits for coding, thus allowing 256 possible characters (in contrast to the 7 bits and 128
characters in the standard ASCII set). Although EBCDIC is not widely used with microcomputers, it is
well known and internationally recognized, primarily as an IBM code for the corporation's mainframes
and minicomputers. In EBCDIC successive characters may not have successive decimal numbers for
their code.
ASCII
ASCII is a coding scheme that assigns numeric values to letters, numbers, punctuation marks, and other
characters. By standardizing the values used for these characters, ASCII enables computers and
computer programs to exchange information.
Getaneh.T[UU] Page 24
Introduction To Computer And Programming
ASCII provides for 256 codes divided into two sets—standard and extended—of 128 each. These sets
represent the total possible combinations of either 7 or 8 bits, the latter being the number of bits in 1
byte.
The basic, or standard, ASCII set uses 7 bits for each code, yielding 128 character codes from 0 through
127 (hexadecimal 00H through 7FH).
The extended ASCII set uses 8 bits for each code, yielding an additional 128 codes numbered 128
through 255 (hexadecimal 80H through FFH).
In the standard ASCII character set, the first 32 values are assigned to communication and printer
control codes—nonprinting characters, such as backspace, carriage return, and tab—that are used to
control the way information is transferred from one computer to another or from a computer to a printer.
The remaining 96 codes are assigned to common punctuation marks, the digits 0 through 9, and the
uppercase and lowercase letters of the Roman alphabet.
The extended ASCII codes, 128 through 255, are assigned to variable sets of characters by computer
manufacturers and software developers. These codes are not as interchangeable among different
programs and computers as are the standard ASCII characters. IBM, for example, uses a group of
extended ASCII characters generally called the IBM extended character set for its personal computers;
Apple Computer uses a similar but different group of extended ASCII characters for its Macintosh line
of computers. Thus, whereas the standard ASCII character set is universal among microcomputer
hardware and software, extended ASCII characters can be interpreted correctly only if a program,
computer, or printer is designed to do so.
The first 32 characters in the ASCII-table are unprintable control codes and are used to control peripherals such as printers.
Getaneh.T[UU] Page 25
Introduction To Computer And Programming
Getaneh.T[UU] Page 26
Introduction To Computer And Programming
close bracket)
42 052 2A 00101010 * * Asterisk
43 053 2B 00101011 + + Plus
44 054 2C 00101100 , , Comma
45 055 2D 00101101 - - Hyphen
Period, dot or
46 056 2E 00101110 . .
full stop
47 057 2F 00101111 / / Slash or divide
48 060 30 00110000 0 0 Zero
49 061 31 00110001 1 1 One
50 062 32 00110010 2 2 Two
51 063 33 00110011 3 3 Three
52 064 34 00110100 4 4 Four
53 065 35 00110101 5 5 Five
54 066 36 00110110 6 6 Six
55 067 37 00110111 7 7 Seven
56 070 38 00111000 8 8 Eight
57 071 39 00111001 9 9 Nine
58 072 3A 00111010 : : Colon
59 073 3B 00111011 ; ; Semicolon
Less than (or
60 074 3C 00111100 < < < open angled
bracket)
61 075 3D 00111101 = = Equals
Greater than (or
62 076 3E 00111110 > > > close angled
bracket)
63 077 3F 00111111 ? ? Question mark
64 100 40 01000000 @ @ At symbol
65 101 41 01000001 A A Uppercase A
66 102 42 01000010 B B Uppercase B
67 103 43 01000011 C C Uppercase C
68 104 44 01000100 D D Uppercase D
69 105 45 01000101 E E Uppercase E
70 106 46 01000110 F F Uppercase F
71 107 47 01000111 G G Uppercase G
72 110 48 01001000 H H Uppercase H
73 111 49 01001001 I I Uppercase I
74 112 4A 01001010 J J Uppercase J
75 113 4B 01001011 K K Uppercase K
76 114 4C 01001100 L L Uppercase L
Getaneh.T[UU] Page 27
Introduction To Computer And Programming
Getaneh.T[UU] Page 28
Introduction To Computer And Programming
EBCDIC
EBCDIC is a coding scheme developed by IBM for use with its computers as a standard method of
assigning binary (numeric) values to alphabetic, numeric, punctuation, and transmission-control
characters. EBCDIC is analogous to the ASCII coding scheme more or less universally accepted in the
micro-computing environment. It differs in using 8 bits for coding, thus allowing 256 possible
characters (in contrast to the 7 bits and 128 characters in the standard ASCII set). Although EBCDIC
is not widely used with microcomputers, it is well known and internationally recognized, primarily as
an IBM code for the corporation's mainframes and minicomputers.
Dec Hex Code Dec Hex Code Dec Hex Code Dec Hex Code
0 00 NUL 32 20 64 40 space 96 60 -
1 01 SOH 33 21 65 41 97 61 /
2 02 STX 34 22 66 42 98 62
3 03 ETX 35 23 67 43 99 63
4 04 36 24 68 44 100 64
5 05 HT 37 25 LF 69 45 101 65
6 06 38 26 ETB 70 46 102 66
8 08 40 28 72 48 104 68
Getaneh.T[UU] Page 29
Introduction To Computer And Programming
9 09 41 29 73 49 105 69
10 0A 42 2A 74 4A [ 106 6A |
11 0B VT 43 2B 75 4B . 107 6B ,
12 0C FF 44 2C 76 4C < 108 6C %
13 0D CR 45 2D ENQ 77 4D ( 109 6D _
14 0E SO 46 2E ACK 78 4E + 110 6E >
15 0F SI 47 2F BEL 79 4F |! 111 6F ?
16 10 DLE 48 30 80 50 & 112 70
17 11 49 31 81 51 113 71
18 12 50 32 SYN 82 52 114 72
19 13 51 33 83 53 115 73
20 14 52 34 84 54 116 74
21 15 53 35 85 55 117 75
22 16 BS 54 36 86 56 118 76
23 17 55 37 EOT 87 57 119 77
24 18 CAN 56 38 88 58 120 78
25 19 EM 57 39 89 59 121 79 ‘
26 1A 58 3A 90 5A !] 122 7A :
27 1B 59 3B 91 5B $ 123 7B #
28 1C IFS 60 3C 92 5C * 124 7C @
Getaneh.T[UU] Page 30
Introduction To Computer And Programming
Getaneh.T[UU] Page 31
Introduction To Computer And Programming
be unsigned or signed. The bit operations performed are identical, the difference comes from the
interpretation of the bits. The interpretation of the value will be different depending on whether the
value is considered to be unsigned or signed.
For example: Find the 2’s complement of the following 8 bit number
00101001
11010110 First, invert the bits
+ 00000001 Then, add 1
= 11010111
The 2’s complement of 00101001 is 11010111
Another example: Find the 2’s complement of the following 8 bit number
10110101
= 01001011
The counting sequence for an eight bit binary value using 2’s complement representation appears as
follows:
00000011 03h
00000010 02h
00000001 01h
00000000 00h
11111111 0FFh -1
11111110 0FEh -2
11111101 0FDh -3
…
10000010 82h -126
10000001 81h -127
Getaneh.T[UU] Page 32
Introduction To Computer And Programming
Getaneh.T[UU] Page 33
Introduction To Computer And Programming
Chapter four
Introduction to programming and Algorithm
Programming (Knowledge Transfer)
Knowledge can be transferred from
Human to human
Human to computer
Knowledge transfer from human to human is much simpler than knowledge
transfer from human to computer. Why?
o All humans have the same internal working mechanism
o All humans have the ability to think
Programming: is the system of transferring human knowledge fromhuman
to computers.
Programmer: is the one who can transfer knowledge from human to
computers.
Program: is a human knowledge represented in computer understandable
format. Or in professional meaning, a program is a list of instruction that
the computer must follow in order to process data into information.
What kinds of knowledge can be transferred from human to computer?
Answer: A knowledge that can be expressed algorithmically.
How can this knowledge be transferred?
Answer: Using problem solving steps.
Algorithm: is a sequence of logical steps expressed informally that can
accomplish a given task.
A Program: is a sequence of logical steps expressed formally that can
accomplish a given task.
Example:
1. Given the following list, develop an algorithm that finds the smallest
number.
4 3 -1 6 -4 7
Getaneh.T[UU] Page 34
Introduction To Computer And Programming
7 2 -1 8 10 8 Sn=11
Compare the search key with the element of the list one by one starting
from first element until a match is found or the list is exhausted.
Expressing Algorithm
There are two ways by which you can express or describe your algorithm.
A. Using Pseudo code
An algorithm is a procedure for solving a problem in terms of the actions to be
executed and the order in which those actions are to be executed. An algorithm
is merely the sequence of steps taken to solve a problem. The steps are
normally "sequence," "selection,” "iteration," and a case-type statement.
Pseudocode is an artificial and informal language that helps programmers
develops algorithms. Pseudocode is a "text-based" detail (algorithmic) design
tool.
Getaneh.T[UU] Page 35
Introduction To Computer And Programming
1. To get the smallest number from the list for above example.
Start
Let min=the first element
While not the end of list
Do
Compare min with the next element
If min is greater than the compared number
min=the compared number
Else
Do nothing
End Do
Display min
Stop
2. the program computes the sum, average and product of three numbers:
Getaneh.T[UU] Page 36
Introduction To Computer And Programming
Read X, Y, Z
Compute Sum (S) as X + Y + Z
Getaneh.T[UU] Page 37
Introduction To Computer And Programming
3. a program that reads two numbers and displays the numbers read in decreasing order:
Read A, B
If A is less than B
BIG = B
SMALL = A
else
BIG = A
SMALL = B
Write (Display) BIG, SMALL
B. Using Flowchart
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very
helpful in writing program and explaining program to others. Symbols Used In
Flowchart Different symbols are used for different states in flowchart, For
example: Input/output and decision making has different symbols.
Represent an algorithm graphically.
Enforce programmer to put steps precisely.
Makes an algorithm easier to convert into program.
More readable
Can be easily hand traced.
It uses standard symbols.
Getaneh.T[UU] Page 38
Introduction To Computer And Programming
Examples:
1. To get the smallest number from the list for above example.
start
min= a1 i=2
ai<min min= ai
i=i+1
Getaneh.T[UU] Page 39
Introduction To Computer And Programming
3. Draw flowchart to find the largest among three different numbers entered by user.
Getaneh.T[UU] Page 40
Introduction To Computer And Programming
Getaneh.T[UU] Page 41
Introduction To Computer And Programming
Getaneh.T[UU] Page 42
Introduction To Computer And Programming
Getaneh.T[UU] Page 43
Introduction To Computer And Programming
Though, flowchart is useful in efficient coding, debugging and analysis of a program, drawing
flowchart in very complicated in case of complex programs and often ignored.
Getaneh.T[UU] Page 44
Introduction To Computer And Programming
Note:
Machine language and assembly languages are called low level
programming language.
The computer (CPU) can understand directly or with little
translator, so that they are very fast.
They require less resource (Memory).
You can get the power of the machine.
Disadvantages:
Much closer to the machine so that you need to know the architecture of
the machine.
Difficult to learn, write and debug.
Machine dependent.
3. High level programming Languages
Getaneh.T[UU] Page 45
Introduction To Computer And Programming
Note:
These are some basic things to apply
I. Exercise the problem by taking several examples
II. Split the problem into manageable pieces
f(x) = ax2+bx+c
a≠0
Getaneh.T[UU] Page 46
Introduction To Computer And Programming
4. Program Testing
Check the program to discover errors
Run the program and debug it.
Run the program with real-world data.
Errors
Getaneh.T[UU] Page 47
Introduction To Computer And Programming
5. Documentation
All your works at different stages has to be documented.
Documentation is necessary for
o The program
o The other user
o The user
6. Maintenance
After delivering the program to the end user, different things might
happened
a. Error might be discovered
b. User need(Requirements) might be changed
c. The infrastructure might be changed (Hardware, Operating
system)
In the above cases maintenance is needed
Getaneh.T[UU] Page 48
Introduction To Computer And Programming
Chapter Two
Introduction to C++
Structure of a Program
Probably the best way to start learning a programming language is by writing a
program. Therefore, here is our first program:
// my first program in C++ Hello World!
#include<iostream.h>
#include<conio.h>
void main ()
{
cout << "Hello World! \n ";
getch();
}
// my first program in C++
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.
Lines beginning with a pound 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.h>
and #include<conio.h> tells the preprocessor to include the iostream and
conio standard file. Iostream.h is a standard C++ header file and contains
definitions for input and output.
Getaneh.T[UU] Page 49
Introduction To Computer And Programming
void main ()
getch()
getch is a code that wait until the user enters any character
from keyboard so here we can see the output on the screen until
any character entered.
Getaneh.T[UU] Page 50
Introduction To Computer And Programming
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
In this case, we performed two insertions into cout in two different statements.
Once again, the separation in different lines of code has been done just to give
greater readability to the program, since main could have been perfectly valid
defined this way:
Comments
Comments are parts of the source code disregarded by the compiler. They
simply do nothing. Their purpose is only to allow the programmer to insert notes
or descriptions embedded within the source code.
// line comment
/* block comment */
Getaneh.T[UU] Page 51
Introduction To Computer And Programming
1 #include <iostream.h>
2 /* This program calculates the weekly gross pay for a worker,
3 based on the total number of hours worked and the hourly pay
4 rate. */
Comment
5 int main (void)
6 {
7 int workDays = 5; // Number of work days per weekfloat
8 workHours = 7.5; // Number of work hours per dayfloat
9 payRate = 33.50; // Hourly pay rate
10 float weeklyPay; // Gross weekly pay
11 weeklyPay = workDays * workHours * payRate;
12 cout << "Weekly Pay = " << weeklyPay << '\n';
13 }
#include<iostream.h>
#include<conio.h>
int main ()
{
cout << "Hello World! "; // prints
Hello World!
cout << "I'm a C++ program"; // prints I'm
a C++ program
getch();
}
Getaneh.T[UU] Page 52
Introduction To Computer And Programming
Memory
1 1 0 1 0 0 0 1
Bit
The C++ compiler generates executable code which maps data entities tomemory
locations. For example, the variable definition
int salary = 65000;
Causes the compiler to allocate a few bytes to represent salary. The exact number
of bytes allocated and the method used for the binary representation of the integer
depends on the specific C++ implementation, but let us say two bytes encoded
as a 2’s complement integer. The compiler uses the address of the first byte at
which salary is allocated to refer to it. The above assignment causes the value
65000 to be stored as a 2’s complement integer in the two bytes allocated (see
Figure below).
Getaneh.T[UU] Page 53
Introduction To Computer And Programming
Variables
Getaneh.T[UU] Page 54
Introduction To Computer And Programming
identifiers will change the value that can be accessed through the other identifiers.
Compilers have to replace variables' symbolic names with the actual locations of
the data. While a variable's name, type, and location often remain fixed, thedata
stored in the location may be changed during program execution.
Each variable needs an identifier that distinguishes it from the others, forexample,
in the previous code the variable identifiers were a, b and result, but we could
have called the variables any names we wanted to invent, as long as they were
valid identifiers.
Identifiers
An identifier is a name that identifies (that is, labels the identity of) either a unique
object or a unique class of objects, where the "object" or class may be an idea,
physical [countable] object (or class thereof), or physical [noncountable]
substance (or class thereof). The abbreviation ID often refers to identity,
identification (the process of identifying), or an identifier (that is, an instance of
identification).
Getaneh.T[UU] Page 55
Introduction To Computer And Programming
Another rule that you have to consider when inventing your own identifiers is
that they cannot match any keyword of the C++ language nor your compiler's
specific ones, which are reserved keywords. The standard reserved keywords
are:
asm, auto, bool, break, case, catch, char, class, const, const_cast,
continue, default, delete, do, double, dynamic_cast, else, enum,
explicit, export, extern, false, float, for, friend, goto, if,
inline, int, long, mutable, namespace, new, operator, private,
protected, public, register, reinterpret_cast, return, short,
signed, sizeof, static, static_cast, struct, switch, template, this,
throw, true, try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while
Getaneh.T[UU] Page 56
Introduction To Computer And Programming
operations that can be done on values of that type; the meaning of the data;
and the way values of that type can be stored.
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.
Next you 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:
signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)
Getaneh.T[UU] Page 57
Introduction To Computer And Programming
A literal character is written by enclosing the character between a pair of single quotes (e.g., 'A').
Nonprintable characters are represented using escape sequences. For example:
'\n' // new line
'\r' // carriage return
'\t' // horizontal tab
'\v' // vertical tab
'\b' // backspace
'\f' // formfeed
Single and double quotes and the backslash character can also use the escape notation:
'\'' // single quote (')
'\"' // double quote (")
'\\' // backslash (\)
Literal characters may also be specified using their numeric code value. The general escape sequence
\ooo (i.e., a backslash followed by up to three octal digits) is used for this purpose. For example
(assuming ASCII):
'\12' // newline (decimal code = 10)
'\11' // horizontal tab (decimal code = 9)
'\101' // 'A' (decimal code = 65)
'\0' // null (decimal code = 0)
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. 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
Getaneh.T[UU] Page 58
Introduction To Computer And Programming
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;
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:
#include<iostream.h>
#include<conio.h>
void main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Getaneh.T[UU] Page 59
Introduction To Computer And Programming
Do not worries if something else than the variable declarations themselves look
a bit strange to you. You will see the rest in detail in coming sections.
Scope of variables
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.
Getaneh.T[UU] Page 60
Introduction To Computer And Programming
Initialization of variables
int a = 10;
Constants
In computer programming, a constant is an identifier whose associated value
cannot typically be altered by the program during its execution (though in some
cases this can be circumvented, e.g. using self-modifying code). Many
programming languages make an explicit syntactic distinction between constant
and variable symbols.
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;
Getaneh.T[UU] Page 61
Introduction To Computer And Programming
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.
Exercises
1. Write a program which inputs a temperature reading expressed in Fahrenheit and outputs
its equivalent in Celsius, using the formula:
5
C ( F 32)
9
Compile and run the program. Its behaviour should resemble this:
Temperature in Fahrenheit: 41
41 degrees Fahrenheit = 5 degrees Celsius
2. Which of the following represent valid variable definitions?
int n = -100;
unsigned int i = -100;
signed int = 2.9;
long m = 2, p = 4;
int 2k;
double x = 2 * m;
float y = y * 2;
unsigned double z = 0.0;
double d = 0.67F;
float f = 0.52L;
signed char = -1786;
char c = '$' + 2;
sign char h = '\111';
char *name = "Peter Pan";
unsigned char *num = "276811";
3. Which of the following represent valid identifiers?
identifier
Getaneh.T[UU] Page 62
Introduction To Computer And Programming
seven_11
_unique_
gross-income
gross$income
2by2
default
average_weight_of_a_large_pizza
variable
object.oriented
Operators
Assignment (=)
a = b;
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:
a = b = c = 5;
+ addition
- subtraction
* multiplication
/ division
% modulo
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing 11
between 3.
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price = price * (units +
price *= units + 1;
1);
Operator Example Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
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.
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4, B // A contains 3, B contains
contains 4 4
int k = 5;
Relational and equality operators ( ==, !=, >, <, >=, <= )
== Equal to
!= Not equal to
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Of course, instead of using only numeric constants, we can use any valid
expression, including variables. Suppose that a=2, b=3 and c=6,
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. For example:
The logical operators && and || are used when evaluating two expressions to
obtain a single relational result. The operator && corresponds with Boolean
logical operation AND. This operation results true if both its two operands are
true, and false otherwise. The following panel shows the result of operator &&
evaluating the expression a && b:
&& OPERATOR
a b a && b
The operator || corresponds with Boolean logical operation OR. This operation
results true if either one of its two operands is true, thus being false only when
both operands are false themselves. Here are the possible results of a || b:
|| OPERATOR
a b a || b
For example:
Conditional operator ( ? )
If condition is true the expression will return result1, if it is not it will return
result2.
// conditional operator 7
#include<iostream.h>
#include<conio.h>
void main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
getch();
}
In this example a was 2 and b was 7, so the expression being evaluated (a>b)
was not true, thus the first value specified after the question mark was
discarded in favor of the second value (the one after the colon) which was b,
with a value of 7.
Examle2
int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
Note that of the second and the third operands of the conditional operator only
one is evaluated. This may be significant when one or both contain side-effects
(i.e., their evaluation causes a change to the value of a variable). For example, in
int min = (m < n ? m++ : n++);
m is incremented because m++ is evaluated but n is not incremented because
n++ is not evaluated.
Because a conditional operation is itself an expression, it may be used as an
operand of another conditional operation, that is, conditional expressions may
be nested. For example:
int m = 1, n = 2, p =3;
int min = (m < n ? (m < p ? m : p)
: (n < p ? n : p));
Basic Input/output
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).
The << operator inserts the data that follows it into the stream preceding it. In
the examples above it inserted the constant string Output sentence, the
numerical constant 120 and variable x into the standard output stream cout.
Notice that the sentence in the first instruction is enclosed between double
quotes (") because it is a 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:
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:
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):
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For
example:
First sentence.
Second sentence.
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;
The first statement declares a variable of type int called age, and the second
one waits for an input from cin (the keyboard) in order to store it in this integer
variable.
void main ()
{
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";
getch();
}
You can also use cin to request more than one datum input from the user:
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:
void main ()
{
char mystr[20];
cout << "What's your name? ";
cin.getline(mystr , 20);
cout << "Hello " << mystr <<
".\n";
cout << "What is your favorite
team? ";
cin.getline(mystr , 20);
cout << "I like " << mystr << "
too!\n";
getch();
}
Notice how in both calls to getline we used the same string identifier (mystr).
What the program does in the second call is simply to replace the previous
content by the new one that is introduced.
A value in any of the built-in types we have seen so far can be converted (type-
cast) to any of the other types. For example:
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is 122
(unsigned short) 3.14 // gives 3 as an unsigned short
As shown by these examples, the built-in type identifiers can be used as type
operators. Type operators are unary (i.e., take one operand) and appear
inside brackets to the left of their operand. This is called explicit type
conversion. When the type name is just one word, an alternate notation may be
used in which the brackets appear around the operand:
int(3.14) // same as: (int) 3.14
In some cases, C++ also performs implicit type conversion. This happens
when values of different types are mixed in an expression. For example:
double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d; // means: i = int(double(i) + d)
In the last example, i + d involves mismatching types, so i is first converted to
double (promoted) and then added to d. The result is a double which does not
match the type of i on the left side of the assignment, so it is converted to int
(demoted) before being assigned to i.
The above rules represent some simple but common cases for type conversion.
More complex cases will be examined later in the book after we have discussed
other data types and classes.
Exercises
(n | p & q ^ p << 2 + q)
(p < q ? n < p ? q * n - 2 : q / n + 1 : q - n)
3. What will be the value of each of the following variables after its
initialization:
double d = 2 * int(3.14);
long k = 3.14 - 3;
char c = 'a' + 2;
char c = 'p' + 'A' - 'a';
4. Write a program which inputs a positive integer n and outputs 2 raised
to the power of n.
5. Write a program which inputs three numbers and outputs the message
sorted if the numbers are in ascending order, and outputs Not sorted
otherwise.
Chapter Three
Control Structures
Conditional structure:
The if Statement
The if keyword is used to execute a statement or block only if a condition is
fulfilled. Its form is:
if (condition) statement
if (x == 100)
cout << "x is 100";
if (x == 100)
{
cout << "x is ";
cout << x;
}
if (expression)
statement1;
else
statement2;
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
prints on the screen x is 100 if indeed x has a value of 100, but if it has not -
and only if not- it prints out x is not 100.
}
}
For improved readability, it is conventional to format such cases as follows:
if (ch >= '0' && ch <= '9')
kind = digit;
else if (cha >= 'A' && ch <= 'Z')
kind = capitalLetter;
else if (ch >= 'a' && ch <= 'z')
kind = smallLetter;
else
kind = special;
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
First expression (called the switch tag) is evaluated, and the outcome is compared
to each of the numeric constants (called case labels), in the order they appear,
until a match is found. The statements following the matching case are then
executed. Note the plural: each case may be followed by zero or more statements
(not just one statement). Execution continues until either a break statement is
encountered or all intervening statements until the end of theswitch statement
are executed. The final default case is optional and is exercised if none of the
earlier cases provide a match.
For example, suppose we have parsed a binary arithmetic operation into its
three components and stored these in variables operator, operand1, and operand2.
The following switch statement performs the operation and stored the result in
result.
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
As illustrated by this example, it is usually necessary to include a break statement
at the end of each case. The break terminates the switch statement by jumping
to the very end of it. There are, however, situations in which it makes sense to
have a case without a break. For example, if we extend the above statement to
also allow x to be used as a multiplication operator, we will have:
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case 'x':
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
Because case 'x' has no break statement (in fact no statement at all!), when this
case is satisfied, execution proceeds to the statements of the next case and the
multiplication is performed.
It should be obvious that any switch statement can also be written as multiple if-
else statements. The above statement, for example, may be written as:
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';
switch example if-else equivalent
switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";
The while statement (also called while loop) provides a way of repeating a
statement while a condition holds. It is one of the three flavors of iteration in
C++. The general form of the while statement is:
while (expression)
statement;
First expression (called the loop condition) is evaluated. If the outcome is
nonzero then statement (called the loop body) is executed and the whole process
is repeated. Otherwise, the loop is terminated.
For example, suppose we wish to calculate the sum of all numbers from 1 to some
integer denoted by n. This can be expressed as:
i = 1;
sum = 0;
while (i <= n)
sum += i++;
For n set to 5, Table 5.Error! Bookmark not defined. provides a trace of the
loop by listing the values of the variables involved and the loop condition.
While loop trace.
It is not unusual for a while loop to have an empty body (i.e., a null statement).
The following loop, for example, sets n to its greatest odd factor.
while (n % 2 == 0 && n /= 2)
;
Here the loop condition provides all the necessary computation, so there is no real
need for a body. The loop condition not only tests that n is even, it also divides n
by two and ensures that the loop will terminate should n be zero.
void main ()
{
int n;
cout << "Enter the starting
number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
getch();
}
The do statement (also called do loop) is similar to the while statement, except
that its body is executed first and then the loop condition is examined. The general
form of the do statement is:
do
statement;
while (expression);
First statement is executed and then expression is evaluated. If the outcome of
the latter is nonzero then the whole process is repeated. Otherwise, the loop is
terminated.
The do loop is less frequently used than the while loop. It is useful for situations
where we need the loop body to be executed at least once, regardless of the loop
condition. For example, suppose we wish to repeatedly read a value and print its
square, and stop when the value is zero. This can be expressed as the following
loop:
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
Example
{ You entered: 0
unsigned long n;
do {
cout << "Enter number (0 to
end): ";
cin >> n;
cout << "You entered: " << n
<< "\n";
} while (n != 0);
getch();
}
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.
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 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.
4. finally, whatever is specified in the increase field is executed and the loop
gets back to step 2.
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:
Getaneh.T. [UU] Page 90
Introduction To Computer And Programming
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.
Jump statements.
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?):
void main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown
aborted!";
break;
}
}
getch();
}
The continue statement causes the program to skip the rest of the loop in the
current iteration as if the end of the 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:
void main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
getch();
}
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
(:).
void main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
getch();
}
The purpose of exit is to terminate the current program with a specific exit
code. Its prototype is:
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.
Exercises
1. Write a program which inputs a person’s height (in centimeters) and weight (in kilograms)
and outputs one of the messages: underweight, normal, or overweight,using the
criteria:
Underweight: weight < height/2.5
Normal: height/2.5 <= weight <= height/2.3
Overweight: height/2.3 < weight
2. Assuming that n is 20, what will the following code fragment output when executed?
if (n >= 0)
if (n < 10)
cout << "n is small\n";
else
cout << "n is negative\n";
3. Write a program which inputs a date in the format dd/mm/yy and outputs it in the format
month dd, year. For example, 25/12/61 becomes:
December 25, 1961
4. Write a program which inputs an octal number and outputs its decimal equivalent. The
following example illustrates the expected behavior of the program:
Input an octal number: 214
Octal(214) = Decimal(532)
5. Write a program which produces a simple multiplication table of the following format for
integers in the range 1 to 9:
1 x 1 = 1
1 x 2 = 2
...
9 x 9 = 81
Chapter Four
Functions
Using functions we can structure our programs in a more modular way,
accessing all the potential that structured programming can offer to us in C++.
where:
type is the data type specifier of the data returned by the function.
r=a+b;
return (r);
}
void main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
getch();
}
In order to examine this code, first of all remember something said at the
beginning of this tutorial: a C++ program always begins its execution by the
main function. So we will begin there.
We can see how the main function begins by declaring the variable z of type
int. Right after that, we see a call to a function called addition. Paying
attention we will be able to see the similarity between the structure of the call to
the function and the declaration of the function itself some code lines above:
The parameters and arguments have a clear correspondence. Within the main
function we called to addition passing two values: 5 and 3, that correspond to
the int a and int b parameters declared for function addition.
At the point at which the function is called from within main, the control is lost
by main and passed to function addition. The value of both arguments passed
in the call (5 and 3) are copied to the local variables int a and int b within the
function.
Function addition declares another local variable (int r), and by means of the
expression r=a+b, it assigns to r the result of a plus b. Because the actual
parameters passed for a and b are 5 and 3 respectively, the result is 8.
return (r);
finalizes function addition, and returns the control back to the function that
called it in the first place (in this case, main). At this moment the program
follows it regular course from the same point at which it was interrupted by the
call to addition. But additionally, because the return statement in function
addition specified a value: the content of variable r (return (r);), which at
that moment had a value of 8. This value becomes the value of evaluating the
function call.
So being the value returned by a function the value given to the function call
itself when it is evaluated, the variable z will be set to the value returned by
addition (5, 3), that is 8. To explain it another way, you can imagine that the
call to a function (addition (5,3)) is literally replaced by the value it returns
(8).
That, as you may already expect, produces the printing of the result on the
screen.
void 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';
getch();
}
In this case we have created a function called subtraction. The only thing that
this function does is to subtract both passed parameters and to return the
result.
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
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:
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);
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;
you will see that the declaration begins with a type, that is the type of the
function itself (i.e., the type of the datum that will be returned by the function
with the return statement). But what if we want to return no value?
Imagine that we want to make a function just to show a message on the screen.
We do not need it to return any value. In this case we should use the void type
specifier for the function. This is a special specifier that indicates absence of
type.
#include<conio.h>
void printmessage ()
{
cout << "I'm a function!";
}
void main ()
{
printmessage ();
getch();
}
void can also be used in the function's parameter list to explicitly specify that
we want the function to take no actual parameters when it is called. For
example, function printmessage could have been declared as:
What you must always remember is that the format for calling a function
includes specifying its name and enclosing its parameters between parentheses.
The non-existence of parameters does not exempt us from the obligation to
write the parentheses. For that reason the call to printmessage is:
printmessage ();
The parentheses clearly indicate that this is a call to a function and not the
name of a variable or some other C++ statement. The following call would have
been incorrect:
printmessage;
Until now, in all the functions we have seen, the arguments passed to the
functions have been passed by value. This means that 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:
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.
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:
void main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ",
z=" << z;
getch();
}
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.
That is why our program's output, that shows the values stored in x, y and z
after the call to duplicate, shows the values of all the three variables of main
doubled.
i.e., without the ampersand signs (&), we would have not passed the variables
by reference, but a copy of their values instead, and therefore, the output on
screen of our program would have been the values of x, y and z without having
been modified.
prev = x-1;
next = x+1;
}
void main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ",
Next=" << z;
getch();
}
When declaring a function we can specify a default value for each parameter.
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:
// default values in functions 6
#include<iostream.h> 5
#include<conio.h>
void main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
getch();
}
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).
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).
Exercises
1. Given the following definition of a Swap function
void Swap (int x, int y)
{
int temp = x;
x = y;
y = temp;
}
what will be the value of x and y after the following call:
x = 10;
y = 20;
Swap(x, y);
2. Write a function which outputs all the prime numbers between 2 and a given positive
integer n:
void Primes (unsigned int n);
A number is prime if it is only divisible by itself and 1.
3. Define a recursive version of the Power function described in this chapter.
4. Write a function which returns the sum of a list of real values
double Sum (int n, double val ...);
where n denotes the number of values in the list
Chapter Five
Arrays, Strings and Pointer
Arrays
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.
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:
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. In order to create arrays with a variable length dynamic memory is
needed, which is explained later in these tutorials.
Initializing arrays.
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:
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
void main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
getch();
}
a = billy[2];
Therefore, the expression billy[2] is for all purposes like a variable of type
int.
Multidimensional arrays
and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:
jimmy[1][3]
Pointers
This way, each cell can be easily located in the memory because it has a unique
address and all the memory cells follow a successive pattern. For example, if we
are looking for cell 1776 we know that it is going to be right between cells 1775
and 1777, exactly one thousand cells after 776 and exactly one thousand cells
before cell 2776.
type * name;
where type is the data type of the value that the pointer is intended to point to.
This type is not the type of the pointer itself! but the type of the data the pointer
points to. For example:
int * number;
char * character;
float * greatnumber;
int * ted;
int andy,fred;
The address that locates a variable within memory is what we call a reference to
that variable. This reference to a variable can be obtained by preceding the
identifier of a variable with an ampersand sign (&), known as reference operator,
and which can be literally translated as "address of". For example:
ted = &andy;
This would assign to ted the address of variable andy, since when preceding the
name of the variable andy with the reference operator (&) we are no longer
talking about the content of the variable itself, but about its reference (i.e., its
address in memory).
For now on we are going to assume that andy is placed during runtime in the
memory address 1776. This number (1776) is just and arbitrary assumption we
are inventing right now in order to help clarify some concepts in this tutorial, but
in reality, we cannot know before runtime the real value the address of a
variable will have in memory.
andy = 25;
fred = andy;
ted = &andy;
The values contained in each variable after the execution of this, are shown in
the following diagram:
The second statement copied to fred the content of variable andy (which is 25).
This is a standard assignment operation, as we have done so many times
before.
Finally, the third statement copies to ted not the value contained in andy but a
reference to it (i.e., its address, which we have assumed to be 1776). The
reason is that in this third assignment operation we have preceded the identifier
andy with the reference operator (&), so we were no longer referring to the
value of andy but to its reference (its address in memory).
We have just seen that a variable which stores a reference to another variable is
called a pointer. Pointers are said to "point to" the variable whose reference they
store.
Using a pointer we can directly access the value stored in the variable which it
points to. To do this, we simply have to precede the pointer's identifier with an
asterisk (*), which acts as dereference operator and that can be literally
translated to "value pointed by".
beth = *ted;
(that we could read as: "beth equal to value pointed by ted") beth would take
the value 25, since ted is 1776, and the value pointed by 1776 is 25.
You must clearly differentiate that the expression ted refers to the value 1776,
while *ted (with an asterisk * preceding the identifier) refers to the value stored
at address 1776, which in this case is 25. Notice the difference of including or
not including the dereference operator (I have included an explanatory
commentary of how each of these two expressions could be read):
andy = 25;
ted = &andy;
Right after these two statements, all of the following expressions would give
true as result:
andy == 25
&andy == 1776
ted == 1776
*ted == 25
The first expression is quite clear considering that the assignment operation
performed on andy was andy=25. The second one uses the reference operator
(&), which returns the address of variable andy, which we assumed it to have a
value of 1776. The third one is somewhat obvious since the second expression
was true and the assignment operation performed on ted was ted=&andy. The
fourth expression uses the dereference operator (*) that, as we have just seen,
can be read as "value pointed by", and the value pointed by ted is indeed 25.
So, after all that, you may also infer that for as long as the address pointed by
ted remains unchanged the following expression will also be true:
*ted == andy
void main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue <<
endl;
cout << "secondvalue is " << secondvalue
<< endl;
getch();
}
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.
String Variables
There are two types of string variable declaration:
Example:
char name[5][10] ;
for (int i=0 ; i<5 ; i++ )
cin>>name[i] ;
The above fragment of code accept five name each with ten characters
Note: In order to use a string library function you must include a header file:
#include<string.h>
char *Y;
strcpy(Y, “MICROLINK”);
strlwr(Y);
cout<<Y; //displays microlink
// string Example
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main ()
{
char name[100][15] , key[15];
int n,m=0;
cout<<”Hopw many names : “;
cout<<”\nEnter all names one by one:”;
cin>>n;
for(int i=0 ; i<n ; i++)
cin>>name[i];
cout<<”Enter the name you are looking for:”;
cin>>key;
Chapter Six
Data Structure
Getaneh.T. [UU] Page 122
Introduction To Computer And Programming
We have already learned how groups of sequential data can be used in C++. But
this is somewhat restrictive, since in many occasions what we want to store are
not mere sequences of elements all of the same data type, but sets of different
elements with different data types.
Data structures
A data structure is a group of data elements grouped together under one name.
These data elements, known as members, can have different types and different
lengths. Data structures are declared in C++ using the following syntax:
struct structure_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
The first thing we have to know is that a data structure creates a new type:
Once a data structure is declared, a new type with the identifier specified as
structure_name is created and can be used in the rest of the program as if it
was any other type. For example:
struct product {
int weight;
float price;
} ;
product apple;
product banana, melon;
Let's see a real example where you can see how a structure type can be used in
the same way as fundamental types:
void main ()
{
char mystr[20];
strcpy(mine.title,"2001 A Space
Odyssey");
mine.year = 1968;
cin.getline (mystr,20);
The example shows how we can use the members of an object as regular
variables. For example, the member yours.year is a valid variable of type int,
and mine.title is a valid variable of type string.
Chapter Seven
Input/output with Files
C++ provides the following classes to perform output and input of characters
to/from files:
These classes are derived directly or indirectly from the classes istream, and
ostream. We have already used objects whose types were these classes: cin is
an object of class istream and cout is an object of class ostream. Therfore, we
have already been using classes that are related to our file streams. And in fact,
we can use our file streams the same way we are already used to use cin and
cout, with the only difference that we have to associate these streams with
physical files. Let's see an example:
void main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a
file.\n";
myfile.close();
getch();
}
This code creates a file called example.txt and inserts a sentence into it in the
same way we are used to do with cout, but using the file stream myfile
instead.
Open a file
In order to open a file with a stream object we use its member function open():
All these flags can be combined using the bitwise operator OR (|). For example,
if we want to open the file example.bin in binary mode to add data we could do
it by the following call to member function open():
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app );
Each one of the open() member functions of the classes ofstream, ifstream
and fstream has a default mode that is used if the file is opened without a
second argument:
default mode
class
parameter
ofstream ios::out
ifstream ios::in
For ifstream and ofstream classes, ios::in and ios::out are automatically
and respectivelly assumed, even if a mode that does not include them is passed
as second argument to the open() member function.
Closing a file
When we are finished with our input and output operations on a file we shall
close it so that its resources become available again. In order to do that we
have to call the stream's member function close(). This member function takes
no parameters, and what it does is to flush the associated buffers and close the
file:
myfile.close();
Text files
Text file streams are those where we do not include the ios::binary flag in
their opening mode. These files are designed to store text and thus all values
that we input or output from/to them can suffer some formatting
transformations, which do not necessarily correspond to their literal binary
value.
Data output operations on text files are performed in the same way we operated
with cout:
void main () {
ofstream myfile
("example.txt");
getch();
}
Data input from a file can also be performed in the same way that we did with
cin:
void main () {
string line;
ifstream myfile
("example.txt");
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
getch();
}
This last example reads a text file and prints out its content on the screen.
Notice how we have used a new member function, called eof() that returns true
in the case that the end of the file has been reached. We have created a while
loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the
file has been reached).
References Books
1. Website: WWW.cplusplus.com