Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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
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 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.
Process Connector
Flow Lines
Decision
Flow Direction
Preparation Indicators
Flowcharting Symbols
Input/Output
Parallelogram
Process Rectangle
Decision Diamond
Arrowheads
Horizontal/
Vertical Lines
language.
Disadvantage of Flowcharts
1. Flowcharts do not represent a programming
Get Get
Number 1 Inputs Number 1
Get Get
Number 2 Number 2
Result = Result =
Number 1 + Number 2
Process Number 1 - Number 2
End End
Sample Problem
Example 1 - Algorithms
A End
Example 2
Ave = Sum/3
Read
A,B,C
Prod = A*B*C
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
End
Example 4
B
End
Example 5
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
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
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
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
B
C
Loop and Accumulator
•Accumulator
The variable used is thereby
continuously accumulating the
numerical quantities
Example 1
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
A End B
Example 2
A=1 Print
A
F A=A+1
B If A <
End
=10?
T
B
A
Example 3
X=1 A=A+1
Sum = 0
If A < F
Print
Sum = Sum + B
=5? Sum
(A*A)
T
End
A B
Example 4
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
-
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
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
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:
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:
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
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
Result:
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
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;
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,
Cont.
Operators
For example:
Cont.
Operators
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
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
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
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;
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
int main()
{
int num1, num2;
if ( num1 != num2 )
cout << num1 << " is not equal to " << num2 <<
endl;
Cont.
Program 2 : if
if ( num1 > num2 )
cout << num1 << " is greater than " << num2 <<
endl;
Cont.
Conditional Structure :
if and else
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
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
while (expression)
statement;
Cont.
Repetitive Structures -
while loop
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:
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
Program 2 - while loop
Cont.
Program 2 – while loop
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
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.
Result:
#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:
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";
}