You are on page 1of 245

Introduction to

Computer

MELJUN CORTES
Computer System
ELEMENTS OF
COMPUTER SYSTEM
HARDWARE
– PHYSICAL COMPONENT OF
THE COMPUTER SYSTEM
– TANGIBLE PARTS
SOFTWARE
– PROGRAMS THAT DIRECT THE
OPERATION OF THE COMPUTER
PEOPLEWARE
– THE USERS OF THE COMPUTER
Computer Hardware
HARDWARE

INPUT HARWARE PROCESS


DEVICES HARDWARE
KEYBOARD DEVICE
SCANNERS CPU
POINT & DRAW MOTHERBOARD
DEVICES(MOUSE, VIDEO CARD
JOYSTICK,TRACK SOUND CARD
BALL, ETC) EXPANSION SLOT
HARDWARE
OUTPUT STORAGE
HARDWARE HARDWARE
DEVICE DEVICE
MONITOR MAGNETIC TAPE
PRINTER HARDDISK
PLOTTER FLOPPY DISK
ON-SCREEN COMPACT DISK
PROJECTOR
DVD
HARDWARE
TELECOMMUNICATI OTHER HARDWARE
ON HARDWARE UNINTERRUPTIBL
LAN CARDS E POWER
SUPPLY(UPS)
TRANSMISSION
A STANDBY
CABLES(COAXIAL BATTERY
CABLE,FIBER POWERED
OPTIC,SATTELLIT SOURCE USE IN
ES) CASE OF POWER
INTERRUPTIONS
Computer Software
Computer Software
GENERAL-PURPOSE SOFTWARE
– PROVIDES THE FRAMEWORK FOR A GREAT
NUMBER OF BUSINESS,SCIENTIFIC, AND
PERSONAL APPLICATIONS
APPLICATIONS SOFTWARE
– DESIGNED AND WRITTEN TO PERFORM
SPECIFIC BUSINESS,SCIENTIFIC
PROCESSING TASKS SUCH AS INVENTORY
OR TAX PREPARATION
Computer Software

SYSTEM SOFTWARE
– INDEPENDENT OF ANY GENERAL-
PURPOSE SOFTWARE PACKAGE OR
ANY SPECIFIC APPLICATION AREA
– CONTROLS OR IN SOME WAY
SUPPORTS SOFTWARE IN THE
OTHER TWO CATEGORIES
EXAMPLES OF
GENERAL-PURPOSE
SOFTWARE
WORD PROCESSING SOFTWARE
– MS WORD,AMI-PRO,WORDSTAR, ETC.
ELECTRONIC SPREADSHEETS
– MS EXCEL,LOTUS 123,QUATTRO, ETC.
DESKTOP PUBLISHING
– PAGEMAKER,VENTURA ETC.
EXAMPLES OF
GENERAL PURPOSE
SOFTWARE
GRAPHICS /PRESENTATION
SOFTWARE
– PHOTOSHOP,PAINT, COREL
DRAW,MS POWERPOINT,
PRINTSHOP,BANNER MANIA,
DATABASE SOFTWARE
– DBASE,FOXBASE,FOXPRO,CLIPPER
ETC.
EXAMPLES OF
APPLICATION SOFTWARE
THESE ARE PROGRAMS OR SYSTEMS
DEVELOPED THRU DIFFERENT
PROGRAMMING LANGUAGES
INVENTORY SYSTEM, POINT-OF-SALE
SYSTEM, ENROLLMENT SYSTEM,
BILLING SYTEM, PAYROLL SYSTEM,
SCHEDULING OR APPOINTMENT
SYSTEM ETC.
TYPES OF SYSTEM
SOFTWARE
OPERATING SYSTEM
– DISK OPERATING SYSTEM(DOS) ,
WINDOWS OS & XENIX FOR
MICRO COMPUTERS
– UNIX FOR MINICOMPUTER
& MAINFRAME COMPUTERS
– IBM’S MVS & VM
– DEC’S VMS
– AT&T’S UNIX
TYPES OF SYSTEM
SOFTWARE
PROGRAMMING LANGUAGES
– COMPILERS & INTERPRETERS
– 1ST GEN. OF PROGRAMMING
LANGUAGES(MACHINE LANGUAGE)
– 2ND GEN. OF PROGRAMMING
LANGUAGES(ASSEMBLY LANGUAGE)
– 3RD GEN. OF PROGRAMMING
LANGUAGES(PROCEDURE ORIENTED)
COBOL,BASIC,PASCAL,C, ETC
PROGRAMMING
LANGUAGES
4TH GEN. OF PROGRAMMING
LANGUAGES(OBJECT-ORIENTED)
– VISUAL BASIC,VISUAL FOXPRO,VISUAL C++,
ETC.
5TH GEN. OF PROGRAMMING LANGUAGES
– ARTIFICIAL INTELLIGENCE
– NATURAL LANGUAGES
OTHER TYPES OF
SYSTEM SOFTWARE
DATABASE MANAGEMENT SYSTEM
SOFTWARE(DBMS)
– SQL,INFORMIX,ORACLE, ETC.
UTILITY PROGRAMS
– NORTON DISK DOCTOR(NDD),PC TOOLS
PERFORMANCE
MONITORING SOFTWARE
COMMUNICATIONS SOFTWARE
OTHER SOFTWARE
GAMES
VIRUS
– BOOT-SECTOR,TROJAN
HORSE,MACRO
ANTI-VIRUS
PROGRAMS(VACCINES)
BROWSERS
– NAVIGATOR, INTERNET EXPLORER
PEOPLE WARE
ORGANIZATION
MANAGEMENT
– MIS HEAD,EDP HEAD, MIS
PLANNER,CHIEF INFORMATION
OFFICER(CIO)
– PLAN,ORGANIZE,CONTROL,STAFF,DI
RECT,BUDGET ETC.
PEOPLEWARE
ANALYSIS & DESIGN
– SYSTEM ANALYSTS
PROGRAMMING
– PROGRAMMER(SYSTEM OR APPLICATION)
– TRAINEE/JR./SR. PROGRAMMER
NETWORK ADMINISTRATION
– NETWORK ADMINISTRATOR
– DATA BASE ADMINISTRATOR
PEOPLE WARE

OPERATIONS
– COMPUTER OPERATOR
– COMPUTER LIBRARIAN
– COMPUTER ENCODER ETC.
TECHNICAL SUPPORT
– COMPUTER TECHNICIAN
EDUCATION & TRAINING
– TRAINORS
Computer Languages
Programming
Languages
A programming
language is a set of
rules that provides a
way of telling a
computer what
operations to
perform.
Generations of
Programming Languages
There are several generations of
programming languages:
Machine
Assembly
High-level
Very high-level
Natural
Major Programming
Languages
There are several languages with
which to write your program:

