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

Programming I

Programming 101

Uploaded by

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

Programming I

Programming 101

Uploaded by

lightpop58
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Introduction To Computer And Programming

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

. [AASTU] Page 1
Introduction To Computer And Programming

II. Computer System


A computer system is composed of the components that are classified either as hardware
or software i.e. it is composed of two components computerhardware and software
Computer hardware
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
….

. [AASTU] Page 2
Introduction To Computer And Programming

The central processing unit (CPU) (microprocessor)


- it is most expensive and main component of a computer
- it consists of control unit (CU) , arithmetic and logic unit (ALU) and
registers The purpose of the CPU is
- to fetch instruction ( to read instruction from memory
- interpret instructions and determine actions
- 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.
- writedata : the result of execution may require writing a data to memory or output devices

The control unit (CU)


- is also known as the nerve center of the computer system
- it controls , supervises the overall activities of the computer
- monitors the execution of any program processed
- the CU coordinates and controls the activities of different components of the
computer system in the same way that the brain directs the action of human body

- Its primary function is to select and interpret instructions and to send appropriate

signals to other units in the computer . i.e. CU does not execute instructions rather it
directs to other units .

The arithmetic and logic unit (ALU)


- It performs Arithmetic operations (addition, subtraction, multiplication, division) and
logical operation like comparisons .It performs 90% of your computer job.

Registers

. [AASTU] Page 3
Introduction To Computer And Programming

- 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

RAM main (primary) memory


- it referred to random access memory
- it is directly accessible by ALU and CU
- it is possible to write a data to and read data from RAM
- it is a working area of a computer
- every location(cell) with in the RAM has unique address
- it holds temporarily the instructions and data elements that are currently being used in a
process
i.e. it is volatile (when the power is off the data erased )
- it is most expensive
- Semi-conductor memories are most widely used form of memories in today’s computers.
Semi-conductor memories are memories with faster access time, lower cost, reduced space
and high density, less power consumption than magnetic storage

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)

. [AASTU] Page 4
Introduction To Computer And Programming

- 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.

The commonly known magnetic storage devices are


o magnetic drum
o magnetic tape
o magnetic disk hard disk and floppy disk
Magnetic tapes
- is the earliest form of secondary storages
- is a ½ or ¼ inch ribbon of plastic like material coated with a thin layer of iron oxide
material
- a device called a tape drive reads and writes data to tape
- 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

. [AASTU] Page 5
Introduction To Computer And Programming

Disk

. [AASTU] Page 6
Introduction To Computer And Programming

- 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 indicates 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.

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

. [AASTU] Page 7
Introduction To Computer And Programming

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

. [AASTU] Page 8
Introduction To Computer And Programming

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.

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

. [AASTU] Page 9
Introduction To Computer And Programming

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 multimedia 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 hardcopy
- 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
LCD projector

. [AASTU] Page
10
Introduction To Computer And Programming

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

. [AASTU] Page
11
Introduction To Computer And Programming

an entire page at a time. 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)

Programming (Knowledge Transfer)


 Knowledge can be transferred from
Human to human

. [AASTU] Page
12
Introduction To Computer And Programming

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 from
human 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

a. Assume the first number is the smallest number.


b. Compare it with the next number and take the smallest.

. [AASTU] Page
13
Introduction To Computer And Programming

c. Repeat comparing until the list is exhausted.

Step 1: 4 => Smallest Number


Step 2: 3 => 3<4 ? True: 3=Smallest
Step 3: -1 => -1<3 ? True: -1= Smallest
Step 4: 6 => 6<-1 ? False: No change
Step 5: -4 => -4<-1 ? True: -4=Smallest
Step 6: 7 => 7<-4 ? False: No change

The list is exhausted and we have -4 as smallest number

2. Given following list, develop an algorithm which searches a number in


the list.

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.

. [AASTU] Page
14
Introduction To Computer And Programming

Pseudocode is an artificial and informal language that helps programmers


develops algorithms. Pseudocode is a "text-based" detail (algorithmic) design
tool.
The rules of Pseudocode are reasonably straightforward. All statements
showing "dependency" are to be indented. These include while, do, for, if,
switch. Examples below will illustrate this notion.
Pseudo-code is an informal way to express the design of a computer program
or an algorithm. The aim is to get the idea quickly and also easy to read
without details. It is like a young child putting sentences together without
any grammar. There are several ways of writing pseudo-code; there are no
strict rules. But to reduce ambiguity between what you are required to do
and what you express let’s base the pseudo code on the few defined
conventions and carry out the exercises.
 It represents an algorithm in an English line text.
 Some where between formal English and a programming
