Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Reviewer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

MODULE 1

COMPUTER FUNDAMENTALS: INTRODUCTION TO COMPUTER


COMPUTERS
 an electronic machine that follows a set of instruction in order that it may be able to accept and gather
data and transform this into information.
INFORMATION PROCESSING SYSTEM
 DATA is a collection of independent and unorganized facts.
 INFORMATION is the processed and organized data presented in a meaningful form.
 DATA PROCESSING is the course of doing things in a sequence of steps.
ADVANTAGES
 Speed
 Multitasking
 Cost
 Accuracy
 Consistency
 Versatility
 Data security
DISADVANTAGES
 Health risks
 Virus and hacking attacks
 Online cyber crimes
 Potential of loss of privacy
 Public safety
 Increases waste and impacts the environment
 Reduction in employment opportunity
FUNCTIONS OF AN INFORMATION PROCESSING SYSTEM
 It accepts and gather data. (INPUT)
 It processes data to become information. (PROCESSING)
 It stores data and information. (STORE)
 It presents information. (OUTPUT)
THREE MAJOR COMPONENTS OF AN INFORMATION PROCESSING SYSTEM
 HARDWARE is the tangible part of a computer system.
 SOFTWARE is the non-tangible part that tells the computer how to do its job.
 PEOPLEWARE refer to people who use and operate the computer system, write computer
programs, and analyze and design the information system.
BASIC UNITS OF MEASUREMENT
 BIT is a unit of information equivalent to the result of a choice between only 2 possible alternatives
in the binary number system.
 BYTE is a sequence of 8 bits (enough to represent one character of alphanumeric data) processed
as a single unit for information.
BASIC PC HARDWARE
 HARDWARE is the tangible part of a computer system.
BASIC HARDWARE OF A PC SYSTEM
 Central Processing Unit (CPU)
 Memory Unit
 Arithmetic Logic Unit
 Input Devices
 Output Devices
 Secondary Storage Devices

1. CENTRAL PROCESSING UNIT


 Brain of the computer.
 It directs and controls the entire computer system and performs all arithmetic and logical
operations.
2. MEMORY UNIT
 Where the programs and data are stored.
a. READ ONLY MEMORY (ROM) contains the pre-programmed computer instructions such as the
Basic Input Output System (BIOS).
b. RANDOM ACCESS MEMORY (RAM) is used to store the programs and data that you will run.
Exists only when there is power.
3. ARITHMETIC LOGIC UNIT
 An arithmetic logic unit (ALU) is a combinational digital electronic circuit that performs arithmetic
and bitwise operations on integer binary numbers.
INPUT DEVICES
 Allows data and programs to be sent to the CPU.
– Keyboard
– Mouse
– Joystick
– Microphone
– Webcam
– Scanner
– Monitor
KEYBOARD
 Traditional keyboards
 Flexible keyboards
 Ergonomic keyboards
 Wireless keyboards
 PDA keyboards
MOUSE
TWO TYPES OF MOUSE
 Mechanical - a type of computer mouse that has a rubber or metal ball on its underside and it
can roll in every direction.
 Optical: This type uses a laser for detecting the mouse's movement.
HOW A MOUSE HOOKS UP TO A PC
 PS/2 Mouse
 Serial Mouse
 USB/Cordless Mouse
OTHER POINTING DEVICES
 Trackball
 Track point
 Touch pad
 Touch Screen
 Joystick – input device for computer games
 Light Pens – light-sensitive penlike device
 Stylus – penlike device commonly used with tablet PCs and PDAs.
SCANNING DEVICES
 Optical scanners
 Card readers
 Bar code readers
 Character and mark recognition devices
IMAGE CAPTURING DEVICES
 Digital Cameras
 Digital Video Cameras
OUTPUT DEVICES
 Media used by the computer in displaying its responses to our requests and instructions.
 Monitor
 Audio Speakers
 Printer
TYPES OF MONITOR
 Cathode Ray Tube (CRT)
 Liquid Crystal Display (LCD)
PRINTERS
 IMPACT PRINTERS uses pressure by physically striking the paper. Ex. Daisy wheel printers, line
printers, dot matrix printers & band printers.
 NON-IMPACT PRINTER does not apply pressure on the paper but instead produces character by
using lasers, ink spray, photography or heat.
SECONDARY STORAGE DEVICES
 Attached to the computer system to allow you to store programs and data permanently for the
purpose of retrieving them for future use.
 Floppy disk, Hard disk, CD Rom
FLOPPY DISK
 The most common secondary storage device
 3.5” disk – 1.44MB
HIGH-CAPACITY FLOPPY DISKS
 Floppy disk cartridges
 3 ½ inches in diameter
 Stores more information
 Zip disks
