Computer Programming
Computer Programming
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
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
1011010000000101
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: =
Programming is
fun!
The endl Manipulator
• You do NOT put quotation marks around
endl
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
int item;
Variable Definition in Program 2-7
Variable Definition
Literals
• Literal: a value that is written into a
program’s code.
20 is an integer literal
String Literals in Program 2-9
itemsOrdered
totalSales Yes
total_Sales Yes
itemsOrdered = 15;
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:
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
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;
// ERROR!
12 = item;
Variable Initialization
• To initialize a variable means to assign it a
value when it is defined:
- 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
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.
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));
sum = sum + 1;
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();
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;
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 <= z) || (y == z) false
(x <= z) || (y != z) true
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:
subscripts:
0 1 2 3 4
Accessing Array Elements
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
12 17 15 11
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
7-282
(Program Continues)
Program 7-14 (Continued)
Modifying Arrays in Functions