• FORTRAN • C
• COBOL • • C++
BASIC • • Java
Pascal • Object-Oriented
Program Logic
Formulation
Definition of
Programming
Programming
Computer process data under
the control of set of instructions.
Programmer
Computer program guide the
computer through orderly sets
of actions by people.
Programming Cycle
The computer is basically a
problem-solving tool. Once it is
properly provided with a valid
program, the computer becomes self-
operational, that is, it requires no
human intervention during processing.
To use this tool effectively, the
programmer usually ha to perform the
following set of well define steps.
Programming Cycle
Defining the Problem
One of making sure what was has to
be done or what problem has to be
solved. A careful analysis of that need
should involved both prospective users
of the information and one or more
trained systems designers or
programmers, who can perceive the full
nature of the information need and how
the computer can be used to respond
to it.
Planning the Solution
This is the next step, after the
problem has been defined, select
the best method for solving the
problem. This commonly
involves determining the
sequence of processing steps
within individual programs.
To save on time and effort, the
programmer refers to a pictorial
representation, the program flow chart.
The flow chart is an all-purpose tool and
a program blueprint. The programmer
constructs the flow chart to lay out the
program logic.
Coding the Solution
Once the programmer is satisfied that all
processing steps have been identified and all
alternatives and exceptions provided for, the
program is then made. The program flow chart
serves as a guide in coding.
Checking out the Program
Experience will prove that a program seldom
executes successfully the first time. Even the
simplest programs contain errors, and even
experienced programmers make mistakes.
Documentation
After a program has been fully tested
and implemented, the programmer must
write up the full specifications for all
users. The technical documentation
package should include:
1. Complete statement of the problem.
2. Description of the program logic
and copies of the flow charts.
3.Final source listing
4. List and description or error tests along
with the disposition of these error.
5. Operating instructions, including
program and data structures, and test
data used.
6. Input and output specifications.
7. Schedules to be maintained.
If all the pertinent data is contained
within the documentation package, then the
program can be run and modified without
requiring the original programmer’s assistance.
The Programming Cycle
DOCUMEN Write up the full
specifications for other
TATION
program users
Defining what DEFINING
has to be done or THE
what problem PROBLEM
has to be solved

Perform
CHECKING debugging
OUT THE and testing the
PLANNING PROGRAM program,
THE
SOLUTION using
CODING representative
s input data
Select the best method for THE
solving the problem SOLUTION

Prepare the set of instructions


for the computer to execute
Program Design Tools:

Flowchart
A flowchart is a
pictorial
representation of
a step-by-step
solution to a part
of a problem.
Flowchart Basics
A flowchart
consists of arrows
to represent
direction the
program takes and
boxes and symbols
to represent
actions.
Pseudocode
Pseudocode is an English-like
nonstandard language.
It allows programmers to focus on the
program logic without being
concerned about the particulars of a
formal programming language.
Algorithms
An algorithm is a logical sequence of steps
leading to the solution of ONE TASK in a
bigger problem
– Define expected OUTPUT
– Describe desired INPUT
– Determine PROCESSING needed to
produce desired output from
expected input
Sample Problem
What tasks need to be
done?
Add Number 1
and Number 2
– Inputs/Outputs?
– Process?
Subtract Number
2 from Number 1
– Inputs/Outputs?
– Process?
Use Modularity for
Design
Break the problem into separate tasks
For EACH task
– What are the inputs (if any)?
– What are the outputs (if any)?
– What process must be done?
Construct pseudocode or flowchart
Flowcharting
Types of Flowcharts

1. Program Flowchart

It describes graphically in detail the logical


operations and steps within a program and the
sequence in which these steps are to be executed
for the transformation of data to produce the
needed output.
2. System Flowchart

It is a graphically representation of
the procedures involved in converting data on
input media to data in output form. It illustrates
which data is used or produced at various points
in a sequence of operation.

It portray the interaction among data,


hardware, and personnel.
Flowchart Symbols
Input/Output Start/Stop

Process Connector

Flow Lines
Decision

Flow Direction
Preparation Indicators
Flowcharting Symbols
Input/Output
Parallelogram

• It represents an instruction to an input or an


output device.

Process Rectangle

• This symbol is used to represent a group of program


instructions that perform a processing function of the
program such as to perform arithmetic operations, or
to compare, sort, etc.
Flowcharting Symbols

Decision Diamond

• It denotes a point in the program where more


than one path can be taken. It is used to document
points in the program where, based upon variable
conditions, a branch to alternative path is possible.
The particular path that is chosen depends on the
answer to a question or the result of a test which is
inserted in the symbols.
Flowcharting Symbols
Preparation
Hexagon

• This symbols used to represent an instruction or


group in instructions that will alter, or modify a
program’s course of execution. It is commonly
used to specify operations such as control, index
register, initialization, switch setting, and in
indicating loops.
Flowcharting Symbols
Start/Stop Oval

• It is used to designated the beginning and the


end of a program, or a point of interruptions.

Connector Small Circle

• This is a nonprocessing symbols which is used to


connect one part of a flowchart to another without
drawing flow lines. It denotes an entry or an exit from
another part of the flowchart and also used to change
the reading sequence of a flowchart on the same page.
Flowcharting Symbols

Arrowheads

• Used to show the direction of processing or


data flow. These are added to flow lines of a
flowchart appears confusing in its layout.
Flowcharting Symbols

Horizontal/
Vertical Lines

• It is used to show reading order or sequence


in which flowchart symbols are to be read.
Advantage and Disadvantage
of Flowcharts
Advantage of Flowcharts

1. Since flowcharts are language-independent,

they can be learned and applied without formal

knowledge of a programming language.

2. It enforces users to give attention to significant

matters over the less significant ones.


3. Being graphically portrayed, flowcharts

provide an alternative to the usual narrative

description of a system or a program.

4. Flowcharts are easier to understand than a

program written in a particular programming

language.
Disadvantage of Flowcharts
1. Flowcharts do not represent a programming

and are more of a person-to person than a person-

to-computer means of communication. A computer

cannot accept a program describe in flowcharting.

2. Since thinking in graphic term is not normal,

flowchart cannot be viewed as a natural means of


communication.
3. Certain details often require long sequence

of interconnected symbols which could easily be

described in just a few lines of explanation.

4. It does not convey why a given set of

operations is made. Flowcharts only portray how.


5. Flowcharts do not highlight the important
details since each step receives as much attention in
a flowchart as any other.
Two flowcharts needed
Task 1 Task 2
Start Start

Get Get
Number 1 Inputs Number 1

Get Get
Number 2 Number 2

Result = Result =
Number 1 + Number 2
Process Number 1 - Number 2

Display Result Outputs Display Result

End End
Sample Problem
Example 1 - Algorithms

Algorithms for changing a


flat tire

1. Jack up the car


2. Unscrew the lugs
3. Remove the wheel
4. Put on the Spare
5. Screw the lugs
6. Jack the car down
Example 1 - Flowchart
Flowchart for changing a flat
tire. Start A

Put on the spare


Jack up the Car

Screw on the lugs