HARD DISK DRIVE OR HARD DISK
 Made of rigid materials unlike floppy disks
 Holds a greater amount of data
OPTICAL DISCS
 A standard part of modern desktop machines, especially used for multimedia purposes and
preferred in loading applications.
KINDS
• Blue Ray Disk – 40G
• Digital Versatile Disk
– DVD-R – write once, 3.95G
– DVD RW – rewritable, 3G
– Single Layer and Double Layer
• Compact Disk
– CD-R – write once, 650MB
– CD-RW – rewritable, 700MB
OPTICAL DRIVES
 CD-ROM read CDs
 CD-Writer read/write CDs
 DVD-Combo read/write CDs, read DVD
 DVD Writer read/write CDs, read/write DVDs
OTHER SECONDARY STORAGE
Solid-State Storage
• No moving parts
• Flash memory cards
• USB flash drives
PARTS THAT BUILD UP A SYSTEM UNIT
 Casing or cover
 Power Supply
 Motherboard
 Microprocessor
 Memory
 Video Card
 Sound card
 Floppy disk drive
 Hard disk drive
 CD-ROM drive
 MODEM
CASING OR COVER
• The box or outer shell that houses most of the computer, it is usually one of the most overlooked
parts of the PC.
• Protects the computer circuits, cooling and system organization.
POWER SUPPLY
• Responsible for powering every device in your computer.
• Parts of a Power supply:
– Disk drive connectors
– Motherboard connector
– Power supply fan
– Power switch
– Input voltage selector
– Cover
– Power plugs receptacle
MOTHERBOARD
• The physical arrangement in a computer that contains the computer’s basic circuitry and components.
• Components are:
– Microprocessor
– (Optional) Coprocessors
– Memory
– Basic Input/Output System (BIOS)
– Expansion Slot
– Interconnecting circuitry
EXPANSION SLOTS
• Graphic cards
• Sound cards
• Modem cards
• Network interface cards/network adapter
SOFTWARE
• Instructions that tell the computer how to process data into the form you want.
• Software and programs are interchangeable.
• Two major types:
– System and Applications
2 KINDS OF SOFTWARE
1. SYSTEM SOFTWARE - enables the application software to interact with the computer hardware.
Operating Systems are programs that coordinate computer resources, provide an interface between users
and the computer; and run applications.
Utilities perform specific tasks related to managing computer resources.
Device drivers are specialized programs designed to allow particular input or output devices to
communicate with the rest of the computer system.
FUNCTIONS OF A SYSTEM SOFTWARE
 Managing resources (memory, processing, storage, and devices like printer).
 Providing user interface
 Running applications
2. APPLICATIONS SOFTWARE - provides the real functionality of a computer. It helps you use your
computer to do specific types of work.
 Basic Applications, widely used in all career areas.
 Specialized Applications, more narrowly focused on specific disciplines and occupations.
DISK OPERATING SYSTEM
 DOS was the first widely installed operating system for personal computers.
 Command-driven
 MS-DOS Commands
– A COMMAND is the name of a special program that makes your computer carry out a task.
GRAPHICAL USER INTERFACE (GUI)
 Thru GUI, users can interact directly with the operating system.
 Microsoft Windows
 Icons, Menus, Dialog boxes
FILES
 FILE is simply a collection of information that you store on a disk or diskette.
 Must have a unique name
 Two parts: the filename and extension separated by a period.
 RECIPE.DOC
EXTENSIONS
 Use extension to make your filenames more descriptive.
– .DOC – word documents
– .XLS – excel documents
– .PPT – PowerPoint documents
MODULE 1
COMPUTER FUNDAMENTALS: PROGRAMMING CONCEPTS OVERVIEW

