Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Computer Programming

Uploaded by

gelgeuk02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Computer Programming

Uploaded by

gelgeuk02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 288

Wolkite Satellite institute

Computer Programming

Why Program?

Tesfaye Y.
Why Program?
Computer – programmable machine designed
to follow instructions
Program – instructions in computer memory to
make it do something
Programmer – person who writes instructions
(programs) to make computer perform a task

SO, without programmers, no programs;


without programs, a computer cannot do
anything
Main Hardware Component
Categories:
1. Central Processing Unit (CPU)
2. Main Memory
3. Secondary Memory / Storage
4. Input Devices
5. Output Devices
Main Hardware Component
Categories

Figure 1-2
Central Processing Unit (CPU)
Comprised of:
Control Unit
Retrieves and decodes program instructions
Coordinates activities of all other parts of computer
Arithmetic & Logic Unit
Hardware optimized for high-speed numeric
calculation
Hardware designed for true/false, yes/no decisions
CPU Organization

Figure 1-3
Main Memory
• It is volatile. Main memory is erased when
program terminates or computer is turned off
• Also called Random Access Memory (RAM)
• Organized as follows:
– bit: smallest piece of memory. Has values 0 (off,
false) or 1 (on, true)
– byte: 8 consecutive bits. Bytes have addresses.
Main Memory
• Addresses – Each byte in memory is
identified by a unique number known as
an address.
Secondary Storage
• Non-volatile: data retained when program
is not running or computer is turned off
• Comes in a variety of media:
– magnetic: floppy disk, hard drive
– optical: CD-ROM, DVD
– Flash drives, connected to the USB port
Input Devices
• Devices that send information to the
computer from outside
• Many devices can provide input:
– Keyboard, mouse, scanner, digital camera,
microphone
– Disk drives, CD drives, and DVD drives
Software-Programs That Run on a
Computer
• Categories of software:
– System software: programs that manage the
computer hardware and the programs that run
on them. Examples: operating systems, utility
programs, software development tools
– Application software: programs that provide
services to the user. Examples : word
processing, games, programs to solve
specific problems
Programs and Programming
Languages
• A program is a set of instructions that the
computer follows to perform a task

• We start with an algorithm, which is a set


of well-defined steps.
Example Algorithm for Calculating
Gross Pay
Machine Language
• Although the previous algorithm defines
the steps for calculating the gross pay, it is
not ready to be executed on the computer.
• The computer only executes machine
language instructions
Machine Language
• Machine language instructions are binary
numbers, such as

1011010000000101

• Rather than writing programs in machine


language, programmers use programming
languages.
Programs and Programming
Languages
• Types of languages:

– Low-level: used for


communication with computer
hardware directly. Often written
in binary machine code (0’s/1’s)
directly.

– High-level: closer to human


language
Some Well-Known Programming
Languages (Table 1-1 on Page 10)

C++
BASIC Ruby
FORTRAN
Java
Visual Basic
COBOL
C#
JavaScript
C Python
From a High-Level Program to an
Executable File
a) Create file containing the program with a text
editor.
b) Run preprocessor to convert source file
directives to source code program statements.
c) Run compiler to convert source program into
machine instructions.
d) Run linker to connect hardware-specific code to
machine instructions, producing an executable
file.
• Steps b–d are often performed by a single
command or button click.
• Errors detected at any step will prevent
execution of following steps.
From a High-Level Program to an
Executable File
Integrated Development
Environments (IDEs)
• An integrated development environment,
or IDE, combine all the tools needed to
write, compile, and debug a program into a
single software application.
• Examples are Microsoft Visual C++, Turbo
C++ Explorer, CodeWarrior, etc.
Integrated Development
Environments (IDEs)
What is a Program Made of?
• Common elements in programming
languages:
– Key Words
– Programmer-Defined Identifiers
– Operators
– Punctuation
– Syntax
Program 1-1
Key Words
• Also known as reserved words
• Have a special meaning in C++
• Can not be used for any other purpose
• Key words in the Program 1-1: using,
namespace, int, double, and return
Key Words
Programmer-Defined Identifiers
• Names made up by the programmer
• Not part of the C++ language
• Used to represent various things: variables
(memory locations), functions, etc.
• In Program 1-1: hours, rate, and pay.
Operators
• Used to perform operations on data
• Many types of operators:
– Arithmetic - ex: +,-,*,/
– Assignment – ex: =

• Some operators in Program1-1:


<< >> = *
Operators
Punctuation
Syntax
• The rules of grammar that must be
followed when writing a program
• Controls the use of key words, operators,
programmer-defined symbols, and
punctuation
Variables
• A variable is a named storage location in
the computer’s memory for holding a piece
of data.
• In Program 1-1 we used three variables:
– The hours variable was used to hold the
hours worked
– The rate variable was used to hold the pay
rate
– The pay variable was used to hold the gross
pay
Variable Definitions
• To create a variable in a program you
must write a variable definition (also called
a variable declaration)