Unscrew the lugs

Remove the wheel Screw on the lugs

A End
Example 2

Given the three numbers A, B,


C. Draw a flowcharts to
compute and print out the
sum, the average, and the
product of these values.
Example 2 - Algorithms
1. Read in the values of A, B, C.
2. Determine the sum of the three values
read.
3. Compute the average by dividing
the sum by 3.
4. Multiply the first value by the second
value then by the third value to
determine the product of the three
values.
5. Print out the computed values
(sum, average, and the product).
Example 2 - Flowchart
A
Start

Ave = Sum/3

Read
A,B,C
Prod = A*B*C

Sum = A+B+C Print Sum


Ave, Prod

A
End
Decision Making –
Sample Problem
Example 3
The ABC Manufacturing Company plans
to give a year-end bonus to each of its
employees. Make an algorithms which
will compute the bonus of an employee.
Consider the following criteria: If the
employee’s monthly salary is less than
1,000.00 pesos, the bonus is 50% of the
salary; for the employees with salaries
greater than 1,000.00 pesos, the bonus
is 1,000.00. Print out the name and
corresponding bonus of the employee.
Example 3 - Algorithms
1. Read in the employee’s name and salary
2. Test if the employee’s salary is less than
1,000.00
3. If the salary is less than 1,000.00 pesos,
the bonus is 50% of the employee’s
salary. However, if the salary is more
than 1,000.00 pesos, the bonus is
1,000.00 pesos.
4. Print out the employee’s name and
bonus.
Example 3 - Flowchart
A
Start

Read Bonus = .05 Is Salary Bonus


+ Salary < 1000
Name, = 1000
Salary B
Print Sum B
A
Ave, Prod

End
Example 4

Given two numbers X and Y. Draw a


flowchart to determine the difference
between X and Y. If X-Y is negative,
compute R=X+Y, if X-Y is zero, compute
R=2X+XY; and if X-Y is positive,
compute R=X*Y. Print out the values of
X, Y, and R.
Example 4 - Algorithms
1. Read in the values of X and Y
2. Subtract Y from X

3. If the difference between X -Y is


negative, compute R=X+Y, if zero,
compute R=2X+XY; and if X-Y is
positive, compute R=X*Y.
4. Print out the values of X, Y and R.
Example 4 - Flowchart
A
Start

Read R=X+Y <0 If Diff >0 R=X*Y


X, Y B
=0
Diff = X - Y
Print X, R = 2X+2Y B
Y, R
A

B
End
Example 5

Create a Flowchart and algorithms that


would input five values of numbers and
compute for the average. If the average
is below 75, the remarks is failed, if not
remark is passed. Print the average,
remarks.
Example 5 - Algorithms
1. Read in the values of n1, n2, n3, n4, and n5
2. Compute the average of the five values read.
3. If the the average is below 75, the remark
is failed, if not the remark is passed
4. Print out the average and the remarks.
Example 5 - Flowchart
Start A

Read n1, Y Is
n2, n3, Rem = average N Rem =
n4, n5 Failed
<75 Failed

ave =
(n1+n2+n3+n4+ Print Ave,
n5)/5 Rem

A
End
Loop and Counter
Steps in Control Loop
1. Initialization - the value of a counter used is initially
set equal to zero ( or one ). This process is always
done outside the loop.
2. Test for Limit Conditions - before logic flows gets
out of a loop, a loop-terminating condition must first
be satisfied. The process of testing is usually found
either at the beginning or at the end of a loop.
3. Incrementation - after each loop is executed, 1 is
added to the counter. Thus the counter reflects the
number of times the operation has been
performed. Note that process of incrementation is
always done within the loop.
Looping
- is used when it is desired to make the same
calculation on more than one set of data.
- it consists of repeating a program, or a section of a
program, and substituting new data for each repetition.

Counters
- is set up in a program loop to keep track of the
number of times the program segment is repeated.
- the program can then be terminated after the
completion of a predetermined number of passes.
- Prior to the execution of counting, all counters should
be initialized ( usually to zero) before the loop is
executed.
- For instance, if a program is supposed to read
and print five data values, a counter may be set
up in the program which counts the number of
data values; after a data value is read and
printed, the counter is increased by one. Before
a new data value is allowed to be read, a
conditional transfer may be used to determined
whether or not the desired amount of data has
been reached. If it has, the program is
terminated; otherwise an unconditional transfer
causes the computer to repeat the input/output
and other processing operations.
Example 1

The initial value of the radius of a


circle is equal to one unit and each
succeeding radius is one unit greater
than the value before it. Draw a
flowchart to compute the area of the
circle starting with R=1.0 up to R=5.0,
then print out each radius and the
corresponding area of the circle.
Example 1 - Algorithms
1. Initialized the value of R to 1 and the value
of PI to 3.1416
2. Compute area by multiplying PI by the
square of R.
3. Print out the value of R and the square of R.
4. Increment the value of R by 1.
5. Test if R is less than or equal to 5
6. If R is less than than or equal to 5, loop back
and repeat step 2 through 5. However, if R is
greater than 5, stop processing.
Example 1 - Flowchart
A
Start

R=1.0
Print R,
PI = 3.1416 AREA

B
AREA = R=R+1.0
PI *R*R

A B Y Is R < = N End
5.0 ?
Example 2

Given a set of 5 numbers that include


both positive and negative data values.
Draw a flowchart to read in these values
one at a time and count the number of
positive values (including zero values)
and the number of negative values
found in the set. After the required
values are determined, print out these
counted values.
Example 2 - Algorithms
1. Set up two counters and initialized their values
to zero (one counter, NNEG, is used for
counting the number of negative values and
the other, NPOS, for counting positive values).
2. Input the first data value, NO.
3. Test and determine if the the value read is
positive or negative (The decision symbol is
used and in it is written the question, NO<0?)
4. If the value of NO is negative ( or less than
zero), increment the NNEG counter by
one. However, if it is positive ( or equal to
or greater than zero), increment the NPOS
counter.
Example 2 - Algorithms
5. Determine the number of values
encountered (NVAL) by adding the two
counters (NNEG and NPOS).
6. Test if NVAL is equal to 5
7. If the value of NVAL is not equal to 5,
repeat steps 2 through 5. However, if it
is equal to 5, print out the current
value stored in these counters (NNEG
and NPOS)
Example 2- Flowchart
Start A

NNEG = 0
NNEG = Y N
Is NO NPOS =
NPOS = 0 NNEG + 1 <0 NPOS + 1

Read
NVAl = NNEG
NO
+ NPOS
B

End
A
Example 3

Draw a flowchart and algorithms which


will read and print the names and
individual scores of 100 students for a
particular examination. Also, determine
their average and score, and print it out.
Example 3 - Algorithms
1. Initialize the counter (CTR) and
accumulator (sum) to zero.
2. Read in the student’s name and score. Print
3. out the student’s name and score.
4. Accumulate the data value (SCORE) into
the sum.
5. Test if the desired amount of data (100) has
been reached.
6. If the value of counter (CTR) is less than 100,
repeat the steps 2 through 5. However, if the
desired amount of data has been reached
(100), compute the average score by
dividing the sum by the value of counter.
Example 3 - Algorithms