COMPUTER PROGRAMMING
• Computer programming is the process of writing instructions that get executed by computers.
• The instructions, also known as code, are written in a programming language which the computer
can understand and use to perform a task or solve a problem.
ADA LOVELACE
• Ada Lovelace has been called the world's first computer programmer.
• What she did was write the world's first machine algorithm for an early computing machine that existed
only on paper.
PROGRAMMING LANGUAGE (1)
• A programming language is a vocabulary and set of grammatical rules for instructing a computer or
computing device to perform specific tasks.
• The term programming language usually refers to high-level languages, such as BASIC, C, C++,
COBOL, Java, FORTRAN, Ada, and Pascal.
PROGRAMMING LANGUAGE (2)
• It is a computer language engineered to create a standard form of commands.
• These commands can be interpreted into a code understood by a machine.
• Programs are created through programming languages to control the behavior and output of a machine
through accurate algorithms, similar to the human communication process.
• A programming language is also known as a programming system, computer language or computer
system.
LEVELS OF PROGRAMMING LANGUAGE
MIDDLE LEVEL LANGUAGE
• Is designed using some special words known as mnemonic and when we compared it to low level
language, machine level is easy to understand.
• This is the only language that is directly understood by the computer. It does not need any translator
program.
• This kind of languages is called assembly language.
LOW LEVEL LANGUAGES
• The low-level language (LLL) is designed using zeros (0) and ones (1), hence they are critical to
understand.
• Instructions given to the computer in 0’s and 1’s is known as binary language or machine language.
• Then programmers found writing code in binary language seems to be , then they used an English like
words to write a program in order to understand and become easy and simple to code.
HIGH LEVEL LANGUAGE
• These are designed using simple English like words.
• Because of this, they are very easy to understand.
• These are machine independent languages so they need to translator into machine level
language.
IN ORDER TO CONVERT HLL TO LLL WE HAVE 3 TYPES OF TRANSLATOR, WHICH ARE:
• Compiler: It converts the entire source code into object code (machine code) at once. Compilers are
used to convert HLL into Machine code format.
• Interpreter: It converts source code into object code in line-by-line format. It also used to convert HLL
into understandable machine code.
• Assembler: It is used to convert assembly level language (low level) into machine level language.
HISTORY OF PROGRAMMING LANGUAGE
C++ (C WITH CLASSES)
• Bjarne Stroustrup (B-yar-ne Strov-stroop)
• Born 30 December 1950
• A Danish computer scientist, most notable for the creation and development of the C++ programming
language.
• He is a visiting professor at Columbia University, and works at Morgan Stanley as a Managing Director
in New York
• He received a master's in mathematics from Aarhus University in 1975 and a PhD in computer science
from Cambridge University in 1979.
C++
• C++ is based on C and it retains much of that language, including a rich operator set.
• C++ is a highly portable language, and translators for it exist on many different machines and systems.
• C++ compilers are highly compatible with the existing C programs because maintaining such
compatibility was a design objective.
• Programming in C++ does not require a graphics environment, and C++ programs do not incur runtime
expense from type checking or garbage collection.
• C++ has improved on C in significant ways, especially in supporting strong typing.
• The class syntax was added to the language which was an extension of the struct construct in C.
• C++ is superior than C in supporting object-oriented programming. C++ may even replace C in
becoming a general purpose programming language.
DEV C++
SOURCE CODE / SOURCE FILE
• WRITE
• SAVE
• COMPILE
• RUN
C++ BASICS
• The main function ‘main( )’ signals the beginning of the program. Obviously, there cannot be more than
one main() function, otherwise the computer woudn’t know where to start.
• { }-The opening brace marks the beginning of the body of the function ‘main()’. The opposite brace is
serves as the end of the body.
• Semicolon or ; - Statement is a line of code in C and C++ terminated with a semicolon.
• cout <<- output or display, it serves as an outputting command. This function is found in the standard
library functions of C++ system.
• << endl – position the cursor to the next line instead of using \n.
FEATURES
• White Space
– You will frequently see references to something called white space.
– It is typically used to separate different words in a program.
– White space consists of one or more space, tab ( \t) and newline(\n).
– The judicious use of white space can make your programs much more readable.
LITERAL CONSTANTS
• Literal Constants
– Several characters have names that use a back slash notation which is useful when you want to
embed one of these characters within a literal character string.
– Some examples
Constants Name
\n New Line
\t Tab
\’ Single quotation mark
\” Double quotation mark
\0 Zero
DECLARATIONS
• It is a characteristic of many computer languages that variables must be declared before they can be
used.
• A variable declaration gives a name to the variable, and tells the computer what type of data this
variable can hold.

VARIABLE DECLARATION
• A declaration of a variable is where a program says that it needs a variable.
• For our small programs, place declaration statements between the two braces of the main method.
• The declaration gives a name and a data type for the variable.
DataType VariableName;
• It may also ask that a particular value be placed in the variable.
DataType VariableName = InitialValue;
DATA TYPE
A data type or simply type is an attribute of data which tells the compiler or interpreter how the programmer
intends to use the data.
1. NUMBER
• Integer – Whole Number
• Floating Point
o Float – numbers with up to 6 decimal places
o Double – numbers beyond to 6 decimal places
2. CHARACTER
• Character – Single letter or any character enclosed with a single quote
• String – combination of alphanumeric values enclosed with a double quote