language.
 Must be language independent.
Examples:
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

. [AASTU] Page
15
Introduction To Computer And Programming

Display min
Stop
2. the program computes the sum, average and product of three numbers:

Read X, Y, Z
Compute Sum (S) as X + Y + Z
Compute Average (A) as S / 3
Compute Product (P) as X * Y * Z
Write (Display) the Sum, Average and Product
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
4. A program that calculate the average of 10 numbers:
set average to zero
set count to zero
set total to zero
read number
while ( not end-of-data )
increment count by 1
total = total + number
read number
if ( count > 0 ) then
average = total / count
display average

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.

. [AASTU] Page
16
Introduction To Computer And Programming

 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.

Examples:

. [AASTU] Page
17
Introduction To Computer And Programming

1. Draw a flowchart to add two numbers entered by user.

2. Draw flowchart to find the largest among three different numbers entered by user.

. [AASTU] Page
18
Introduction To Computer And Programming

3. Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0

4. A flowchart which calculates N! :

. [AASTU] Page
19
Introduction To Computer And Programming

. [AASTU] Page
20
Introduction To Computer And Programming

. [AASTU] Page
21
Introduction To Computer And Programming

5. A flowchart which shows all prime numbers smaller or equal to N :

. [AASTU] Page
22
Introduction To Computer And Programming

6. A flowchart which calculates all divisors of N :

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.

. [AASTU] Page
23
Introduction To Computer And Programming

Evolution of Programming Language


 Hardware programming
 Called hard wiring
 Software programming
1. Machine Language
 The first programming language.
 Consists of string of 0’s and 1’s.
 The one that CPU directly understand
2. Assembly Language
 Consists of symbolic instructions
E.g MOVE, INT, ADD, SUB etc
 It has to be converted into machine language before it is
used by the computer.

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.

. [AASTU] Page
24
Introduction To Computer And Programming

 Difficult to learn, write and debug.


 Machine dependent.
3. High level programming Languages
 Consists of convenient letters, symbols or English line text.
E.g cout<<endl;
Cout<<”Hello World”;

 There are more than 100 high level programming languages.


a. Structured: such as Basic, Pascal, Fortran
b. Object Oriented: such as C++, Java, Smalltalk
c. Windows Programming: Visual Basic, Visual C++,VB.Net

Problem Solving Steps

1. Understanding the Problem


a. Specify the program objects and program users
b. Specify output and input requirement
c. Specify processing
requirement Example:
Given f(x) = ax2+bx+c where a, b, c are real root and a≠0.
Input: a, b, c
Output: real roots
Process: Using Quadratic General Formula
2. Algorithm Development
a. Determine program logic through top-down approach
b. Design details using pseudo code and/or using flow chart
c. Test design with structure walk through

Note:
These are some basic things to apply

. [AASTU] Page
25
Introduction To Computer And Programming

I. Exercise the problem by taking several examples


II. Split the problem into manageable
pieces f(x) = ax2+bx+c
a≠0
Discriminator D=b2 - 4ac
D<0 then no real solution
D=0 then –b/2a is the only one solution
D>0 then –b+√( b2 - 4ac)/2a and –b-√( b2 - 4ac)/2a will be
the two solutions
III. Define the algorithm successively
Note: Algorithm should be
 A sequences of finite step
 Unambiguous
 Not designed for a particular case of problem

3. Program Coding (Program Development)


 Select the appropriate programming language.
 Code the program in that language following the syntax
carefully.
 Use the programming language.
1. Editor (Editing): to write the source code.
2. Compiler (Compiling): to convert source code into object
code.
3. Linker (Linking): convert object file into executable file.
4. Loader (Running): to load the program into RAM.
In C++:
 Start C++
 Write the source code and save it (*.CPP)
 Compile it (*.CPP -> *.OBJ)
 Link it (*.OBJ -> *.EXE)

. [AASTU] Page
26
Introduction To Computer And Programming

 Run it (Disk -> RAM)

4. Program Testing
 Check the program to discover errors
 Run the program and debug it.
 Run the program with real-world data.
Errors
1. Syntax Error (Compile-time error): it occurs when you violate the
syntax.
And it is called Compiler complaints because it is detected by the
compiler.