7. Print out the average scores.


Example 3 - Flowchart
Start A

CTR=0 SUM = SUM + SCORE


SUM=0
B

Read Ave = Y Is CTR N CTR = CTR + 1 =


Name, SUM/CTR 100?
SCORE
Print
B
A Ave

End
Example 4
Given the lengths of 3 sides (a, b, and c)
of a triangle. Prepare a flowchart to read
these values, compute the perimeter
and the value of S, and determine the
area of the triangle using Hero’s
formula (Hint: Per = a + b + c; S=Per/2;
and the AREA=[s(s-a) (s-b) (s-c)]2. Then
print out the given and computed
values.
Example 4 - Flowchart
Start A

CTR=0 Perimeter = a + b + c
C

Read Is Y
a, b, c Per < Print
CTR
0?

A
1
Example 4 - Flowchart
B
1

N
Is Print
S = Per/2
End Area = 0 ? a, b, c
Per, S,
Area

Area = s(s-a) (s-b) (s-c)


CTR=CTR+1

B
C
Loop and Accumulator
•Accumulator
The variable used is thereby
continuously accumulating the
numerical quantities
Example 1

Draw a flowchart to compute and


print the sum of the squares of
positive integers from 1 to 100.
Example 1 – Flowchart-Sol 1- K<=100
Start A

K=1
Sum = 0 B

Y Is
K=k+1 B N
k<=100? Print
sum

Sum = Sum + 1
End

A
Example 1 – Flowchart-Sol 2 – K=100
Start

Print Y Is N K=K+1
sum K =100?
K=1
Sum = 0

B End B
Sum = Sum + K2

A
Example 1 – Flowchart-Sol 3 – K>100
Start A
N
K=1
Sum = 0 Sum = Sum + K2
B

Is Y Print

K > 100? sum K=k+1

A End B
Example 2

Make a flowchart that will display


the numbers from 1 – 5.
Example 2 - Flowchart
Start A

A=1 Print
A

F A=A+1
B If A <
End
=10?
T

B
A
Example 3

Draw a flowchart to compute and


print the sum of the square of
positive integer from 1 - 5
Example 3 - Flowchart
Start A

X=1 A=A+1
Sum = 0
If A < F
Print
Sum = Sum + B
=5? Sum
(A*A)
T

End
A B
Example 4

Create a flowchart that will print the


product numbers from 1 - 5
Example 4 - Flowchart
Start A

A=1 Prod = A * Prod


Prod = 0

A=A+1

B If A < F Print
Prod
=5?
B
T

End
A
CS 25
Introduction
to
C++
History of C and C++
C++ evolved from C, which evolved from two
previous programming language, BCPL, and B
language.
BCPL
was developed in 1967 by Martin Richard as
a language for writing operating system
software and compilers.

B language
was developed by Ken Thompson.
C language
was evolved from B language, it is a
programming language design by Dennis
Ritchie in 1972 at AT & T Laboratories.

C++
- an extension of C, was developed by
Bjarne Stroustrup in the early 1980’s at
Bell Laboratories .
provides a number of features that “spruce
-

up” the C language, but importantly, it

provides capabilities for object-oriented


programming.
Advantage and
Disadvantage of C++
The advantage of creating functions and
classes is that we will know exactly how they
work. We will be able to examine the C++ code.

The disadvantage is the time consuming and


complex effort that goes into designing,
developing and maintaining new functions and
classes that are correct and that operate
efficiently.
The C++ Environment
Editor
the first phase of C++ environment, use to
create program source codes. It is where
you type the program.

Preprocessor
the second phase of C++ environment, use
to the programs executes automatically before
the compiler’s translation phase begin.
Compiler
the third phase of C++ environment, use to
compile source codes into machine
language.

Linker
the fourth phase of C++ environment, use to
convert (.cc) file to executable file (.c)

Loader
the fifth phase of C++ environment, use to
puts program in memory.
CPU
the sixth phase of C++ environment, use to
takes each instruction and executes it, possibly
storing new data values as the program
executes.
C++ Program Layout
General
Structure/Format of C++
/ my first program in
C++ #include
<iostream.h> int
main ()
{
cout << "Hello
World!"; return 0;
}
C++ Program Layout
General
Structure/Format of C++
// my first program in C++
This is a comment line. All the lines beginning
with two slash signs // are considered
comments and do not have any effect on the
behavior of the program. They can be used by
the programmer to include short explanations
or observations within the source itself. In this
case, the line is a brief description of what our
program does.
#include <iostream.h>
Sentences that begin with a pound
sign # are directives for the preprocessor.
They are not executable code lines but
indications for the compiler. In this case the
sentence #include <iostream.h> tells the
compiler's preprocessor to include the
iostream standard header file. This
specific file includes the declarations of the
basic standard input-output library in C++,
and it is included because its functionality is
used later in the program.
int main ()
This line corresponds to the
beginning of the main function
declaration. The main function is the
point where all C++ programs begin
their execution. It is independent of
whether it is at the beginning, at
the end or in the middle of the code - its
content is always the first to be
executed when a program starts. In
addition, for that same reason, it is
essential that all C++ programs have a
main function. Cont.
main is followed by a pair of
parenthesis () because it is a function. In
C++ all functions are followed by a pair
of parenthesis () that, optionally, can
include arguments within them. The
content of the main function
immediately follows its formal declaration
and it is enclosed between curly brackets
{ },
{ - left brace
it must begin the body of every
function.
} - right braces
it must end the body of each function.
cout << "Hello World";
- it is used to output information to the
screen.

Cont.
- This instruction does the most important
thing in this program. cout is the standard
output stream in C++ (usually the screen), and
the full sentence inserts a sequence of
characters (in this case "Hello World") into this
output stream (the screen). cout is declared in
the iostream.h header file, so in order to be
able to use it that file must be included.

Cont.
Notice that the sentence ends with a
semicolon character (;). This character
signifies the end of the instruction and
must be included after every instruction
in any C++ program (one of the most
common errors of C++ programmers is
indeed to forget to include a semicolon
( at the end of each instruction).
return 0;
The return instruction causes the main()
function finish and return the code that the
instruction is followed by, in this case 0. This it
is most usual way to terminate a program that
has not found any errors during its execution.
As you will see in coming examples, all C++
programs end with a sentence similar to this.
Program 1 – output the
information
Sample Output

Jose Rizal University

Name : Mary Ann Bernadette Taduyo

Course : BS in Computer Science

Subject : CSC 25

This is my first program using the standard insertion


stream operator
Program 1 – output the
information
/ Exercises 1
#include <iostream.h>
int main ()
{
cout << “Jose Rizal University";
cout << “Name : Mary Ann Bernadette Taduyo";
cout << “Coure : BS in Computer Science";
cout << “Subject : CSC 25";
cout << “This is my first program using the standard
output stream operator";
return 0;
}
Program 2– output the
information
Sample Output
Jose Rizal University

Name of Student : Mary Ann Berndette Taduyo


Subject : CSC 25

Quiz 1 : 100

Quiz 2 : 95

Quiz 3 : 70

Quiz 4 : 85

Quiz 5 : 90
Program 2 – output
/ Exercises 2 the information
#include <iostream.h>
int main ()
{
cout << “Jose Rizal University\n";
cout << “Name : Mary Ann Bernadette Taduyo\n";
cout << “Coure : BS in Computer Science\n";
cout << “Subject : CSC 25\n";
cout << “ Quiz 1 : 100\n”;
cout << “ Quiz 2 : 95\n”;
cout << “ Quiz 3 : 70\n”;
cout << “ Quiz 4 : 85\n”;
cout << “ Quiz 5 : 90\n”;
cout << “This is my first program using the standard output stream
operator\n";
return 0;
}
information

Sample Output
Resume

Name : Mary Ann Berndette Taduyo


Address: Malabon City
Birth Place: Navotas
Birthdate: August 14, 1971
Contact No. : 09173276497
Religion: Roman Catholic
Master’s Degree: Master of Art in Education major in
Mathematics
Bachelor’s Degree: Bachelor Of Science in Computer Science
Variables
Is a location in the computer’s memory
where a value can be stored for use by
a program.

It must be declared with a name and a


data type before they can be used in a
program.

Example:
integer1, sum, interger2, etc.
Identifier Names
It is a series of characters consisting of
letters, digits, and underscore (_).
It cannot start with a digit C++ identifiers can
be any length, however, some systems
an/or C++ implementations may impose
some restrictions on the length of identifiers.
Use 31 character or fewer to ensure
portability.
Do not begin with underscore and double
underscores.
Identifier Names
The following are the keywords that they
must not used as identifier:

- asm, auto, bool, break, case, catch, char, class,


const, const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, 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

-and, and_eq, bitand, bitor, compl, not, not_eq, or,


or_eq, xor, xor_eq
Identifier Names
Very important:
The C++ language is "case sensitive",
that means that an identifier written in capital
letters is not equivalent to another one with
the same name but written in small letters.
for example:
the variable RESULT is not the same as
the variable result nor the variable
Result.
Basic Data Types
int
specifying integer values
( whole numbers)

Example: 5, -10, 15, etc.


double
specifying real numbers (decimal point
values), the range are 15 digit

Example: 5.10, 10.50, -15.356, 0.254, etc.


Basic Data Types
float
floating point number, it has a decimal
point, the range are (7 digits)
Example: 6.20, 12.50, -21.489, 0.583, etc.

char
specifying character data, it may hold only
single uppercase letter, a single digit, or a
single special character
Example: a, B, c, name, Course, 7, *, $, etc.
Variables
In order use a variable in C++, we must
first declare it specifying which of the data
types we want it to be. The syntax to
declare a new variable is to write the data
type specifier that we want followed by a
valid variable identifier.
For example:
int a; float mynumber;
Data Data
type Identifier Identifier
type
Sample – operating
with variable
#include / process: a = 5; b
<iostream.h> = 2; = a + 1;
int main () result = a - b;
{
/ declaring
variables: int a,
b;
int result;
// print out the
result:

cout << result;


/ terminate the
program:
return 0;
}
a

Cont.
#include <iostream.h>
int main ()
{
int a, b;
int result;
/ process: a = 5; b = 2; a = a
+ 1; result = a - b;
cout << result;
return 0;
}
Program 1 – Input
the information
Sample Output

Jose Rizal University

Name :

Course :

Subject :
This is my first program using the standard insertion
stream operator
Program 2– Input the
information
Sample Output
Jose Rizal University

Name of Student :
Subject :

Quiz 1 :
Quiz 2 :
Quiz 3 :
Quiz 4 :
Quiz 5 :
information

Sample Output
Resume

Name :
Address:
Birth Place:
Birthdate:
Contact No. :
Religion:
Master’s Degree:
Bachelor’s Degree:
Program 4 – input/output

Enter your name:

Enter your ID:

Hello ______or should I say ____


Program 4 – input/output
#include <iostream>
#include <string> cout << "Enter
using namespace std; your ID number";
cin >> ID;
int main()
{ cout << "Hello " <<
string name; name << " or
int ID; should I say "
< ID << endl;
cout << "Enter your
name "; return 0;
cin >> name; }
output
/ i/o example
#include <iostream.h>
int 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"; return 0;
}
output

Result:

Please enter an integer value: 702


The value you entered is 702 and its
double is 1404.
Program 6 – output the
information

Given the three numbers A, B,


C. Create a C++ program to
compute and print out the
sum, the average, and the
product of these values.
Program 7 –
input/output

Create a program that will input 5


quizzes, then compute the sum and the
average.Then print the sum and
average of 5 quizzes.
Variables
When declaring a local variable, its value is
undetermined by default. But you may want a
variable to store a concrete value the
moment that it is declared. In order to do that,
you have to append an equal sign followed
by the value wanted to the variable
declaration:
type identifier = initial_value ;
For example, if we want to declare an int
variable called a that contains the value 0 at the
moment in which it is declared, we could write: Cont.
int a = 0;
Additionally to this way of initializing
variables (known as c-like), C++ has added a
new way to initialize a variable: by enclosing
the initial value between parenthesis ():
type identifier (initial_value) ;

For example:
int a (0);
Both ways are valid and equivalent in
C++.
Scope of Variables
Scope of Variables
Global variables can be referred to
anywhere in the code, within any function,
whenever it is after its declaration.
Local variables is limited to the code
level in which they are declared. If they are
declared at the beginning of a function (like
in main) their scope is the whole main
function. In the example above, this means
that if another function existed in addition to
main(), the local variables declared in main
could not be used in the other function and
vice versa.
Cont.
In C++, the scope of a local variable is given
by the block in which it is declared (a block is
a group of instructions grouped together within
curly brackets {} signs). If it is declared within
a function it will be a variable with function
scope, if it is declared in a loop its scope will
be only the loop, etc...
In addition to local and global scopes there
exists external scope, that causes a variable
to be visible not only in the same source file
but in all other files that will be linked together
Constants : literals

Constant
any expression that has a fixed value.
They can be divided in Integer
Numbers, Floating-Point Numbers,
Characters and Strings.
Integer Numbers
1776,707,-273
Constants : literals
Floating Point Numbers
They express numbers with decimals
and/or exponents. They can include a decimal
point, an e character (that expresses "by ten at
the Xth height", where X is the following
integer value) or both.
3.1415 // 3.14159
9
6.02e2 // 6.02 x
3 1023
1.6e-19 // 1.6 x
10-19
3.0 // 3.0
Cont.
these are four valid numbers with
decimals expressed in C++. The first number
is PI, the second one is the number of
Avogadro, the third is the electric charge of
an electron (an extremely small number) -all
of them approximated- and the last one is the
number 3 expressed as a floating point
numeric literal.
Constants : literals
Characters and strings
There also exist non-numerical constants,
like:
'z‘, 'p‘, "Hello world“,
"How do you do?"
The first two expressions represent single
characters, and the following two represent
strings of several characters. Notice that
represent a single character we enclose it
between single quotes (') and to express a
string of more than one character we enclose
them between double quotes ("). Cont.
When writing both single characters and
strings of characters in a constant way, it is
necessary to put the quotation marks to
distinguish them from possible variable
identifiers or reserved words. Notice this:
x
'x'
x refers to variable x, whereas 'x' refers
to the character constant 'x'.
Constants : literals
Character constants and
string constants
have certain peculiarities, like the escape
codes. These are special characters that
cannot be expressed otherwise in the source
code of a program, like newline (\n) or tab
(\t). All of them are preceded by an inverted
slash (\). Here you have a list of such escape
codes:
newline \n
carriage return \r
tabulation \t
Cont.
Constants : literals
vertical tabulation \v
backspace page \b
feed alert (beep) \f
single quotes (') \a
double quotes (") \’
question (?) \”
inverted slash (\) \?
\\

For example:
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"
Operators
Once we know of the existence of variables
and constants we can begin to operate with
them.
Assignation (=).
The assignation operator serves to assign
a value to a variable.
a = 5;
assigns the integer value 5 to variable a.
The part at the left of the = operator is known
as lvalue (left value) and the right one as
rvalue (right value). lvalue must always be a
variable whereas the rvalue can be either a

constant, a variable, the result of an


operation or any combination of them. Cont.
Operators
It is necessary to emphasize that the
assignation operation always takes place
from right to left and never at the inverse.
a = b;
assigns to variable a (lvalue) the value
that contains variable b (rvalue)
independently of the value that was stored in
a at that moment. Consider also that we are
only assigning the value of b to a and that a
later change of b would not affect the new
value of a. Cont.
For example, if we take this code (with the
evolution of the variables' content in green color):
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
will give us the result that the value
contained in a is 4 and the one contained in b
is 7. The final modification of b has not
affected a, although before we have declared a
= b; (right-to-left rule).
Cont.
Operators
A property that C++ has over other
programming languages is that the assignation
operation can be used as the rvalue (or part of
an rvalue ) for another assignation. For
example:
a = 2 + (b = 5);
is equivalent to:
b = 5;
a = 2 + b;

Cont.
that means: first assign 5 to variable b
and then assign to a the value 2 plus the
result of the previous assignation of b (that is
5), leaving a with a final value of 7. Thus, the
following expression is also valid in C++:
a = b = c = 5;
assigns 5 to the three variables a, b and
c.
Operators
Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations
supported by the language are:
+ addition
- subtraction
* multiplication
/ division
% module
Operations of addition, subtraction,
multiplication and division should not
suppose an understanding challenge for you
since they literally correspond with their
respective mathematical operators. Cont.
Operators
The only one that may not be known is
the module, specified with the percentage
sign (%).
Module is the operation that gives the
remainder of a division of two integer values.
For example, if we write a = 11 % 3;, the
variable a will contain 2 as the result since 2
is the remainder from dividing 11 between 3.

Cont.
Operators
Compound assignation operators ( +=,
-=, *=, /=, %=, >>=, <<=, &=, ^=, |= )
A feature of assignation in C++ that
contributes to its fame of sparing language
when writing are the compound assignation
operators (+=, -=, *= and /= among others),
which allow to modify the value of a variable
with one of the basic operators:
value += increase; is equivalent
to value = value + increase;
Cont.
Operators
a -= 5; is equivalent to a = a - 5;

a /= b; is equivalent to a = a / b;

price *= units + 1; is equivalent to


price = price * (units + 1);

and the same for all other operations.

Cont.
Operators
Increase and decrease.
Another example of saving language
when writing code are the increase
operator (++) and the decrease operator
(--). They increase or reduce by 1 the value
stored in a variable. They are equivalent to
+=1 and to -=1, respectively. Thus:
a++;
a+=1;
a=a+1;
are all equivalent in its functionality: the
three increase by 1 the value of a.
Cont.
Operators
Example 1 Example 2

B=3; B=3;
A=++B; A=B++
// A is 4, B is 4 //A is 3, B is
4
Operators
Relational operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between
two expressions we can use the Relational
operators. As specified by the ANSI-C++
standard, the result of a relational operation is
a bool value that can only be true or
false, according to the result of the
comparison.

Cont.
Operators
We may want to compare two expressions, for
example, to know if they are equal or if one is
greater than the other. Here is a list of the relational
operators that can be performed in C++:
== Equal Examples:
(7 == 5)would return
!= Different
> Greater than false.
(5 > 4)
would return true.
< Less than
(3 != 2)would return true.
>= Greater or equal than
<= Less or equal than (6 >= 6)would return true.
(5 < 5) would return
false.
Operators
Instead of using only numberic constants,
we can use any valid expression, including
variables. Suppose that a=2, b=3 and c=6,

(a == 5)would return false.


(a*b >= c)would return true since (2*3 >= 6) is it.
(b+4 > a*c)would return false since (3+4 > 2*6)
is it.
((b=2) == a)would return true.
Cont.
Operators

Be aware. Operator = (one equal sign) is not


the same as operator == (two equal signs), the first
is an assignation operator (assigns the right side of
the expression to the variable in the left) and the
other (==) is a relational operator of equality that
compares whether both expressions in the two
sides of the operator are equal to each other. Thus,
in the last expression ((b=2) == a), we first
assigned the value 2 to b and then we compared it
to a, that also stores value 2, so the result of the
operation is true.
Operators
Logic operators ( !, &&, || ).
Operator ! is equivalent to boolean
operation NOT, it has only one operand,
located at its right, and the only thing that it
does is to invert the value of it, producing
false if its operand is true and true
if its operand is false. It is like saying that
it returns the opposite result of evaluating
its operand.

Cont.
Operators
For example:

!(5 == 5) returns false because the


expression at its right
!(6 <= 4) (5 == 5) would be true.
returns true because (6 <=
!true 4) would be false.
returns false.
!false returns true.

Cont.
Operators

Logic operators && and || are used when


evaluating two expressions to obtain a single
result. They correspond with boolean logic
operations AND and OR respectively. The
result of them depends on the relation
between its two operands:

Cont.
Operators
First Second result result
Operand Operand a && B a || b
a b
true true true true
true false false true
false true false true
false false false false
For example:
( (5 == 5) && (3 > 6) ) returns false ( true && false ).
( (5 == 5) || (3 > 6)) returns true ( true || false ).
Operators
Conditional operator ( ? ).
The conditional operator evaluates an
expression and returns a different value
according to the evaluated expression,
depending on whether it is true or false. Its
format is:
condition ? result1 : result2

if condition is true the expression will return


result1, if not it will return result2.
Cont.
Operators
Example:

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 a, since 5 is greater than 3.

a>b ? a : b returns the greater one, a or b.


Precedence of
Operators
When making complex expressions with
several operands, we may have some doubts
about which operand is evaluated first and
which later. For example, in this expression:
a=5+7%2
we may doubt if it really means:
a = 5 + (7 % 2) with result 6,
or a = (5 + 7) % 2 with result 0

Cont.
Precedence of
Operators
The correct answer is the first of the
two expressions, with a result of 6. There
is an established order with the priority of
each operator, and not only the arithmetic
ones (those whose preference we may
already know from mathematics) but for all
the operators which can appear in C++.
From greatest to lowest priority, the priority
order is as follows:
Cont.
Precedence of
Operators
Priority Operator Description Associativity
1 :: scope Left
2 ()[]->.
sizeof Left
3 ++ -- increment/decrement Right
~ Complement to one (bitwise)
! unary NOT
&* Reference and Dereference
(pointers)
(type) Type casting
+- Unary less sign
Cont.
Precedence of
Operators
Priority Operator Description Associativity
4 * / % arithmetical operations
Left
5 + - arithmetical operations Left
6 << >> bit shifting (bitwise)
Left
7 < <= > >= Relational operators Left
8 == != Relational operators
Left
9 & ^ | Bitwise operators
Left
10 && || Logic operators Cont.
Left
Precedence of
Operators
Priority Operator Description Associativity
11 ?: Conditional Right
12 =+=-=*=
/= %= >>=
<<= &= ^= |= Assignation Right
13 , Comma, Separator Left
Example: (7 % 2); or
a = 5 +
a = (5 + 7) % 2;
according to the operation that we wanted to
perform. So if you want to write a complicated
expression and you are not sure of the
precedence
Functions
console
it is the basic interface of computers,
normally it is the set composed of the
keyboard and the screen. The keyboard is
generally the standard input device and the
screen the standard output device.
In the iostream C++ library, standard input
and output operations for a program are
supported by two data streams: cin for
input and cout for output.
Cont.
Functions
cout (the standard output stream )
it is normally directed to the screen.
it is used to output information to the
screen.
cin (the standard input stream)
it is normally assigned to the keyboard.
it is used to input information from the
keyboard.
cout
The cout stream is used in conjunction with
the overloaded operator << (a pair of "less
than" signs).
cout << "Output sentence"; // prints
Output
sentence on
screen
cout << 120; // prints number 120 on
screen
cout << x; // prints the content of
variable x on screen
Cont.
cout
The << operator is known as insertion
operator since it inserts the data that follows
it into the stream that precedes it. In the
examples above it inserted the constant string
Output sentence, the numerical constant 120
and the variable x into the output stream cout.
Notice that the first of the two sentences is
enclosed between double quotes (") because
it is a 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
variables. Cont.
cout
For example, these two sentences are very
different:
cout << "Hello"; // prints Hello on screen
cout << Hello; // prints the content of
Hello variable on
screen
The insertion operator (<<) may be used
more than once in a same sentence:
cout << "Hello, " << "I am " << "a C+
+ sentence";
this last sentence would print the message
Hello, I am a C++ sentence on the screen.
Cont.
cout

cout << "Hello, I am " << age << "


years old and my zipcode is " << zipcode;
If we supose that variable age contains
the number 24 and the variable zipcode
contains 90064 the output of the previous
sentence would be:
Hello, I am 24 years old and my zipcode
is 90064

Cont.
cin
Handling the standard input in C++ is
done by applying the overloaded operator of
extraction (>>) on the cin stream. This must
be followed by the variable that will store the
data that is going to be read.
For example:
int age;
cin >> age;
declares the variable age as an int and then
waits for an input from cin (keyborad) in
order to store it in this integer variable.
Cont.
cin

Always consider the type of the variable


that are using as a container with cin
extraction. If the variable is an integer then
get an integer, if variable is a character than
get a character.
Control Structure
A program is usually not limited to a linear
sequence of instructions. During its process
it may bifurcate, repeat code or take
decisions. For that purpose, C++ provides
control structures that serve to specify what
has to be done to perform our program.
With the introduction of control sequences
we are going to have to introduce a new
concept: the block of instructions.

Cont.
Control Structure

Block of instructions
is a group of instructions separated
by semicolons (;) but grouped in a block
delimited by curly bracket signs: { and }.

Cont.
Control Structure
Most of the control structures that we will
see in this section allow a generic
statement as a parameter, this refers to
either a single instruction or a block of
instructions, as we want. If we want the
statement to be a single instruction we do
not need to enclose it between curly-
brackets ({} ). If we want the statement to be
more than a single instruction we must
enclose them between curly brackets ({})
forming a block of instructions.
if
It is used to execute an instruction or block
of instructions only if a condition is fulfilled. Its
format is:
if (condition)
statement ;
where condition is the expression that is
being evaluated. If this condition is true,
statement is executed. If it is false,
statement is ignored (not executed) and the
program continues on the next instruction
after the conditional structure.
Cont.
if
For example,
the following code fragment prints out x
is 100 only if the value stored in variable x
is indeed 100:
if (x == 100)
cout << "x is 100";

Cont.
if
If we want more than a single instruction
to be executed in case that condition is
true we can specify a block of
instructions using curly brackets { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
Program 1: if
#include <iostream>

int main()
{

int number = 5;
int guess;

cout << "I am thinking of a number between


1 and 10" << endl;
cout << "Enter your guess, please " << endl;
cin >> guess;
Cont.
Program 1: if

if (guess == number)
{
cout << "Incredible, you are correct" <<
endl;
}

return 0;
}
Program 1: if and else

Result:
I am thinking of a number between 1 and 10

Enter your guess,


please 5

Incredible, you are correct


Program 2 : if
/ Using if statements, relational
/ operators, and equality
operators #include <iostream>

int main()
{
int num1, num2;

cout << "Enter two integers, and I will tell


you\n" << "the relationships they satisfy: ";
cin >> num1 >> num2; // read two integers
Cont.
Program 2 : if
if ( num1 == num2 )
cout << num1 << " is equal to " << num2 <<
endl;

if ( num1 != num2 )
cout << num1 << " is not equal to " << num2 <<
endl;

if ( num1 < num2 )


cout << num1 << " is less than " << num2 <<
endl;

Cont.
Program 2 : if
if ( num1 > num2 )
cout << num1 << " is greater than " << num2 <<
endl;

if ( num1 <= num2 )


cout << num1 << " is less than or equal to
" << num2 << endl;

if ( num1 >= num2 )


cout << num1 << " is greater than or equal to
" << num2 << endl;
Cont.
Program 2 : if

return 0; // indicate that program ended


successfully
}
Program 3 : if

Make a C++ Program that will input


the age of a person. If the person’s
age is less than 18, print MINOR.
Otherwise, print ADULT.
Conditional Structure :
if and else
We can additionally specify what we
want that happens if the condition is not
fulfilled by using the keyword else. Its form
used in conjunction with if is:
if (condition)
statement1
else
statement2

Cont.
Conditional Structure :
if and else
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

prints out on the screen x is 100 if


indeed x is worth 100, but if it is not -and
only if not- it prints out x is not 100.
Conditional Structure : if
and else if
The if + else structures can be
concatenated with the intention of verifying a
range of values. The following example shows
its use telling if the present value stored in x is
positive, negative or none of the previous, that
is to say, equal to zero.
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0"; Cont.
Conditional Structure :
if and else if

Remember that in case we want more


than a single instruction to be executed, we
must group them in a block of
instructions by using curly brackets { }.
Program 1: if and else
#include <iostream>
int main()
{
int choice;

cout << "What flavor ice cream do


want?" <<
endl;
cout << "Enter 1 for chocolate" << endl;
cout << "Enter 2 for vanilla" << endl;
cout << "Enter 3 for strawberry" << endl;
Cont.
Program 1: if and else
cout << "Enter 4 for green tea flavor, yuck"
<< endl;
cout << "Enter you choice: ";

cin >> choice;

if (choice == 1) {
cout << "Chocolate, good
choice" << endl;
}
Cont.
Program 1: if and else

else if (choice == 2) {
cout << "Vanillarific" << endl;
}
else if (choice == 3) {
cout << "Berry Good" << endl;
}
else if (choice == 4) {
cout << "Big Mistake" << endl;
}
Cont.
Program 1: if and else

else {
cout << "We don't have any" << endl;
cout << "Make another selection" <<
endl;
}

return 0;
}
Program 2: if and else
Given two numbers X and Y.
Create a program to determine the
difference between X and Y. If X -Y is
negative, compute R=X+Y, if X-Y is
zero, compute R=2X+XY; and if X-Y is
positive, compute R=X*Y. Print out the
values of X, Y, and R.
Program 3: if and else

Create a program that would


input five values of numbers and
compute for the average. If the
average is below 75, the remarks is
failed, if not remark is passed. Print
the average, remarks.
Repetitive Structures -
while loop
Loops
have as objective to repeat a statement a
certain number of times or while a condition is
fulfilled.
The while loop.
its format is:

while (expression)
statement;

Cont.
Repetitive Structures -
while loop

and its function is simply to repeat


statement while expression is true.

For example,
we are going to make a program to
count down using a while loop:
Program 1 - while loop
// custom countdown using
while #include
<iostream.h> int main ()
{
int n;
cout << "Enter the starting number >
";
cin >> n;
while (n>0)
{
cout << n << ", "; --n;
}
cout << "FIRE!";
return 0;
}
Program 1 - while loop

Result:

Enter the starting number > 8

8, 7, 6, 5, 4, 3, 2, 1, FIRE!
Program 2 - while loop

This program determines the minimum


number of bits needed to store a positive
integer. The largest unsigned number that can
be stored in N bits is (2N - 1).
Program 2 – while loop
#include <iostream>
int main()
{
int bitsRequired = 1; //the power of 2
int largest = 1; //largest number that
can be stored
int powerOf2 = 2;
int number;

cout << "Enter a positive integer: ";


cin >> number;

Cont.
Program 2 – while loop

while (number > largest)


{
bitsRequired += 1; //Shorthand for
bitsRequired =
bitsRequired + 1

powerOf2 = powerOf2 *
2; largest = powerOf2 - 1;

Cont.
Program 2 – while loop

cout << "To store " << number << " requires ";
cout << bitsRequired << " bits" << endl;

return 0;
}
Program 3 – while loop

Make a C++ program that will read


and print the names and individual scores
of 100 students for a particular
examination. Also, determine their average
and score, and print it out.
Program 4 – while loop

The initial value of the radius of a


circle is equal to one unit and each
succeeding radius is one unit greater
than the value before it. Create a C++
program to compute the area of the
circle starting with R=1.0 up to R=5.0,
then print out each radius and the
corresponding area of the circle.
Repetitive Structures – do
while loop

The do-while loop.


Format:
do
statement;
while (condition);

Cont.
Repetitive Structures – do
while loop
Its functionality is exactly the same as the
while loop except that condition in the do-
while is evaluated after the execution of
statement instead of before, granting at least
one execution of statement even if condition is
never fulfilled.

For example, the following program


echoes any number you enter until you enter
0.
Cont.
Program 1 – do while loop
/ number echoer
#include <iostream.h>
int main ()
{
unsigned long n;
do
{
cout << "Enter number (0 to end): ";
cin >> n; cout << "You entered: “
<< n << "\n";
}
while (n != 0);
return 0;
}
Cont.
Program 1 – do while loop

Result:

Enter number (0 to end): 12345


You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0
loop
The for loop.
Its format is:
for (initialization; condition;
increase) statement;

its main function is to repeat statement


while condition remains true, like the while
loop. But in addition, for provides places to
specify an initialization instruction and an
increase instruction. So this loop is specially
designed to perform a repetitive action with a
counter. Cont.
loop
It works the following way:
1, initialization is executed. Generally it is an
initial value setting for a counter variable. This
is executed only once.

2, condition is checked, if it is true the loop


continues, otherwise the loop finishes and
statement is skipped.

3, statement is executed. As usual, it can be


either a single instruction or a block of
instructions enclosed within curly brackets { }.
Program 1 – for loop
// countdown using a for loop

#include <iostream.h>
int main ()

{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
Cont.
Program 1 – for loop

Result:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
loop
The comma operator (,) is an instruction
separator, it serves to separate more than one
instruction where only one instruction is
generally expected.
For example, suppose that we wanted
to initialize more than one variable in our loop:

for ( n=0, i=100 ; n!=i ; n++, i-- )


{
// whatever here...
}
Cont.
loop
This loop will execute 50 times if neither
n nor i are modified within the loop:
n starts with 0 and i with 100, the
condition is (n!=i) (that n be not equal to i).
Beacuse 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.
else

The syntax of the switch instruction


is a bit peculiar. Its objective is to check
several possible constant values for an
expression, something similar to what we
did at the beginning of this section with
the linking of several if and else if
sentences.

Cont.
else
Its form is the following:
switch (expression)
{
case constant1:
block of instructions 1
break;
case constant2:
block of instructions 2
break;
.
.
.
default:
default block of instructions
}
cout << "x is
2";
switch break;
example
switch (x) {
case 1:
cout << "x
is
1";
break;

case 2:
else

cout <<
"value of
x
unknown
";

}
else
if-else equivalent }

if (x == 1) {
cout << "x is 1";
}

else if (x == 2)
{ cout << "x
is 2";
else {
cout <<
"value of x
unknown";
}

You might also like