• Here is the statement from Program 1-1


that defines the variables:

double hours, rate, pay;


Variable Definitions
• There are many different types of data,
which you will learn about in this course.

• A variable holds a specific type of data.

• The variable definition specifies the type of


data a variable can hold, and the variable
name.
Variable Definitions
• Once again, line 7 from Program 1-1:

double hours, rate, pay;

• The word double specifies that the


variables can hold double-precision
floating point numbers. (You will learn
more about that in Chapter 2)
1.5
Input, Processing, and Output
Input, Processing, and Output
Three steps that a program typically
performs:
1) Gather input data:
• from keyboard
• from files on disk drives
2) Process the input data
3) Display the results as output:
• send it to the screen
• write to a file
The Programming Process
Procedural and Object-Oriented
Programming
Procedural and Object-Oriented
Programming
• Procedural programming: focus is on the
process. Procedures/functions are written
to process data.
• Object-Oriented programming: focus is on
objects, which contain data and the means
to manipulate the data. Messages sent to
objects to perform operations.
The Parts of a C++ Program
// sample C++ program comment
#include <iostream> preprocessor directive
using namespace std; which namespace to use
int main() beginning of function named main
{ beginning of block for main
cout << "Hello, there!"; output statement

return 0; send 0 to operating system string literal


} end of block for main
Special Characters
Character Name Meaning
// Double slash Beginning of a comment
# Pound sign Beginning of preprocessor
directive
< > Open/close brackets Enclose filename in #include
( ) Open/close Used when naming a
parentheses function
{ } Open/close brace Encloses a group of
statements
" " Open/close Encloses string of
quotation marks characters
; Semicolon End of a programming
statement
The cout Object
• Displays output on the computer screen

• You use the stream insertion operator <<


to send output to cout:

cout << "Programming is fun!";


The cout Object
• Can be used to send more than one item
to cout:

cout << "Hello " << "there!";


Or:

cout << "Hello ";


cout << "there!";
The cout Object
• This produces one line of output:

cout << "Programming is ";


cout << "fun!";
The endl Manipulator
• You can use the endl manipulator to start
a new line of output. This will produce two
lines of output:

cout << "Programming is" << endl;


cout << "fun!";
The endl Manipulator

cout << "Programming is" << endl;


cout << "fun!";

Programming is
fun!
The endl Manipulator
• You do NOT put quotation marks around
endl

• The last character in endl is a lowercase


L, not the number 1.

endl This is a lowercase L


The \n Escape Sequence
• You can also use the \n escape sequence
to start a new line of output. This will
produce two lines of output:

cout << "Programming is\n";


cout << "fun!";

Notice that the \n is INSIDE


the string.
The \n Escape Sequence
cout << "Programming is\n";
cout << "fun!";

Programming is
fun!
2.3
The #include Directive
The #include Directive
• Inserts the contents of another file into the
program
• This is a preprocessor directive, not part of
C++ language
• #include lines not seen by compiler
• Do not place a semicolon at end of
#include line
2.4
Variables and Literals
Variables and Literals
• Variable: a storage location in memory

– Has a name and a type of data it can hold


– Must be defined before it can be used:

int item;
Variable Definition in Program 2-7

Variable Definition
Literals
• Literal: a value that is written into a
program’s code.

"hello, there" (string literal)


12 (integer literal)
Integer Literal in Program 2-9

20 is an integer literal
String Literals in Program 2-9

These are string literals


2.5
Identifiers
Identifiers
• An identifier is a programmer-defined
name for some part of a program:
variables, functions, etc.
C++ Key Words
You cannot use any of the C++ key words as an
identifier. These words have reserved meaning.
Variable Names
• A variable name should represent the
purpose of the variable. For example:

itemsOrdered

The purpose of this variable is to hold the


number of items ordered.
Identifier Rules
• The first character of an identifier must be
an alphabetic character or and underscore
( _ ),
• After the first character you may use
alphabetic characters, numbers, or
underscore characters.
• Upper- and lowercase characters are
distinct
Valid and Invalid Identifiers
IDENTIFIER VALID? REASON IF INVALID

totalSales Yes

total_Sales Yes

total.Sales No Cannot contain .

4thQtrSales No Cannot begin with digit

totalSale$ No Cannot contain $


2.6
Integer Data Types
Integer Data Types
• Integer variables can hold whole numbers such
as 12, 7, and -99.
Defining Variables
• Variables of the same type can be defined
- On separate lines:
int length;
int width;
unsigned int area;
- On the same line:
int length, width;
unsigned int area;
• Variables of different types must be in different
definitions
Integer Types in Program 2-10