2. Logical Error (Run-time error): when the program generates


unexpected result. But there is no error in compilation. It
produces wrong output.

Debugging: isthe process of finding out and correcting program


error.

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

Asfaw k [AASTU] Page


27
Introduction To Computer And Programming

c. The infrastructure might be changed (Hardware, Operating


system)
 In the above cases maintenance is needed

2.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.

#include<iostream.h> and #include<conio.h>

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.

Asfaw k [AASTU] Page


28
Introduction To Computer And Programming

void 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.

This brace marks the beginning of the body of main.


cout<< "Hello World\n";

This line is a statement. A statement is a computation step which may


produce a value. The end of a statement is always marked with a
semicolon (;). This statement causes the string "Hello World\n" to be
sent to the cout output stream. A string is any sequence of characters
enclosed in double-quotes. The last character in this string (\n) is a
newline character which is similar to a carriage return on a type writer.
A stream is an object which performs input or output. Cout is the
standard output stream in C++ (standard output usually means your
computer monitor screen). The symbol << is an output operator which
takes an output stream as its left operand and an expression as its
right operand, and causes the value of the latter to be sent to the
former. In this case, the effect is that the string "Hello World\n" is sent
to cout, causing it to be printed on the computer monitor screen

getch()

Asfaw k [AASTU] Page


29
Introduction To Computer And Programming

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.

} This brace marks the end of the body of main.

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

Let us add an additional instruction to our first program:

// my second program in C++ Hello World! I'm a C++ program


#include<iostream.h>
#include<conio.h>
void main ()
{
cout<<"Hello World! ";
cout<<"I'm a C++ program";
getch();
}

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.

Kassahun T. Page
[AASTU] 30
Introduction To Computer And Programming

C++ supports two ways to insert comments:

// line comment
/* block comment */

We are going to add comments to our second program:

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
4 pay rate. */
Comment
5 int main (void)
6 {
7 int workdays = 5; // Number of work days per week
8 float work Hours = 7.5; // Number of work hours per
9 day float pay Rate = 33.50; //
10 Hourly pay rate
11 float weekly Pay; // Gross weekly
12 pay weekly Pay = workdays * work Hours * pay
13 Rate; cout<< "Weekly Pay = " <<weekly Pay<<
'\n';
}

/* my second program in C++ Hello World! I'm a


with more comments */ C++ program

#include<iostream.h>
#include<conio.h>

int main ()
{
cout<<"Hello World! "; // prints Hello

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

World!
cout<<"I'm a C++ program"; // prints I'm a
C++ program
getch();
}

Memory

A computer provides a Random Access Memory (RAM) for storing executable


program code as well as the data the program manipulates. This memory
can be thought of as a contiguous sequence of bits, each of which is capable
of storing a binary digit (0 or 1). Typically, the memory is also divided into
groups of 8 consecutive bits (called bytes). The bytes are sequentially
addressed. Therefore each byte can be uniquely identified by its address
(see Figure below).

Figure Bits and bytes in memory.


Byte Address

1211 1212 1213 1214 1215 1216 1217


... Byte Byte Byte Byte Byte Byte Byte ... Memory

1 1 0 1 0 0 0 1

Bit

The C++ compiler generates executable code which maps data entities to
memory 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

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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

Figure Representation of an integer in memory.


1211 1212 1213 1214 1215 1216 1217
... Byte Byte Byte 10110011 10110011 Byte Byte ... Memory
salary
(a tw o-byte integer w hose address is 1214)

While the exact binary representation of a data item is rarely of interest to a


programmer, the general organization of memory and use of addresses for
referring to data items (as we will see later) is very important.

Variables and Data


Types

Variables

In computer programming, a variable is a storage location and an associated


symbolic name (an identifier) which contains some known or unknown
quantity or information, a value. The variable name is the usual way to
reference the stored value; this separation of name and content allows the
name to be used independently of the exact information it represents. The
identifier in computer source code can be bound to a value during run time,
and the value of the variable may thus change during the course of program
execution. Variables in programming may not directly correspond to the
concept of variables in mathematics. The value of a computing variable is not

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

necessarily part of an equation or formula as in mathematics. In computing,


a variable may be employed in a repetitive process — assigned a value in one
place, then used elsewhere, then reassigned a new value and used again in
the same way (see iteration). Variables in computer programming are
frequently given long names to make them relatively descriptive of their use,
whereas variables in mathematics often have terse, one- or two-character
names for brevity in transcription and manipulation.