3. BOOLEAN
• True or False
VARIABLE
• a variable is a storage location (identified by a memory address) paired with an associated symbolic
name (an identifier), which contains some known or unknown quantity of information referred to as a
value
• Examples:
X, XY, name, NUMBER, SAMPLE1, sample2, First_name
FirstName, Sample1, sample1, sAMPLE1
IDENTIFIER/ VARIABLE DECLARATION RULES
• A sequence of one or more letters, digits, or underscore characters (_).
• Spaces, punctuation marks, and symbols cannot be part of an identifier.
• Shall always begin with a letter.
• No case can they begin with a digit.
• Max 8 chars or depend on compiler and OS
• Always exist in the left hand side of assignment operator
• No keyword for a variable name
KEYWORDS - a word that is reserved by a program because the word has a special meaning.
LIST OF C++ KEYWORDS: alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch,
char, char16_t, char32_t, class, compl, const, constexpr, const_cast, continue, decltype, default, delete, do,
double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long,
mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected, public,
register, reinterpret_cast, return, short, signed, sizeof, static, static_assert, static_cast, struct, switch,
template, this, thread_local, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void,
volatile, wchar_t, while, xor, xor_eq
FEATURES
• COMMENTS
– // and /*....*/ comments in C++ could be used for representing remarks.
– End-of-line Comments //
– Everything on the program line to the right of the // characters is ignored and removed by the
preprocessors.
– One benefit of these comments is the ability to place them within a block style comment.
– Since block style comments cannot be nested, these comments offer the ability to nest
comments within comments.
COMMON PROGRAMMING PROBLEMS
 Same identifiers are used with different letter formats.
 C++ is case sensitive. It distinguishes between uppercase and lowercase characters.
 Identifiers are predefined keywords in C++.
 Programmers should be careful in defining identifiers. They should, as far as possible, be meaningful.
 Working with blocks
 C++ is a block structured language.
 Blocks are defined as: { }.
 Blocks are generally used when there are more than one instructions to be executed at a point
of condition checking.

MODULE 2
PROBLEM SOLVING: INTRODUTION TO ALGORITHMS, FLOWCHART AND PSEUDO CODE

SOFTWARE DEVELOPMENT
• Requirement analysis, leading to a specification of the problem
• Design of a solution
• Implementation of the solution
• Analysis of the solution
• Testing, debugging and integration
• Maintenance and evolution of the system.
SPECIFICATION OF A PROBLEM
• A precise statement/description of the problem.
• It involves describing the input, the expected output, and the relationship between the input and
output.
• This is often done through preconditions and post-conditions.
DESIGN (1)
• Formulation of a method, that is, of a sequence of steps, to solve the problem.
• The design “language” can be pseudo-code, flowcharts, natural language, any combinations of
those, etc.

DESIGN (2)
• A design so expressed is called an algorithm(s).
• A good design approach is a top-down design where the problem is decomposed into smaller,
simpler pieces, where each piece is designed into a module.
IMPLEMENTATION
• Development of actual source code that will carry out the design and solve the problem.
• The design and implementation of data structures, abstract data types, and classes, are often a
major part of design implementation.

ANALYSIS OF THE SOLUTION


• Estimation of how much time and memory an algorithm takes.
• The purpose is twofold:
to get a ballpark figure of the speed and memory requirements to see if they meet the target
to compare competing designs and thus choose the best before any further investment in the application
(implementation, testing, etc.)

TESTING AND DEBUGGING (1)


• Testing a program for syntactical correctness (no compiler errors)
• Testing a program for semantic correctness, that is, checking if the program gives the correct
output.

TESTING AND DEBUGGING (2)


• This is done by:
• having sample input data and corresponding, known output data;
• running the programs against the sample input;
• comparing the program output to the known output; and
• in case there is no match, modify the code to achieve a perfect match.

TESTING AND DEBUGGING (3)


• One important tip for thorough testing:
“Fully exercise the code, that is, make sure each line of your code is executed.”

INTEGRATION
• Gluing all the pieces (modules) together to create a cohesive whole system.

MAINTENANCE AND EVOLUTION OF A SYSTEM


• Ongoing, on-the-job modifications and updates of the programs.
WHAT IS AN ALGORITHM? (1)
• An organized sequence or list of clear steps or operations needed to solve a given programming
problem
• 3 Components:
• Input
• Process (Steps or Instructions)
• Output

• Any well-defined computational procedure that takes some value(s) as input and produces
some value(s) as output
• Sequence of computational steps that transform the input to output

EFFICIENT ALGORITHMS
• We choose between different algorithms based on their efficiency
• Usual measure of efficiency:
• Speed – how long an algorithm takes to produce its result
• Memory – how much resources an algorithm takes to produce its result

ALGORITHM FORMULATION (STEPS)


• Understand the problem

• Determine the given inputs, the desired output, and the steps to reach the output
• Design the algorithm
• Write the algorithm that will solve the problem given the inputs

• Analyse the algorithm

• Determine the resources that the algorithm requires – memory, bandwidth,