This program has three variables: checking,


miles, and days
Integer Literals
• An integer literal is an integer value that is
typed into a program’s code. For example:

itemsOrdered = 15;

In this code, 15 is an integer literal.


Integer Literals in Program 2-10

Integer Literals
Integer Literals
• Integer literals are stored in memory as
ints by default
• To store an integer constant in a long
memory location, put ‘L’ at the end of the
number: 1234L
• Constants that begin with ‘0’ (zero) are
base 8: 075
• Constants that begin with ‘0x’ are base
16: 0x75A
2.7
The char Data Type
The char Data Type
• Used to hold characters or very small
integer values
• Usually 1 byte of memory
• Numeric value of character from the
character set is stored in memory:
CODE: MEMORY:
char letter; letter
letter = 'C';
67
Character Literals
• Character literals must be enclosed in
single quote marks. Example:

'A'
Character Literals in Program 2-13
Character Strings
• A series of characters in consecutive memory
locations:
"Hello"
• Stored with the null terminator, \0, at the end:

• Comprised of the characters between the " "

H e l l o \0
2.8
The C++ string Class
The C++ string Class
• Special data type supports working with strings
• #include <string>
• Can define string variables in programs:
string firstName, lastName;
• Can receive values with assignment operator:
firstName = "George";
lastName = "Washington";
• Can be displayed via cout
cout << firstName << " " << lastName;
The string class in Program 2-15
2.9
Floating-Point Data Types
Floating-Point Data Types
• The floating-point data types are:
float
double
long double

• They can hold real numbers such as:


12.45 -3.8

• Stored in a form similar to scientific notation

• All floating-point numbers are signed


Floating-Point Data Types
Floating-Point Literals
• Can be represented in
– Fixed point (decimal) notation:
31.4159 0.0000625
– E notation:
3.14159E1 6.25e-5
• Are double by default
• Can be forced to be float (3.14159f) or
long double (0.0000625L)
Floating-Point Data Types in
Program 2-16
2.10
The bool Data Type
The bool Data Type
• Represents values that are true or
false
• bool variables are stored as small
integers
• false is represented by 0, true by 1:
bool allDone = true; allDone finished

1 0
bool finished = false;
Boolean Variables in Program 2-17
2.11
Determining the Size of a Data
Type
Determining the Size of a Data
Type
The sizeof operator gives the size of any
data type or variable:
double amount;
cout << "A double is stored in "
<< sizeof(double) <<
"bytes\n";
cout << "Variable amount is
stored in "
<< sizeof(amount)
<< "bytes\n";
2.12
Variable Assignments and
Initialization
Variable Assignments and
Initialization
• An assignment statement uses the =
operator to store a value in a variable.

item = 12;

• This statement assigns the value 12 to the


item variable.
Assignment
• The variable receiving the value must
appear on the left side of the = operator.
• This will NOT work:

// ERROR!
12 = item;
Variable Initialization
• To initialize a variable means to assign it a
value when it is defined:

int length = 12;

• Can initialize some or all variables:


int length = 12, width = 5, area;
Variable Initialization in Program 2-
19
2.13
Scope
Scope
• The scope of a variable: the part of the
program in which the variable can be
accessed
• A variable cannot be used before it is
defined
Variable Out of Scope in Program
2-20
2.14
Arithmetic Operators
Arithmetic Operators
• Used for performing numeric calculations
• C++ has unary, binary, and ternary
operators:
– unary (1 operand) -5
– binary (2 operands) 13 - 7
– ternary (3 operands) exp1 ? exp2 : exp3
Binary Arithmetic Operators
SYMBOL OPERATION EXAMPLE VALUE OF
ans
+ addition ans = 7 + 3; 10

- subtraction ans = 7 - 3; 4

* multiplication ans = 7 * 3; 21

/ division ans = 7 / 3; 2

% modulus ans = 7 % 3; 1
Arithmetic Operators in Program 2-
21
A Closer Look at the / Operator
• / (division) operator performs integer
division if both operands are integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
• If either operand is floating point, the result
is floating point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
A Closer Look at the % Operator
• % (modulus) operator computes the
remainder resulting from integer division
cout << 13 % 5; // displays 3
• % requires integers for both operands
cout << 13 % 5.0; // error
2.15
Comments
Comments
• Used to document parts of the program
• Intended for persons reading the source
code of the program:
– Indicate the purpose of the program
– Describe the use of variables
– Explain complex sections of code
• Are ignored by the compiler
Single-Line Comments
Begin with // through to the end of line:
int length = 12; // length in
inches
int width = 15; // width in inches
int area; // calculated area