A variable storage location may be referred by several different identifiers, a


situation known as aliasing. Assigning a value to the variable using one of the
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,
the data stored in the location may be changed during program execution.

We can define a variable as a portion of memory to store a determined value.

Each variable needs an identifier that distinguishes it from the others, for
example, 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

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

to identity, identification (the process of identifying), or an identifier (that is,


an instance of identification).

A valid identifier is a sequence of one or more letters, digits or underscore


characters (_). Neither spaces nor punctuation marks or symbols can be part
of an identifier. Only letters, digits and single underscore characters are
valid. In addition, variable identifiers always have to begin with a letter. They
can also begin with an underline character (_ ), but in some cases these may
be reserved for compiler specific keywords or external identifiers, as well as
identifiers containing two successive underscore characters anywhere. In no
case they can begin with a digit.

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

Very important: The C++ language is a "case sensitive" language. That


means that an identifier written in capital letters is not equivalent to another
one with the same name but written in small letters. Thus, for example, the
RESULT variable is not the same as the result variable or the Result variable.
These are three different variable identifiers.

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

salary // valid identifier


salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
_salary // valid identifier
Salary // valid but distinct from salary

Fundamental data types

In computer science and computer programming, a data type or simply


type is a classification identifying one of various types of data, such as real-
valued, integer or Boolean, that determines the possible values for that
type; the 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.

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.

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:

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

Name Description Size Range*


signed: -128 to 127
char Character or small integer. 1byte
unsigned: 0 to 255
short int signed: -32768 to 32767
Short Integer. 2bytes
(short) unsigned: 0 to 65535

signed: -32768 to 32767


int Integer. 2bytes
unsigned: 0 to 65535

signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295

float Floating point number. 4bytes 3.4e +/- 38 (7 digits)


Double precision floating
double 8bytes 1.7e +/- 308 (15 digits)
point number.

long Long double precision floating


10bytes 1.7e +/- 308 (15 digits)
double point number.

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 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
[Type here] [Type here] [Type here]
Introduction To Computer And Programming

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:

// operating with variables 4

#include<iostream.h>

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

#include<conio.h>

void main ()
{
// declaring variables:
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:


getch();
}

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

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.

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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.

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.

For example, if we want to declare an int variable called a initialized with a


value of 10 at the moment in which it is declared, we could write:

int a = 10;

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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.

Although a constant's value is specified only once, a constant may be


referenced many times in a program. Using a constant instead of specifying a
value multiple times in the program can not only simplify code maintenance,
but it can also supply a meaningful name for it and consolidate such constant
bindings to a standard code location (for example, at the beginning).

Constants are expressions with a fixed value.

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.

Exercises

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

1. Which of the following represent valid variable definitions?


int n = -100;
unsigned inti = -
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";
2. Which of the following represent valid identifiers?
identifier
seven_11
_unique_
gross-
income
gross$incom
e 2by2
default
average_weight_of_a_large_pizza

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

variable
object.oriented

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

Operators

Assignment (=)

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

The assignment operator assigns a value to a variable.


a = 5;

This statement assigns the integer value 5 to the variable a.

a = b;

Here also assign the value of b into 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:

// assignment operator a:4 b:7


#include<iostream.h>
#include<conio.h> void
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;
getch();
}

The following expression is also valid in C++:

a = b = c = 5;

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

It assigns 5 to the all the three variables: a, b and c.

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

C++ provides five basic arithmetic operators (+, -, *, /, %).


Except for remainder (%) all other arithmetic operators can accept a mix of
integer and real operands. Generally, if both operands are integers then the
result will be an integer. However, if one or both of the operands are reals
then the result will be a real (or double to be exact).
When both operands of the division operator (/) are integers then the division
is performed as an integer division and not the normal division we are used
to. Integer division always results in an integer outcome (i.e., the result is
always rounded down). For example:
9/2 // gives 4, not 4.5!
-9 / 2 // gives -5, not -4!
To obtain a real division when both operands are integers, you should cast
one of the operands to be real:
Int cost = 100;
Int volume = 80;
Double unitPrice = cost / (double) volume; // gives 1.25
The remainder operator (%) expects integers for both of its operands. It
returns the remainder of integer-dividing the operands. For example 13%3 is
calculated by integer dividing 13 by 3 to give an outcome of 4 and a
remainder of 1; the result is therefore 1.
It is possible for the outcome of an arithmetic operation to be too large for
storing in a designated variable. This situation is called an overflow. The
outcome of an overflow is machine-dependent and therefore undefined. For
example:
unsigned char k = 10 * 92; // overflow: 920 > 255

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