hardware, computational time
• Refine the algorithm
• Verification
• Test the algorithm to ensure it performs its intended task
ALGORITHM ANALYSIS
• Study the behaviour of the algorithm to determine its pattern and performance
• Measured in terms of execution time (speed) and amount of memory (space)
consumed
• Designing efficient algorithms
ALGORITHM
• PROBLEM
• GIVEN (INPUT)
• OUTCOME (OUTPUT)
• PROCEDURE
PSEUDO CODE
• is an informal high-level description of the operating principle of a computer program or
other algorithm.
( := or )
START
INITIALIZE (CONSTANT)
COMPUTE
READ or INPUT
WRITE or OUTPUT
END

SOURCE CODE
• is any collection of code, possibly with comments, written using a human-readable
programming language, usually as plain text.
• is specially designed to facilitate the work of computer programmers, who specify the
actions to be performed by a computer mostly by writing source code.
• is often transformed by an assembler or compiler into binary machine code understood
by the computer.

FLOWCHART AND
FLOWCHARTING SYMBOLS
FLOWCHART
• It is a modelling tools used to illustrate data, instructions, process, information and workflow by
the use of specialized symbols.
• Also known as a step by step graphical representation of a solution.

• INPUT/OUTPUT is the part of the program that the user sees.


• INPUT is the only way for the user to send data to the computer for processing it can be numeric value,
character, or string.
DESCRIPTIVE STATEMENT is use to ask the user what to do and what type of data to input.
OUTPUT – includes descriptive statement to communicate to the user.
- output instruction defines when and where to release the data in the program

FLOWCHARTING TECHNIQUES (1)


• A flowchart always start with the instruction START or BEGIN….the only guidelines to
remember in the terminal symbol is the consistency of terminologies. The organized way of
writing the instruction is to use the pairs START – STOP or BEGIN - END
• Initialization symbol is where you prepare the variables to be available for use. When you
initialize, you are also allocating memory space for your data storage. As a rule we always draw
this symbols to state the use of our memory
• Flowchart helps the programmer to define when to ask an input from the user and when to
release a value.
GET(), INPUT()
PRINT(), DISPLAY()
• The processing symbol is only limited to: (1) assignment of new value to the variables and (2)
mathematical computations.
• **Since we use the START in the opening of our flowchart, for consistency we should use STOP to
terminate.
FLOWCHARTING SYMBOLS
MODULE 2
PROBLEM SOLVING: COMPUTER EXPRESSIONS AND OPERATORS

EXPRESSION IN C++
• An expression is a valid arrangement of variables, constants/literals, and operators.
• In C++, each expression can be evaluated to compute a value of a given type
• In C++, an expression can be:
– A variable or a constant (count, 100)
– An operation (a + b, a * 2)
– Function call (pow(b, 2) , sqrt(area))
COMPUTER EXPRESSION (1)

(b+sqrt(pow(b,2)-(4*a*c)))/(2*a)

c = sqrt(pow(a,2)+pow(b,2))

A = 1/4*sqrt((a+b+c)*(a*b-c))

b 2  4ac b *b  4* a *c
x( y  z )
1
x * ( y  z)
x2  x  3 1 /( x * x  x  3)
ab
cd (a  b) /( c  d )
KEY TERMS (1)
• Operand
– In computer programming, an operand is a term used to describe any object that is capable of
being manipulated.
– For example, in "1 + 2" the "1" and "2" are the operands and the plus symbol is the operator.
• LITERALS
– the values assigned to each constant variables are referred to as the literals
• NONZERO VALUE
– quantity which does not equal zero is said to be nonzero
– A nonzero number may be either positive or negative
– May represent TRUE value
• ZERO VALUE
– 0 (zero) is both a number and the numerical digit used to represent that number in numerals.
– May represent False value
• Truth Table - lists all combinations of operand values and the value of the expression for each
combination
OPERATOR
• an operator is a character that represents an action, as for example x is an arithmetic operator that
represents multiplication
• in computer programs, one of the most familiar sets of operators, the Boolean operators, is used to
work with true/false values.
TYPES OF OPERATORS
• Unary, binary, and ternary operators are useful for carrying out mathematical operations.
– Unary operators need only one operand to perform the task or operation.
– Binary operators are the one that operate on two operands.
– Ternary operators are the one that operates on three operands.
A. ARITHMETIC OPERATOR
– Additive
• Addition + Sum
• Subtraction - Difference
– Multiplicative
• Multiplication * Product
• Division / Quotient
• Modulo % Remainder
NOTES…’
• For floating numbers, the result is as same as in Math operations.
• Note on integer division: the result is an integer value. Example: 7/2 is 3
• % (remainder or modulo) is the special operator just for integer values. It yields an integer as the
result. Example: 7%2 is 1

B. RELATIONSHIP OPERATOR (TRUE OR FALSE 1 OR 0)