// calculate rectangle area


area = length * width;
Multi-Line Comments
• Begin with /*, end with */
• Can span multiple lines:
/* this is a multi-line
comment
*/
• Can begin and end on the same line:
int area; /* calculated area */
2.16
Named Constants
Named Constants
• Named constant (constant variable):
variable whose content cannot be
changed during program execution
• Used for representing constant values with
descriptive names:
const double TAX_RATE = 0.0675;
const int NUM_STATES = 50;
• Often named in uppercase letters
Named Constants in Program 2-28
2.17
Programming Style
Programming Style
• The visual organization of the source code
• Includes the use of spaces, tabs, and
blank lines
• Does not affect the syntax of the program
• Affects the readability of the source code
Programming Style
Common elements to improve readability:
• Braces { } aligned vertically
• Indentation of statements within a set of
braces
• Blank lines between declaration and other
statements
• Long statements wrapped over multiple
lines with aligned operators
2.18
Standard and Prestandard C++
Standard and Prestandard C++
Older-style C++ programs:
– Use .h at end of header files:
– #include <iostream.h>
– Use #define preprocessor directive instead
of const definitions
– Do not use using namespace convention
– May not compile with a standard C++
compiler
#define directive in Program 2-31
Chapter 3:

Expressions and Interactivity

• The cin Object


The cin Object
• Standard input object
• Like cout, requires iostream file
• Used to read input from keyboard
• Information retrieved from cin with >>
• Input is stored in one or more variables
The cin Object in Program 3-1
The cin Object
• cin converts data to the type that
matches the variable:

int height;
cout << "How tall is the room? ";
cin >> height;
Displaying a Prompt
• A prompt is a message that instructs the
user to enter data.
• You should always use cout to display a
prompt before each cin statement.

cout << "How tall is the room? ";


cin >> height;
The cin Object
• Can be used to input more than one value:
cin >> height >> width;

• Multiple values from keyboard must be


separated by spaces

• Order is important: first value entered goes to


first variable, etc.
The cin Object Gathers Multiple
Values in Program 3-2
The cin Object Reads Different
Data Types in Program 3-3
3.2
Mathematical Expressions
Mathematical Expressions
• Can create complex expressions using multiple
mathematical operators
• An expression can be a literal, a variable, or a
mathematical combination of constants and
variables
• Can be used in assignment, cout, other
statements:
area = 2 * PI * radius;
cout << "border is: " << 2*(l+w);
Order of Operations
In an expression with more than one operator,
evaluate in this order:
- (unary negation), in order, right to left
* / %, in order, left to right
+ -, in order, left to right
In the expression 2 + 2 * 2 – 2

evaluate
evaluate evaluate third
second first
Order of Operations
Associativity of Operators
• - (unary negation) associates right to left
• *, /, %, +, - associate left to right
• parentheses ( ) can be used to override the
order of operations:
2 + 2 * 2 – 2 = 4
(2 + 2) * 2 – 2 = 6
2 + 2 * (2 – 2) = 2
(2 + 2) * (2 – 2) = 0
Grouping with Parentheses
Algebraic Expressions
• Multiplication requires an operator:
Area=lw is written as Area = l * w;
• There is no exponentiation operator:
Area=s2 is written as Area = pow(s, 2);
• Parentheses may be needed to maintain
order of operations:
y 2  y1 is written as
m m = (y2-y1) /(x2-x1);
x 2  x1
Algebraic Expressions
3.3
When You Mix Apples with
Oranges: Type Conversion
When You Mix Apples with
Oranges: Type Conversion
• Operations are performed between
operands of the same type.
• If not of the same type, C++ will convert
one to be the type of the other
• This can impact the results of calculations.
Hierarchy of Types
Highest: long double
double
float
unsigned long
long
unsigned int
int
Lowest:
Ranked by largest number they can hold
Type Coercion
• Type Coercion: automatic conversion of
an operand to another data type
• Promotion: convert to a higher type
• Demotion: convert to a lower type
Coercion Rules
1) char, short, unsigned short
automatically promoted to int
2) When operating on values of different
data types, the lower one is promoted to
the type of the higher one.
3) When using the = operator, the type of
expression on right will be converted to
type of variable on left
3.4
Overflow and Underflow
Overflow and Underflow
• Occurs when assigning a value that is too
large (overflow) or too small (underflow) to
be held in a variable
• Variable contains value that is ‘wrapped
around’ set of possible values
• Different systems may display a
warning/error message, stop the program,
or continue execution using the incorrect
value
3.5
Type Casting
Type Casting
• Used for manual data type conversion
• Useful for floating point division using ints:
double m;
m = static_cast<double>(y2-y1)
/(x2-x1);
• Useful to see int value of a char
variable:
char ch = 'C';
cout << ch << " is "
<< static_cast<int>(ch);
Type Casting in Program 3-9
C-Style and Prestandard Type Cast
Expressions
• C-Style cast: data type name in ()
cout << ch << " is " << (int)ch;
• Prestandard C++ cast: value in ()
cout << ch << " is " << int(ch);
• Both are still supported in C++, although
static_cast is preferred
3.6
Multiple Assignment and
Combined Assignment
Multiple Assignment and Combined
Assignment
• The = can be used to assign a value to
multiple variables:
x = y = z = 5;
• Value of = is the value that is assigned
• Associates right to left:
x = (y = (z = 5));

