02_Elementary_Programming
02_Elementary_Programming
Programming
These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
of Jordan for the Course: Computer Skills for Engineers (0907101)
Updated by Dr. Ashraf Suyyagh (Spring 2021)
1
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
2
Writing a Simple Program
A program that computes the area of the circle.
4
animation
5
animation
6
animation
int main() {
radius 20
double radius; area 1256.636
double area;
7
animation
8
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
9
Reading Input from the Keyboard
You can use the cin object to read input from the
keyboard.
ComputeAreaWithConsoleInput Run
10
Reading Multiple Input in One
Statement
#include <iostream>
using namespace std;
int main()
{
// Prompt the user to enter three numbers
double number1, number2, number3;
cout << "Enter three numbers: ";
cin >> number1 >> number2 >> number3;
// Compute average
double average = (number1 + number2 + number3) / 3;
// Display result
cout << "The average of " << number1 << " " << number2
<< " " << number3 << " is " << average << endl;
ComputeAverage Run
return 0;
} 11
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
12
Identifiers
Identifiers are the names that identify elements such as
variables and functions in a program.
• An identifier is a sequence of characters that consists of
letters, digits, and underscores (_).
• An identifier must start with a letter or an underscore. It
cannot start with a digit.
• An identifier cannot be a reserved word. (See Appendix
A, “C++ Keywords,” for a list of reserved words.)
• An identifier can be of any length, but your C++ compiler
may impose some restriction. Use identifiers of 31
characters or fewer to ensure portability.
13
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
14
Variables
Variables are used to represent values that may be
changed in the program.
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
16
Declaring Variables
int i, j, k; // Declare three integers
17
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
18
Assignment Statements
An assignment statement designates a value for a variable. An
assignment statement can be used as an expression in C++.
x = 1; // Assign 1 to x;
y = x + 1; // Assign 2 to y;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
19
Assignment Statements
An assignment statement designates a value for a variable.
20
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
21
Named Constants
A named constant is an identifier that represents a
permanent value.
ComputeAreaConstant Run
22
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
23
Numerical Data Types
• Signed integers
– 16 bits: short -3
– 32 bits: int 100000
– 64 bits: long long -2147483648
• Unsigned integers
– 16 bits: unsigned short 4
– 32 bits: unsigned
– 64 bits: unsigned long long
24
Synonymous Types
25
Numerical Data Types
• Floating-point numbers
– 32 bits: float 1.5
– 64 bits: double -1.23456E+2
– 80 bits: long double 9.1e-1000
cout << "1.0 / 3.0 is " << 1.0 / 3.0 << endl;
16 digits
cout << "1.0F / 3.0F is " << 1.0F / 3.0F << endl;
27
Numerical Data Types
Name Synonymy Range Storage Size
28
sizeof Function
You can use the sizeof function to find the size of a type.
For example, the following statement displays the size of
int, long, and double on your machine.
int i = 34;
long k = 1000000;
double d = 5.0;
30
octal and hex literals
• By default, an integer literal is a decimal number.
• To denote a binary integer literal, use a leading
0b or 0B (zero b).
• To denote an octal integer literal, use a leading 0
(zero)
• To denote a hexadecimal integer literal, use a
leading 0x or 0X (zero x).
cout << 10 << " " << 0b10 << " " << 010
<< " " << 0x10;
10 2 8 16 31
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
32
Numeric Operators
33
Integer Division
5 / 3 yields an integer 1.
5.0 / 2 yields a double value 2.5
34
Remainder Operator
Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is
always 1. So you can use this property to determine
whether a number is even or odd.
Suppose today is Saturday and you and your friends are
going to meet in 10 days. What day is in 10 days? You can
find that day is Tuesday using the following expression:
S M T W T F S
0 1 2 3 4 5 6
35
Example: Displaying Time
A program that obtains minutes from seconds.
DisplayTime Run
36
Exponent Operations
pow(a, b) = ab
is translated to
40
Precedence
() Operators contained within pairs of
parentheses are evaluated first.
* / % Multiplication, division, and remainder
operators are applied next.
+ - Addition and subtraction operators are
applied last.
→ If an expression contains several similar
operators, they are applied from left to right.
41
Precedence Example
42
Example: Converting
Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:
FahrenheitToCelsius Run
43
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
44
Displaying the Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The time(0) function in the ctime header file returns
the current time in seconds elapsed since the time
00:00:00 on January 1, 1970 GMT, as shown in Figure 2.1.
This time is known as the Unix epoch because 1970 was
the year when the Unix operating system was formally
introduced.
Elapsed
time
Time
Unix Epoch Current Time
01-01-1970 time(0)
00:00:00 GMT ShowCurrentTime Run
45
ShowCurrentTime.cpp
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// Obtain the total seconds since the midnight, Jan 1,
1970
int totalSeconds = time(0);
// Compute the current second in the minute in the hour
int currentSecond = totalSeconds % 60;
// Obtain the total minutes
int totalMinutes = totalSeconds / 60;
// Compute the current minute in the hour
int currentMinute = totalMinutes % 60;
// Obtain the total hours
long totalHours = totalMinutes / 60;
// Compute the current hour
int currentHour = (int)(totalHours % 24);
// Display results
cout << "Current time is " << currentHour << ":"
<< currentMinute << ":" << currentSecond << " GMT" <<
46
endl;
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
47
Augmented Assignment Operators
48
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
49
Increment and Decrement Operators
Operator Name Description
++var pre- Increments var by 1 and evaluates to the new
increment value in var after the increment.
var++ post- Evaluates to the original value in var and
increment increments var by 1.
--var pre- Decrements var by 1 and evaluates to the new
decrement value in var after the decrement.
50
Increment and
Decrement Operators, cont.
What is the output of the following two sequences?
51
Increment and
Decrement Operators, cont.
Using increment and decrement operators makes
expressions short, but it also makes them complex
and difficult to read. Avoid using these operators in
expressions that modify multiple variables, or the
same variable for multiple times such as this:
52
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
53
Numeric Type Conversion
Consider the following statements:
short i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
54
Type Casting
Implicit casting
double d = 3; // type widening
Explicit casting
int i = static_cast<int>(3.0);
// type narrowing
int i = (int)3.9; // C-style casting
// Fraction part is truncated
55
NOTE
Casting does not change the variable being cast.
For example, d is not changed after casting in
the following code:
double d = 4.5;
int i = static_cast<int>(d);
// d is not changed
56
NOTE
57
Example: Keeping Two Digits
after Decimal Points
Write a program that displays the 6%-sales tax with
two digits after the decimal point.
SalesTax Run
58
Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence
59
Case Study: Counting Monetary Units
60
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
remainingAmount
initialized
// Find the number of quarters in the remaining
amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;