1. RELATIONAL (>,<,>=,<=)

 Greater than >


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

2. EQUALITY (==,!=)

 is equal to ==
 Is not equal to !=

C. BITWISE OPERATOR (TRUE OR FALSE 1 OR 0)(1)


XOR OPERATOR (^)
a. A TRUE/1 output results if one, and only one of the operand is TRUE/1 otherwise FALSE/0.
D. LOGICAL OPERATOR (TRUE OR FALSE 1 OR 0) (1)
LOGICAL NOT OPERATOR (!)
a. Use to reverses the logical state of its operand.
b. If a condition is true, then Logical NOT operator will make false.
AND OPERATOR (&&)
c. You can only obtain TRUE/1 as final result if and only if both operands are TRUE or nonzero
values, otherwise FALSE/0.
OR OPERATOR (||)
d. You can obtain TRUE/1 as final result if at least one (1) operand is TRUE or nonzero value,
otherwise FALSE/0.
NOTES…
• Highest precedence among logical operators is the logical NOT
• AND and OR are low precedence
• Associate left to right with low precedence
• Use parenthesis to override priority or for clarification
• x && y || z will evaluate “x && y ” first
• x && (y || z) will evaluate “y || z” first
E. ASSIGNMENT OPERATOR’

• An operator to give (assign) a value to a variable


• Denoted by ‘=‘
• Only variable can be on the left side
• An expression is on the right side
• Variables keep their assigned values until changed by another assignment statement or by reading
in a new value.
• Variable = Expression
• First, expression on right is evaluated.
• Then the resulting value is stored in the memory location of Variable on left.
NOTE: An automatic type conversion occurs after evaluation but before the value is stored if the types differ
for Expression and Variable.
PRECEDENCE RULE (GENERALIZED)
OPERATORS SYMBOL ASSOCIATIVITY
1. Parentheses/Functions () INNER
2. Logical Not and Unary !, ++,-- R to L
3. Multiplicative *,/,% L to R
4. Additive +,- L to R
5. Relational >,<,>=,<= L to R
6. Equality ==, != L to R
7. Bitwise XOR (^) L to R
8. Logical And && L to R
9. Logical Or || L to R
10. Assignment
MODULE 3
CONDITIONAL STATEMENTS

RELATIONAL OPERATORS
• The expressions which determine
– Selection
– Repetition are usually comparisons
• Comparisons are done with relational operators

LOGICAL (BOOLEAN) OPERATORS


• The && operator (logical and)
– If both operands are true, the result is true
– If either or both operands is false, the comparison is false
• The || operator (logical or)
– If either or both of the operands are true, the comparison is true
– The comparison is false only if both operands are false
• The ! operator (logical not)
– The not operator reverses the logical value of the one operand

SHORT CIRCUIT EVALUATION


• Evaluate this
(x != 0) && (1.0 / x < 0.25)
• If the first condition is false, the program could crash when it tried to divide by zero
– but if the first condition is false, the whole expression is false
– no need to go on
• When C++ evaluates an expression, realizes that fact and does not even make the second comparison
• Called "short circuit" evaluation

3 CONTROL STRUCTURES
• SEQUENCE STRUCTURE
– Programs executed sequentially by default
• SELECTION STRUCTURES
– if, if/else, switch
• REPETITION STRUCTURES
– while, do/while, for
CONTROL STRUCTURES
• Statements can be
executed in sequence
• One right after the other
• No deviation from the
specified sequence
• A selection structure
can be used
• Which statement
is executed is
selected by
whether the
expression is true
or false
CONDITIONAL STATEMENT
• It checks certain conditions (Boolean expressions) before executing certain statements.
• Condition – Selection – Decision
• Expression – Condition
• Statement – any programming statement
• The Selection control structures allow one set of statement to be executed if a condition is true and
another set of actions to be executed if a condition is false.
SINGLE SELECTION STATEMENT
“To be or not to be, that is the question.”
• Or in terms of the single selection statement, we should rephrase it to
“To execute or not to execute, that is the question.”
SINGLE SELECTION STATEMENT
• In C++, the if statement is used for single selection.
• The statement will be executed if and only if the expression evaluates to true.
COMPOUND STATEMENTS
• If more than one statement needs to be executed, these statements must be enclosed within braces
({}).
• These statements are called compound statements.
SINGLE SELECTION STATEMENT
Write a program segment that asks for an item price from the user and displays the strings “Expensive!” and
“Can’t Afford” if the price is greater than or equal to 1000.
MULTIPLE SELECTION STATEMENTS
• Selection statements are branching mechanisms in programming languages.
• These branching mechanisms allow us to choose among alternatives.
• In C++, the if-else and the switch statements facilitate the branching.
REVIEW
• The Selection control structures allows one set of statement to be executed if a condition is true and
another set of actions to be executed if a condition is false.

USING LOGICAL OPERATORS


• Simplifies the conditional statement
• Used when two or more needs to be satisfied
• You can have combinations of these operators(i.e. Logical Operators) with other types of operators(i.e.
Relational, Equality, Arithmetic Operators)

SWITCH STRUCTURE
• It is useful if there are a lot of alternatives to choose from.
• However, switch statements can only check equality relationships.
• Switch - Case
- Test variable for multiple values
- Series of case labels and optional default case
switch ( expression ) {
case value1: statement1; break;
case value2: statement2; break;
case valueN: statement3; break;
default: statement4;
}
COMMON PROGRAMMING ERRORS
MODULE 4
CONTROL STRUCTURE: LOOPING STATEMENTS

LOOP STATEMENT

Allows us to execute a statement or


group of statements multiple times.

LOOPING STATEMENT

• is a program instruction that repeats some statements or sequence of statements in a specified number
of times?
INSTANCES OF LOOPS
1. INDEX LOOPS – finite loops
2. INFINITE LOOPS – unended loops
NOTE:
-UNSTARTED
-UNENDED
TYPES OF LOOPS
1. COUNT CONTROLLED LOOP
A. FOR LOOP
2. EVENT CONTROLLED LOOP
A. WHILE LOOP
B. DO WHILE LOOP
FORMULA IN LOOPS
1. INCREMENTATION
num = 10 num++
2. DECREMENTATION
num = -8 num--
3. ACCUMULATOR

num = 20
num = num+2 num+=2
num = num*2 num*=2
+-*/%
PARTS OF A LOOP
1. DECLARATION/INITIALIZATION
int num = 0; or int num; num = 0;
2. CONDITION
< > <= >= == != && ||
3. INCREMENTATION OR DECREMENTATION OR ACCUMULATOR
4. STATEMENTS
cout, cin, if, if-else, nested if, switch, loops, computation
WHILE LOOP IN C++
- Statement in C++ programming language repeatedly executes a target statement as long as a given
condition is true.
- This means in plain English “While some condition is true, do some statement”
FOR LOOP IN C++
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times
SYNTAX:

for(initialization;condition;inc\dec\acc){ statements;
}

DO… WHILE

Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C++ programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.

SYNTAX:
initialization; do {
statement/s; inc/dec/acc;
}while(condition);

NESTED LOOP IN C/C++


C++ programming language allows to use one loop inside another loop. Following section shows few
examples to illustrate
COMMON PROGRAMMING ERROR
1. The three expressions in a for statement are separated by semicolons, not commas or other symbols. For
this reason, it is wrong to write:
for ( expression1, expression2, expression3 )
statement1;
2. Do not place a semicolon at the end of the for (...) and the body of the for loop. The following is
syntactically correct, but possibly logically erroneous if the user intends the cout statement to be inside the
loop.
for (i=0;i<10;i++); cout << “i = ”<< i;

3. The while statement does not include the word do. Thus, it is wrong to write while:
while(condition) do

Statements;
MODULE 5
FUNCTION
DIVIDE AND CONQUER
• Construct a program from smaller pieces or components
• Each piece more manageable than the original program
PROGRAM COMPONENTS IN C++’

• Programs written by
• combining new functions with “prepackaged” functions in the C++ standard library.
• new classes with “prepackaged” classes.
• The standard library provides a rich collection of functions.
• Functions are invoked by a function call
• A function call specifies the function name and provides information (as arguments) that the
called function needs
• Boss to worker analogy:
A boss (the calling function or caller) asks a worker (the called function) to perform a task and return (i.e.,
report back) the results when the task is done.
FUNCTIONS
• These are subprograms or sub routines that execute a specific task.
• TYPE:
1. Standard Functions
2. 2.Programmer-Defined Functions
• FUNCTIONS
1. Allow the programmer to modularize a program
• LOCAL VARIABLES
1. Known only in the function in which they are defined
2. All variables declared in function definitions are local variables
• PARAMETERS
1. Local variables passed when the function is called that provide the function with outside
information
• WHY WRITE FUNCTIONS?