value value value


is 5 is 5 is 5
Combined Assignment
• Look at the following statement:

sum = sum + 1;

This adds 1 to the variable sum.


Other Similar Statements
Combined Assignment
• The combined assignment operators provide a
shorthand for these types of statements.
• The statement
sum = sum + 1;
is equivalent to
sum += 1;
Combined Assignment Operators
3.7
Formatting Output
Formatting Output
• Can control how output displays for
numeric, string data:
– size
– position
– number of digits
• Requires iomanip header file
Stream Manipulators
• Used to control how an output field is
displayed

• Some affect just the next value displayed:


– setw(x): print in a field at least x spaces
wide. Use more spaces if field is not wide
enough
The setw Stream Manipulator in
Program 3-13

Continued…
The setw Stream Manipulator in
Program 3-13
Stream Manipulators
• Some affect values until changed again:
– fixed: use decimal notation for floating-point
values
– setprecision(x): when used with fixed,
print floating-point value using x digits after
the decimal. Without fixed, print floating-
point value using x significant digits
– showpoint: always print decimal for floating-
point values
More Stream Manipulators in
Program 3-17

Continued…
More Stream Manipulators in
Program 3-17
Stream Manipulators
3.8
Working with Characters and
string Objects
Working with Characters and
string Objects
• Using cin with the >> operator to input
strings can cause problems:
• It passes over and ignores any leading
whitespace characters (spaces, tabs, or
line breaks)
• To work around this problem, you can use
a C++ function named getline.
Using getline in Program 3-19
Working with Characters and
string Objects
• To read a single character:
– Use cin:
char ch;
cout << "Strike any key to continue";
cin >> ch;
Problem: will skip over blanks, tabs, <CR>
– Use cin.get():
cin.get(ch);
Will read the next character entered, even
whitespace
Using cin.get() in Program 3-21
Working with Characters and
string Objects
• Mixing cin >> and cin.get() in the same
program can cause input errors that are hard to
detect
• To skip over unneeded characters that are still in
the keyboard buffer, use cin.ignore():
cin.ignore(); // skip next char
cin.ignore(10, '\n'); // skip the next
// 10 char. or until a '\n'
string Member Functions and
Operators
• To find the length of a string:
string state = "Texas";
int size = state.length();

• To concatenate (join) multiple strings:


greeting2 = greeting1 + name1;
greeting1 = greeting1 + name2;

Or using the += combined assignment


operator:
greeting1 += name2;
3.9
More Mathematical Library
Functions
More Mathematical Library
Functions
• Require cmath header file
• Take double as input, return a double
• Commonly used functions:
sin Sine
cos Cosine
tan Tangent
sqrt Square root
log Natural (e) log
abs Absolute value (takes and returns an int)
More Mathematical Library
Functions
• These require cstdlib header file
• rand(): returns a random number (int)
between 0 and the largest int the compute
holds. Yields same sequence of numbers
each time program is run.
• srand(x): initializes random number
generator with unsigned int x
The Program

Continued…
The Program

Continued…
The Program
Chapter 4:

Making
Decisions
Relational Operators
• Used to compare numbers to determine
relative order
• Operators:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Relational Expressions
• Boolean expressions – true or false
• Examples:
12 > 5 is true
7 <= 5 is false

if x is 10, then
x == 10 is true,
x != 8 is true, and
x == 8 is false
Relational Expressions
• Can be assigned to a variable:
result = x <= y;
• Assigns 0 for false, 1 for true
4.2
The if Statement
The if Statement
• Allows statements to be conditionally
executed or skipped over
• Models the way we mentally evaluate
situations:
– "If it is raining, take an umbrella."
– "If it is cold outside, wear a coat."
Flowchart for Evaluating a Decision
Flowchart for Evaluating a Decision
The if Statement
• General Format:

if (expression)
statement;
The if Statement-What Happens
To evaluate:
if (expression)
statement;
• If the expression is true, then
statement is executed.
• If the expression is false, then
statement is skipped.
if Statement in Program 4-2

