0% found this document useful (0 votes)
24 views56 pages

Topic2 20234 Part2

Uploaded by

Jasmine Evelyna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views56 pages

Topic2 20234 Part2

Uploaded by

Jasmine Evelyna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

CHAPTER 2: SEQUENCE CSC126 – FUNDAMENTALS OF

ALGORITHMS AND COMPUTER

STRUCTURE
PROBLEM SOLVING

UMI HANIM MAZLAN

(PART 2)
COLLEGE OF COMPUTING, INFORMATICS &
MATHEMATICS
2024
2.16 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
system(“Pause”);
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.
system(“Pause”);
CHARACTER STRINGS
q A series of characters in consecutive memory locations: "Hello"
q Stored with the null terminator, \0, at the end:
q Comprised of the characters between the " "

H e l l o \0
CHARACTER STRINGS
q To read an entire line of input, use cin.getline():
const int SIZE = 81;
char address[SIZE]; //or char address[81];
cout << "Enter your address: ";
cin.getline(address, SIZE);

q cin.getline takes two arguments:


­ Name of array to store string
­ Size of the array
system(“Pause”);
READING STRINGS WITH cin
• Can be used to read in a string
• Must first declare an array to hold characters in string:
char myName[21];

• myName is name of array, 21 is the number of characters


that can be stored (the size of the array), including the NULL
character at the end
• Can be used with cin to assign a value:
cin >> myName;
FORMATTED INPUT
q Mixing cin >> and cin.get() in the same program
can cause input errors that are hard to detect
q 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’
OR
cin>>ws; //skips the whitespace, in particular the newline
system(“Pause”);
Mathematical
2.17 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:

* / %, in order, left to right


+ -, in order, left to right

• In the expression 2 + 2 * 2 – 2

evaluate evaluate evaluate


second first third
ORDER OF OPERATIONS
ASSOCIATIVITY OF OPERATORS
• *, /, %, +, - associate right to left
• 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
m= is written as
x 2 - x1 m = (y2-y1) /(x2-x1);
ALGEBRAIC EXPRESSIONS
When You Mix Apples
2.18 and Oranges:
Type Conversion
WHEN YOU MIX APPLES AND ORANGES:
TYPE CONVERSION
q Operations are performed between operands of the same type.
q If not of the same type, C++ will convert one to be the type of the other
q This can impact the results of calculations.
HIERARCHY OF TYPES
Highest: long double
double
float
unsigned long
long
unsigned int
Lowest: int
Ranked by largest number they can hold
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
2.19 Named Constants
NAMED CONSTANTS
q Named constant (constant variable): variable whose content cannot be
changed during program execution
q Used for representing constant values with descriptive names:

const double TAX_RATE = 0.0675;


const int NUM_STATES = 50;

q Often named in uppercase letters


system(“Pause”);
Combined
2.20 Assignment
COMBINED ASSIGNMENT
q Look at the following statement:

sum = sum + 1;

This adds 1 to the variable sum.


OTHER SIMILAR STATEMENTS
COMBINED ASSIGNMENT
q The combined assignment operators provide a shorthand for these
types of statements.
q The statement
sum = sum + 1;
is equivalent to
sum += 1;
COMBINED ASSIGNMENT OPERATORS
Formatting
2.21 Output
FORMATTING OUTPUT
q Can control how output displays for numeric, string data:
­ size
­ position
­ number of digits
q Requires iomanip header file
STREAM MANIPULATORS
q Used to control how an output field is displayed
q 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
STREAM MANIPULATORS
q 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
system(“Pause”);
More
Mathematical
2.22 Library Functions
MORE MATHEMATICAL LIBRARY
FUNCTIONS
q Require math.h header file
q Take double as input, return a double
q Commonly used functions:
sin Sine
cos Cosine
tan Tangent
sqrt Square root
log Natural (e) log
abs Absolute value (takes and returns an int)
Programming
2.23 Errors
PROGRAMMING ERRORS
q Programming errors can be categorized into three types:
q syntax errors,
q runtime errors, and
q logic errors.
SYNTAX ERRORS
q Errors that are detected by the compiler
q Syntax errors result from errors in code construction, such as:
q mistyping a keyword,
q omitting necessary punctuation, or
q using an opening brace without a corresponding closing brace.
q These errors are usually easy to detect, because the compiler tells you
where they are and what caused them.
SYNTAX ERRORS
q The following program would cause a runtime error.

1 #include <iostream>
2 using namespace std
3
4 int main()
5 {
6 cout << "Programming is fun << endl;
7
8 system(“Pause”);
9 }
SYNTAX ERRORS
q When you compile the program using Dev C++, it displays the
following errors:

Line 6 Col 8: [Warning] missing terminating ” character


Line 6 Col 2: [Error] missing terminating ” character
Line 4 Col 1: [Error] expected ‘;’ before ‘int’

q Two errors are reported. First, the semicolon (;) is missing at the end of
line 2. Second, the string Programming is fun should be closed
with a closing quotation mark in line 6.
RUNTIME ERRORS
q Runtime errors cause a program to terminate abnormally.
q They occur while an application is running if the environment detects an
operation that is impossible to carry out.
q Input mistakes typically cause runtime errors. An input error occurs when the
program is waiting for the user to enter a value, but the user enters a value
that the program cannot handle.
q For instance, if the program expects to read in a number, but instead, the user
enters a string, this causes data-type errors to occur.

q Another common source of runtime errors is division by zero. This happens


when the divisor is zero for integer divisions.
RUNTIME ERRORS
q For example, the following program has a syntax error.
1 #include <iostream>
2 using namespace std
3
4 int main()
5 {
6 int i = 4;
7 int j = 0;
8 cout << i/j << endl;
9
10 system(“Pause”);
11
12 }

q i has a value of 4 and j has a value of 0. i/j in line 8 causes a


runtime error of division by zero.
LOGIC ERRORS
q Logic errors occur when a program does not perform the way it was
intended.
q For example, suppose you wrote the following program to convert a Celsius
35 degrees to a Fahrenheit degree:
1 #include <iostream>
2 using namespace std
3
4 int main()
5 {
6 cout<< “Celsius 35 is Fahrenheit degree”<<endl;
7 cout << (9/5)*32 + 32 << endl;
8
9 system(“Pause”);
10
12 }
LOGIC ERRORS
q You will get Fahrenheit 67 degrees, which is wrong. It should be 95.
q In C++, the division for integers is the quotient. The fractional part is
truncated. So 9/5 is 1. To get the correct result, you need to use
9.0/5, which results in 1.8.
q In general, syntax errors are easy to find and easy to correct, because the
compiler indicates where the errors were introduced and why they are
wrong.
q Runtime errors are not difficult to find, either, because the reasons and
locations for the errors are displayed on the console when the program
aborts.
q Finding logic errors, on the other hand, can be very challenging.
Hand Tracing a
2.24 Program
HAND TRACING A PROGRAM
q Hand trace a program: act as if you are the computer, executing a
program:
­ step through and ‘execute’ each statement, one-by-one
­ record the contents of variables after statement execution, using a hand trace
chart (table)

q Useful to locate logic or mathematical errors


REFERENCES
Gaddis, Tony. Starting Out with C++: From Control Structures through
Objects. (2007). Pearson Education, Inc. Publishing as Pearson
Addison-Wesley, Fifth Edition.
Liang, Daniel, Y. Introduction to Programming with C++. (2014).
Pearson, Third Edition

You might also like