1. modularity
2. re-use
3. maintenance / testing
MATH LIBRARY FUNCTIONS
• Math library functions
• Allow the programmer to perform common mathematical calculations
• Are used by including the header file <cmath>
• Functions called by writing
functionName (argument)
• Example
cout << sqrt( 900.0 );
• Calls the sqrt (square root) function. The preceding statement would print 30
• The sqrt function takes an argument of type double and returns a result of type double, as do
all functions in the math library
FUNCTION ARGUMENTS CAN BE
• CONSTANTS
sqrt( 4 );
• VARIABLES
sqrt( x );
• EXPRESSIONS
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
FUNCTION PROTOTYPE
• Every function should have a function prototype.
• The function prototype specifies the type of the value that the function returns (if any) and the type,
number, and order of the function's arguments.
return-data-type function-name(argument data types);
or
void function-name(argument data types);
• The use of function prototypes permits error checking of data types by the compiler.
• It also ensures conversion of all arguments passed to the function to the declared argument data type
when the function is called.
• FUNCTION PROTOTYPE
• FUNCTION NAME
• PARAMETERS
• Information the function takes in
• C++ is “strongly typed” – error to pass a parameter of the wrong type
• RETURN TYPE
• Type of information the function passes back to caller (default int)
• void signifies the function returns nothing

• Only needed if function definition comes after the function call in the program
• Example:
int maximum( int, int, int );
• Takes in 3 ints
• Returns an int

FUNCTION DEFINITION IN C++


• Function definitions
• Only written once
• These statements are hidden from other functions.
• Boss to worker analogy:
The boss does not know how the worker gets the job done; he just wants it done
• Define function header and function body
• VALUE-RETURNING FUNCTIONS
return-data-type function-name(parameter list)
{
constant declarations variable declarations
other C++ statements return value
}
• NON VALUE-RETURNING FUNCTIONS
void function-name(parameter list)
{
constant declarations variable declarations
other C++ statements
}
• The argument names in the function header are referred to as formal parameters.
int FindMax(int x, int y)
{
int maximum;
if(x>=y) maximum = x;
else
maximum = y;
return maximum;
}
• Create customized functions to
• Take in data
• Perform operations
• Return the result
• Format for function definition:
return-value-type function-name( parameter-list )
{
declarations and statements
}
• Example:
int square( int y)
{
return y * y;
}
CALLING A FUNCTION
• A function is called by specifying its name followed by its arguments.
• Non-value returning functions:
function-name (data passed to function);

• Value returning functions:


results = function-name (data passed to function);
• The argument names in the function call are referred to as actual parameters
CALLING A FUNCTION AND ITS PARAMETERS
• CALL BY VALUE
• Copy of data passed to function
• Changes to copy do not change original
• Used to prevent unwanted side effects
• CALL BY REFERENCE
• Function can directly access data
• Changes affect original
• Reference parameter alias for argument
• & is used to signify a reference
void change( int& variable )
{ variable += 3; }
CALLING A FUNCTION BY VALUE

 Adds 3 to the variable inputted


 The function receives a copy of the actual parameter values.
 The function cannot change the values of the actual parameters.
CALLING A FUNCTION BY REFERENCE
• Very useful when we need a function which "returns more than one value".
• The formal parameter becomes an alias for the actual parameter.
• The function can change the values of the actual parameters.
FUNCTION OVERLOADING
• C++ provides the capability of using the same function name for more than one function (function
overloading).
• The compiler must be able to determine which function to use based on the number and data types of
the parameters.
MODULE 6
ARRAY
• ARRAYS

– Structures of related data items


– Static entity (same size throughout program)
• A FEW TYPES
– Pointer-based arrays (C-like)
– Arrays as objects (C++)

• ARRAY
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
• TO REFER TO AN ELEMENT
– Specify array name and position number (index)
– Format: arrayname[ position number ]
– First element at position 0
• N-ELEMENT ARRAY C
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1

• Array elements like other variables


– Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
• Can perform operations inside subscript
c[ 5– 2 ] same as c[3]
DECLARING ARRAYS
• WHEN DECLARING ARRAYS, SPECIFY
– Name
– Type of array
• Any data type
– Number of elements
– type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats
• DECLARING MULTIPLE ARRAYS OF SAME TYPE
– Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
• INITIALIZING ARRAYS
– FOR LOOP
• Set each element
– INITIALIZER LIST

• Specify each element when array declared


int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array

• ARRAY SIZE
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
• STRINGS
ARRAYS OF CHARACTERS
– All strings end with null ('\0')

– Examples
• char string1[] = "hello";
– Null character implicitly added
– string1 has 6 elements
• char string1[] = {'h','e','l','l','o','\0’};
– Subscripting is the same String1[ 0 ] is 'h' string1[ 2 ] is 'l'

EXAMPLES USING ARRAYS


• INPUT FROM KEYBOARD
char string2[ 10 ]; cin >> string2;
– Puts user input in string
• Stops at first whitespace character
• Adds null character
– If too much text entered, data written beyond array
• We want to avoid this
• PRINTING STRINGS
– cout << string2 << endl;
• Does not work for other array types
– Characters printed until null found

MULTIPLE-SUBSCRIPTED ARRAYS
• A program to keep track of students grades
Multiple-subscripted array (table)
Rows are students
Columns are grades

You might also like