Continued…
if Statement in Program 4-2
Flowchart for Program 4-2 Lines 21
and 22
if Statement Notes
• Do not place ; after (expression)
• Place statement; on a separate line
after (expression), indented:
if (score > 90)
grade = 'A';
• Be careful testing floats and doubles
for equality
• 0 is false; any other value is true
4.3
Expanding the if Statement
Expanding the if Statement
• To execute more than one statement as part of
an if statement, enclose them in { }:
if (score > 90)
{
grade = 'A';
cout << "Good Job!\n";
}
• { } creates a block of code
4.4
The if/else Statement
The if/else statement
• Provides two possible paths of execution
• Performs one statement or block if the
expression is true, otherwise performs
another statement or block.
The if/else statement
• General Format:
if (expression)
statement1; // or block
else
statement2; // or block
if/else-What Happens
To evaluate:
if (expression)
statement1;
else
statement2;

• If the expression is true, then statement1 is


executed and statement2 is skipped.
• If the expression is false, then statement1 is
skipped and statement2 is executed.
The if/else statement and
Modulus Operator in Program 4-8
Flowchart for Program 4-8 Lines 14
through 18
Testing the Divisor in Program 4-9

Continued…
Testing the Divisor in Program 4-9
4.5
Nested if Statements
Nested if Statements
• An if statement that is nested inside
another if statement
• Nested if statements can be used to test
more than one condition
Flowchart for a Nested if
Statement
Nested if Statements
• From Program 4-10
Nested if Statements
• Another example, from Program 4-1
Use Proper Indentation!
4.6
The if/else if Statement
The if/else if Statement
• Tests a series of conditions until one is
found to be true
• Often simpler than using nested if/else
statements
• Can be used to model thought processes
such as:
"If it is raining, take an umbrella,
else, if it is windy, take a hat,
else, take sunglasses”
if/else if Format
if (expression)
statement1; // or block
else if (expression)
statement2; // or block
.
. // other else ifs
.
else if (expression)
statementn; // or block
The if/else if Statement in
Program 4-13
Using a Trailing else to Catch
Errors in Program 4-14
• The trailing else clause is optional, but it
is best used to catch errors.

This trailing
else
catches
invalid test
scores
4.7
Flags
Flags
• Variable that signals a condition
• Usually implemented as a bool variable
• Can also be an integer
– The value 0 is considered false
– Any nonzero value is considered true
• As with other variables in functions, must
be assigned an initial value before it is
used
4.8
Logical Operators
Logical Operators
• Used to create relational expressions from
other relational expressions
• Operators, meaning, and explanation:
&& AND New relational expression is true if both
expressions are true
|| OR New relational expression is true if either
expression is true
! NOT Reverses the value of an expression – true
expression becomes false, and false becomes
true
Logical Operators-Examples
int x = 12, y = 5, z = -4;
(x > y) && (y > z) true

(x > y) && (z > y) false

(x <= z) || (y == z) false

(x <= z) || (y != z) true

!(x >= z) false


The logical && operator in Program
4-15
The logical || Operator in Program
4-16
The logical ! Operator in Program
4-17
Logical Operator-Notes
• ! has highest precedence, followed by &&,
then ||
• If the value of an expression can be
determined by evaluating just the sub-
expression on left side of a logical
operator, then the sub-expression on the
right side will not be evaluated (short
circuit evaluation)
4.9
Checking Numeric Ranges with
Logical Operators
Checking Numeric Ranges with
Logical Operators
• Used to test to see if a value falls inside a range:
if (grade >= 0 && grade <= 100)
cout << "Valid grade";
• Can also test to see if value falls outside of range:
if (grade <= 0 || grade >= 100)
cout << "Invalid grade";
• Cannot use mathematical notation:
if (0 <= grade <= 100) //doesn’t work!
4.10
Menus
Menus
• Menu-driven program: program execution
controlled by user selecting from a list of
actions
• Menu: list of choices on the screen
• Menus can be implemented using
if/else if statements
Menu-Driven Program Organization
• Display list of numbered or lettered
choices for actions
• Prompt user to make selection
• Test user selection in expression
– if a match, then execute code for action
– if not, then go on to next expression
4.11
Validating User Input
Validating User Input
• Input validation: inspecting input data to
determine whether it is acceptable
• Bad output will be produced from bad
input
• Can perform various tests:
– Range
– Reasonableness
– Valid menu choice
– Divide by zero
4.12
The Conditional Operator
The Conditional Operator
• Can use to create short if/else
statements
• Format: expr ? expr : expr;

x<0 ? y=10 : z=20;

First Expression: 2nd Expression: 3rd Expression:


Expression to be Executes if first Executes if the first
tested expression is true expression is false
The Conditional Operator
• The value of a conditional expression is
– The value of the second expression if the first
expression is true
– The value of the third expression if the first
expression is false
• Parentheses () may be needed in an
expression due to precedence of
conditional operator
The Conditional Operator in
Program 4-22
4.14
The switch Statement
The switch Statement
• Used to select among statements from
several alternatives
• In some cases, can be used instead of
if/else if statements
switch Statement Format
switch (expression) //integer
{
case exp1: statement1;
case exp2: statement2;
...
case expn: statementn;
default: statementn+1;
}
The switch Statement in Program
4-23
switch Statement Requirements
1) expression must be an integer variable
or an expression that evaluates to an
integer value
2) exp1 through expn must be constant
integer expressions or literals, and must
be unique in the switch statement
3) default is optional but recommended
switch Statement-How it Works
1) expression is evaluated
2) The value of expression is compared
against exp1 through expn.
3) If expression matches value expi, the
program branches to the statement
following expi and continues to the end
of the switch
4) If no matching value is found, the
program branches to the statement after
default:
break Statement
• Used to exit a switch statement
• If it is left out, the program "falls through"
the remaining statements in the switch
statement
break and default statements in
Program 4-25

Continued…
break and default statements in
Program 4-25
Using switch in Menu Systems
• switch statement is a natural choice for
menu-driven program:
– display the menu
– then, get the user's menu selection
– use user input as expression in switch
statement
– use menu choices as expr in case
statements
4.15
More About Blocks and Scope
More About Blocks and Scope
• Scope of a variable is the block in which it
is defined, from the point of definition to
the end of the block
• Usually defined at beginning of function
• May be defined close to first use
Inner Block Variable Definition in
Program 4-29
Variables with the Same Name
• Variables defined inside { } have local or
block scope
• When inside a block within another block,
can define variables with the same name
as in the outer block.
– When in inner block, outer definition is not
available
– Not a good idea
Two Variables with the Same
Name in Program 4-30
Chapter 7:

Arrays
7.1
Arrays Hold Multiple Values
Arrays Hold Multiple Values
• Array: variable that can store multiple
values of the same type
• Values are stored in adjacent memory
locations
• Declared using [] operator:
int tests[5];
Array - Memory Layout
• The definition:
int tests[5];
allocates the following memory:

first second third fourth fifth


element element element element element
Array Terminology

In the definition int tests[5];


• int is the data type of the array elements
• tests is the name of the array
• 5, in [5], is the size declarator. It shows
the number of elements in the array.
• The size of an array is (number of
elements) * (size of each element)
Array Terminology

• The size of an array is:


– the total number of bytes allocated for it
– (number of elements) * (number of bytes for
each element)
• Examples:
int tests[5] is an array of 20 bytes,
assuming 4 bytes for an int
long double measures[10]is an array of
80 bytes, assuming 8 bytes for a long double
Size Declarators
• Named constants are commonly used as
size declarators.

const int SIZE = 5;


int tests[SIZE];
• This eases program maintenance when
the size of the array needs to be changed.
7.2
Accessing Array Elements
Accessing Array Elements

• Each element in an array is assigned a


unique subscript.
• Subscripts start at 0

subscripts:
0 1 2 3 4
Accessing Array Elements

• The last element’s subscript is n-1 where n


is the number of elements in the array.

subscripts:
0 1 2 3 4
Accessing Array Elements
• Array elements can be used as regular variables:
tests[0] = 79;
cout << tests[0];
cin >> tests[1];
tests[4] = tests[0] + tests[1];
• Arrays must be accessed via individual
elements:
cout << tests; // not legal
(Program Continues)
Here are the contents of the hours array, with the values
entered by the user in the example output:
Accessing Array Contents

• Can access element with a constant or


literal subscript:
cout << tests[3] << endl;

• Can use integer expression as subscript:


int i = 5;
cout << tests[i] << endl;
Using a Loop to Step Through
an Array
• Example – The following code defines an
array, numbers, and assigns 99 to each
element:

const int ARRAY_SIZE = 5;


int numbers[ARRAY_SIZE];

for (int count = 0; count < ARRAY_SIZE; count++)


numbers[count] = 99;
A Closer Look At the Loop
Default Initialization
• Global array  all elements initialized to 0
by default

• Local array  all elements uninitialized by


default
7.4
Array Initialization
7.4
Array Initialization
Array Initialization
• Arrays can be initialized with an
initialization list:

const int SIZE = 5;


int tests[SIZE] = {79,82,91,77,84};

• The values are stored in the array in the


order in which they appear in the list.
• The initialization list cannot exceed the
array size. 7-260
Code From Program 7-6
Partial Array Initialization

• If array is initialized with fewer initial


values than the size declarator, the
remaining elements will be set to 0:
Implicit Array Sizing
• Can determine array size by the size of
the initialization list:
int quizzes[]={12,17,15,11};

12 17 15 11

• Must use either array size declarator or


initialization list at array definition
7.5
Processing Array Contents
Processing Array Contents
• Array elements can be treated as ordinary
variables of the same type as the array

• When using ++, -- operators, don’t


confuse the element with the subscript:
tests[i]++; // add 1 to tests[i]
tests[i++]; // increment i, no
// effect on tests
Array Assignment

To copy one array to another,


• Don’t try to assign one array to the other:
newTests = tests; // Won't work

• Instead, assign element-by-element:


for (i = 0; i < ARRAY_SIZE; i++)
newTests[i] = tests[i];
Printing the Contents of an
Array
• You can display the contents of a
character array by sending its name to
cout:

char fName[] = "Henry";


cout << fName << endl;

But, this ONLY works with character arrays!


Printing the Contents of an
Array
• For other types of arrays, you must print
element-by-element:

for (i = 0; i < ARRAY_SIZE; i++)


cout << tests[i] << endl;
Summing and Averaging
Array Elements
• Use a simple loop to add together array
elements:
int tnum;
double average, sum = 0;
for(tnum = 0; tnum < SIZE; tnum++)
sum += tests[tnum];
• Once summed, can compute average:
average = sum / SIZE;
Finding the Highest Value in an
Array
int count;
int highest;
highest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}

When this code is finished, the highest variable will contains the highest value
in the numbers array.
Finding the Lowest Value in an
Array
int count;
int lowest;
lowest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}

When this code is finished, the lowest variable will contains the lowest value in
the numbers array.
Partially-Filled Arrays
• If it is unknown how much data an
array will be holding:
– Make the array large enough to hold the
largest expected number of elements.
– Use a counter variable to keep track of
the number of items stored in the array.
Comparing Arrays

• To compare two arrays, you must compare


element-by-element:
const int SIZE = 5;
int firstArray[SIZE] = { 5, 10, 15, 20, 25 };
int secondArray[SIZE] = { 5, 10, 15, 20, 25 };
bool arraysEqual = true; // Flag variable
int count = 0; // Loop counter variable
// Compare the two arrays.
while (arraysEqual && count < SIZE)
{
if (firstArray[count] != secondArray[count])
arraysEqual = false;
count++;
}
if (arraysEqual)
cout << "The arrays are equal.\n";
else
cout << "The arrays are not equal.\n";
7.6
Using Parallel Arrays
Using Parallel Arrays
• Parallel arrays: two or more arrays that
contain related data
• A subscript is used to relate arrays:
elements at same subscript are related
• Arrays may be of different types
Parallel Array Example
const int SIZE = 5; // Array size
int id[SIZE]; // student ID
double average[SIZE]; // course average
char grade[SIZE]; // course grade
...
for(int i = 0; i < SIZE; i++)
{
cout << "Student ID: " << id[i]
<< " average: " << average[i]
<< " grade: " << grade[i]
<< endl;
}
(Program Continues)
Program 7-12 (Continued)
The hours and payRate arrays are related through their subscripts:
7.7
Arrays as Function Arguments
Arrays as Function Arguments
• To pass an array to a function, just use the array
name:
showScores(tests);
• To define a function that takes an array
parameter, use empty [] for array argument:
void showScores(int []);
// function prototype
void showScores(int tests[])
// function header
Arrays as Function Arguments
• When passing an array to a function, it is common
to pass array size so that function knows how many
elements to process:
showScores(tests, ARRAY_SIZE);
• Array size must also be reflected in prototype,
header:
void showScores(int [], int);
// function prototype
void showScores(int tests[], int size)
// function header

7-282
(Program Continues)
Program 7-14 (Continued)
Modifying Arrays in Functions

• Array names in functions are like


reference variables – changes made to
array in a function are reflected in actual
array in calling function

• Need to exercise caution that array is not


inadvertently changed by a function
7.8
Two-Dimensional Arrays
Two-Dimensional Arrays
• Can define one array for multiple sets of
data
• Like a table in a spreadsheet
• Use two size declarators in definition:

const int ROWS = 4, COLS = 3;


int exams[ROWS][COLS];

• First declarator is number of rows;


second is number of columns
Two-Dimensional Array
Representation
const int ROWS = 4, COLS = 3; int
exams[ROWS][COLS];
columns
exams[0][0] exams[0][1] exams[0][2]
r exams[1][0] exams[1][1] exams[1][2]
o
w exams[2][0] exams[2][1] exams[2][2]
s
exams[3][0] exams[3][1] exams[3][2]

• Use two subscripts to access element:


exams[2][2] = 86;

You might also like