It is illegal to divide a number by zero. This results in a run-time division-by-


zero failure which typically causes the program to terminate.

The five arithmetical operations supported by the C++ language are:

+ addition
- subtraction
* multiplication
/ division
% modulo

Operations of addition, subtraction, multiplication and division literally


correspond with their respective mathematical operators. The only one that
you might not be so used to see may be 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.

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:

expression is equivalent to
value += increase; value = value + increase;

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 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

// compound assignment operators 5


#include<iostream.h>
#include<conio.h>
void main ()
{
int a, b=3;
a = b;
a+=2; // equivalent
cout<< a; to a=a+2
getch();
}
An assignment operation is itself an expression whose value is the value
stored in its left operand. An assignment operation can therefore be used as
the right

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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.

Example 1 Example 2

[AASTU] Page
49
Introduction To Computer And Programming

B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B contains 4

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.

int k = 5;

Increment and decrement operators.


Operator Name Example
++ Auto ++k + 10 // gives 16
Increment
(prefix)
++ Auto k++ + 10 // gives 15
Increment
(postfix)
-- Auto --k + 10 // gives 14
Decrement
(prefix)
-- Auto k-- + 10 // gives 15
Decrement
(postfix)
Both operators can be used in prefix and postfix form. The difference is
significant. When used in prefix form, the operator is first applied and the
outcome is then used in the expression. When used in the postfix form, the
expression is evaluated first and then the operator applied.

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.

== Equal to
!= Not equal to

[AASTU] Page
50
Introduction To Computer And Programming

[AASTU] Page
51
Introduction To Computer And Programming

> Greater than


< Less than
Greater than or equal
>=
to
<= Less than or equal to

Here there are some examples:

(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,

(a == 5) // evaluates to false since a is not equal to 5.


(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or 5 <= 5 // gives 1
Equal
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or 6.3 >= 5 // gives 1
Equal

Logical operators ( !, &&, || )

[AASTU] Page
52
Introduction To Computer And Programming

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:

!(5 == 5) // evaluates to false because the expression in (5


== 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be
false.
!true// evaluates to false
!false// evaluates to true.
Operator Name Example
! Logical !(5 == 5) // gives 0
Negation
&& Logical And 5 < 6 && 6 < // gives 1
6
|| Logical Or 5 < 6 || 6 < // gives 1
5

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
true true true
true false false
false true false

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

false false false

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
true true true
true false true
false true true
false false false

For example:

( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false


).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false
).

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:

condition ? result1 : result2

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

// conditional operator 7

#include<iostream.h>
#include<conio.h>
void main ()
{
Inta,b,c;
a=2;
b=7;
c = (a>b) ? a : b;

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

7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.


7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is
greater than 3.
a>b ? a : b // returns whichever is greater, a or b.

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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 valuespecified 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.

Basic Input/output

Standard Output (cout)

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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.
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:

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:

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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

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;

would print out:

First sentence.
Second sentence.

Standard Input (cin).

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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.

// i/o example Please enter an integer value:


702
#include<iostream.h> The value you entered is 702 and
#include<conio.h> its double is 1404.

void main ()
{
inti;
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:

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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.

cin and strings

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:

// cin with strings What's your name? Juan Souli�


#include<iostream.h> Hello Juan Souli�.
#include <string.h> What is your favorite team? The
#include <iostream.h> Isotopes
#include<conio.h> I like The Isotopes too!

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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.

Simple Type Conversion

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

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

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

1. Write expressions for the following:


 To test if a number n is even.
 To test if a character c is a digit.
 To test if a character c is a letter.
 To do the test: n is odd and positive or n is even and negative.
 To give the number of characters in a null-terminated string literal
s.
2. Add extra brackets to the following expressions to explicitly show the
order in which the operators are evaluated:

[Type here] [Type here] [Type here]


Introduction To Computer And Programming

(n <= p + q && n >= p - q || n ==


0) (++n * q-- / ++p - q)
(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; charc = '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.

[Type here] [Type here] [Type here]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy