Professional Documents
Culture Documents
PART (I)
WEEK #2
5
COMPUTER
PROGRAM?
DEFINITION
FUNCTION
(SUB-PROGRAM)
• Is a collection of statements
• When it is executed, it will accomplish something
• Can either be:
✓ Written on your own
✓ Already written and provided by the system
(Pre-defined Function)
THE BASICS OF A C++ PROGRAM
9
SYNTAX RULES
• rules that determines whether the statements
(instructions) within the program are valid or not
• If valid, this means that the statements are accepted
by the programming language
SYNTAX ERROR
(detected by the compiler)
caused by missing ;
(semicolon) at line #8
THE BASICS OF A C++ PROGRAM
10
SEMANTIC RULES
• rules that determine the meaning of the instructions
• SEMANTIC ERROR: valid code the compiler
understands, but they do not what you, the
programmer, intended. SEMANTIC ERROR
These may be using the wrong
variable, the wrong operation, or
operations in the wrong order.
THE BASICS OF A C++ PROGRAM
11
COMMENTS
• Are meant only for the human readers, not for the
compiler
• The compiler will ignore comments placed inside
Single line comment: Begin with //
the program
Multiple line comments:
Enclosed between
/* and */
12
✓To define and use the identifier, variable, constant and statement
THE BASICS OF A C++ PROGRAM
13
TOKENS
• smallest element of any programming language that
is meaningful to the compiler.
TOKENS: SPECIAL
SYMBOLS
ADD SUBTRACT MULTIPLICATION DIVISION
+ - *
QUESTION MARK
/
COMMA
MATHEMATICAL SYMBOLS
FULLSTOP SEMICOLON
. ; ? , PUNCTUATION MARKS
TOKENS: WORD
SYMBOLS
RESERVED WORDS (KEYWORDS)
TOKENS: IDENTIFIERS
• Are names of things that appear in a program, includes:
• variables / constants / functions
• All identifiers must obey C++’s rules for identifiers.
• Identifiers can either be: NOTE
• Predefined identifier: C++ is case sensitive—
❑ cout UPPERCASE and lowercase letters are
considered different.
❑ cin the identifier NUMBER ≠ number.
X and x are different identifier.
• User-defined identifier
• Consists of letters, digits and underscore character ( _ )
• No space or comma is allowed
• Must only begin with letter or underscore ( _ )
THE BASICS OF A C++ PROGRAM
17
TOKENS: PRE-DEFINED
IDENTIFIERS
• int can only accept integer type of value.
• char can store only 1 character.
• float can store real constants which contain
decimal.
• double is same as float, just the range is wider
• void means ‘null’ or nothing. Or as good as
‘empty’
THE BASICS OF A C++ PROGRAM
18
TOKENS: IDENTIFIERS
✓ EXAMPLE OF LEGAL USER-DEFINED IDENTIFIERS
salary first num1
total_sum second isAvailable
payRate choice average
counter1 max x1
VA R I A B L E
IDENTIFIERS: VARIABLE
• Is an identifier that refers to memory location, which can
hold values [the value can be changed – varies]
• However, it can only store ONE value at a time
VA R I A B L E D E C L A R AT I O N :
int average;
dataType variableName
THE BASICS OF A C++ PROGRAM
20
IDENTIFIERS: VARIABLE
VA R I A B L E D E C L A R AT I O N
int num1;
int num2;
IDENTIFIERS: CONSTANTS
• = values that are fixed
• The content inside it will not change throughout the program
execution
• The syntax to declare a constant:
const dataType variableName = value;
For example:
const float PI = 3.142; ←variable PI is used to
… represent a constant value
… of 3.142
area = 2 * PI * radius; ←legal statement
PI = number; ←illegal statement
22
22
MAR 2017
23
23
MAR 2016
24
24
OCT 2016
25
DATA TYPES
• Data types are used on identifiers that store data
• Specify the type of data the identifiers can hold
• This include:
✓ Integer
✓ Floating-point
✓ Boolean
✓ Single character
✓ String of characters
THE BASICS OF A C++ PROGRAM
27
✓ EXAMPLE OF INTEGERS
✓ S T R I N G C H A R A C T E R D ATA T Y P E I N C + +
OCT 2016
33
33
MAR 2015
THE BASICS OF A C++ PROGRAM
34
QUICK EXERCISE
✓ D E T E R M I N E W H E T H E R T H E F O L L O W I N G S A R E VA L I D I D E N T I F I E R S :
QUICK EXERCISE
QUICK EXERCISE
✓ G I V E T H E M O S T A P P R O P R I AT E D ATA T Y P E F O R T H E F O L L O W I N G
VA L U E S :
How to declare this and set the initial value in a C++ program?
a. 23
b. ‘C’
c. 18.52
d. true
e. 2.452679753
f. “Michael Jackson”
37
37
MAR 2016
THE BASICS OF A C++ PROGRAM
38
QUICK EXERCISE
✓ D E C L A R E T H E F O L L O W I N G VA R I A B L E S :
a. age
b. grade
c. average
d. sum
e. address
f. totalCost
39
ARITHMETIC OPERATORS
• used to manipulate integral and floating-data types
• This include:
▪ + ADDITION Can be used with:
▪ - SUBTRACTION •Integral data type
▪ * MULTIPLICATION •Floating-point data type
▪ / DIVISION
▪ (gives quotient in ordinary division)
▪ % modulus operator Can be used with:
•Integral data type
▪ (gives remainder in ordinary division)
STRUCTURE OF A OF A C++ PROGRAM
41
ARITHMETIC EXPRESSION
ARITHMETIC EXPRESSION:
• Is constructed by using:
▪ Arithmetic operators
▪ Operands (are the numbers)
UNARY OPERATOR: Example:
UNARY OPERATOR:
ORDER OF PRECEDENCE
int a = 10;
int b = -a; // b = -10
Unary minus (negation) is different from
subtraction operator, as subtraction requires
two operands.
• Order of precedence is RIGHT to LEFT
B I N A RY O P E R AT O R
43
ORDER OF PRECEDENCE
• Needs to be followed when there are more than one
arithmetic operators are used in an expression
OPERATOR OPERATION
+,- Addition
Subtraction LOWEST level of
Are evaluated from left to right precedence
EXAMPLE
• Evaluate the following expressions:
1. x = 8 / 2 * 3 + 4 * 5 % 3
2. x = 8 / 2 * (3 + 4) * 5 % 3
45
REVIEW
• Evaluate the following expressions:
1. x = 7 + 3 * 6 / (2 – 1)
2. x = (7 + 3)* 6 / 2 – 1
3. x = 7 + 3 * 6 / 2 - 1
46
MAR 2015
47
EXPRESSIONS
• INTEGRAL • FLOATING-POINT
EXPRESSION: EXPRESSION:
• Is an expression when all • Is an expression when all of
of the operands the operands (numbers)
(numbers) involved are involved are floating-point
integers • For example: 12.8 * 17.5 –
• For example: 2 + 3 * 5 34.50
• Will give out an integral • Will give out a floating-point
result result
48
EXPRESSIONS
• MIXED EXPRESSION
Is an expression when all of the operands (numbers)
involved are both integers and floating-point
For example: 3 / 2 + 5.5
Rules of Evaluation:
• If the operator have the same type of operands, it will be
evaluated according to the type of operand
QUICK EXERCISE
Evaluate the following expressions:
1. x = 1 – 3 / 2 * 3
2. x = 3 * 3.142 + 5 / 3
3. x = 15.6 / 2 + 5
4. x = 4 * 3 % 5 + 3.14
5. x = 4 * 3 + 7 / 5 – 25.5
50
50
MAR 2017
51
51
OCT 2009
52
QUICK EXERCISE
What is the output of the following program?
int main()
{
int num = 20, x;
x = num / 3;
cout << x;
}
53
2.DECREMENT OPERATOR:
• Decreasethe value of variable by 1 For example:
Syntax: variableName--; count--;
54
PART (II)
WEEK #3
55
VARIABLE INITIALIZATION:
• Variables can be initialized after it was declared
• This is done by giving the variable a value, either by:
(i) Assignment statement
• The syntax to initialize variable:
variableName = expression;
int age = 10;
(ii) Input from user • The value stored inside
variable must MATCH the
cin >> variableName; data type of variable
int age; • This value will represent
the first value that is
cin >> age; placed inside the variable
THE BASICS OF A C++ PROGRAM
57
ASSIGNMENT STATEMENT
• Is used to place value into a variable
• This value is assigned directly within the program by the
programmer and DOES NOT come from the value keyed in
by the user
• The syntax to assign value to a variable:
variableName = expression
For example:
PROMPT LINE
• Will inform the user what to do when interacting with the
program
• ALWAYS include prompt line when getting input from user
OUTPUT STATEMENT
• Is used to display messages or output data
cout << expression; ←Syntax to output
on the screen
For example:
endl MANIPULATOR
• Causes the insertion point to move to the beginning of
the next line ←endl is like pressing
cout << expression << endl; the key ‘ENTER’
For example: when typing
LINE # STATEMENT OUTPUT
1 cout << 29 / 4 << endl; 7
2 cout << “Hello there.” << endl; Hello there
3 cout << 12 << endl; 12
4 cout << “4 + 7” << endl; 4+7
5 cout << 4 + 7 << endl; 11
For example:
6 cout << ‘A’ << endl; A
7 cout << “4 + 7 = ” << 4 + 7 << endl; 4 + 7 = 11
8 cout << 2 + 3 * 5 << endl; 17
9 cout << “Hello \nthere” << 4 + 7 << endl; Hello
there
THE BASICS OF A C++ PROGRAM
67
WHITESPACES
• Are used to separate special symbols, reserved symbols and
identifiers
• It makes the program readable
• This include:
✓ Blanks
✓ Tabs
✓ Newline characters
THE BASICS OF A C++ PROGRAM
68
ESCAPE SEQUENCES
• Allows you to control how your output looks
For example:
SYNTAX ESCAPE SEQUENCE DESCRIPTION
\n Newline Cursor moves to the beginning of the next line
\t Tab Cursor moves to the next tab stop
\b Backspace Cursor moves one space to the left
\r Return Cursor moves to the beginning of the current line
(not the next line)
\\ Backslash Backslash is printed
For example:
\’ Single quotation Single quotation mark is printed
\” Double quotation Double quotation mark is printed
69
QUICK EXERCISE
STRUCTURE OF A
C++ PROGRAM
WHAT SHOULD BE
INSIDE A C++
PROGRAM?
For example:
STRUCTURE OF A OF A C++ PROGRAM
71
PREPROCESSOR DIRECTIVES
• Are commands given to the pre-processor to allow us to
use predefined functions contained inside a header file
#include <headerFileName>
<iostream>
For example:
Allow us to use input and output functions
• cin
• cout
STRUCTURE OF A OF A C++ PROGRAM
72
NAMESPACE
• cin and cout are declared in the header file iostream,
but within std namespace
using namespace std;
#include <iostream>
For example:
SEMICOLONS, BRACKETS
SEMICOLONS AND COMMAS
• Every statement inside a C++ program will end with a
semicolon ;
BRACKETS
• Are used to enclose the body of a function
COMMAS
• Are used to separate items in a list
74
DEBUGGING
QUICK EXERCISE
• Write a simple program that displays:
Hello World!!
I am excited to learn C++ programming.
76
QUICK EXERCISE
• Write a program that prompts the user for their first name
and age. The output should be displayed as below:
Welcome Michael.
This year, you are 20 years old.
This is so exciting!!
NOTE: For this program, you are NOT allowed to use the
endl manipulator
77
QUICK EXERCISE
• Write a program that prompts the user for their full name,
age and gender (M/F). The output should be displayed as
below:
Welcome Michael Jackson.
Your age is 20 years old and your gender is M.
Right now you are no longer Michael Jackson.
Instead, you are a Wonderful Programmer.
QUICK QUESTION
PREPROCESSOR DIRECTIVES
<cmath>
Allow us to use mathematical functions inside a program
• pow(x, y) x to the power of y
• sqrt(x) square root of x
• log(x) natural log of x
• sin(x) sine of x
• cos(x) cosine of x
• tan(x) tangent of x
• abs(x) absolute value of x
Must be in a floating-point expression
81
QUICK EXERCISE
For example:
82
QUICK EXERCISE
For example:
83
REVIEW
• Evaluate the following expressions:PAGE60
84
PREPROCESSOR DIRECTIVES
<cstring> OUTPUT
Allow us to use predefined
functions on cstring
• strcpy(x, y)
• Will copy a string, y into a
variable of type string, x
• strlen(x)
• Will return the length of the
string in x (excluding the null
terminator
85
PREPROCESSOR DIRECTIVES
<iomanip>
Allows you to manipulate how your output is displayed
FUNCTION NAME DESCRIPTION
EXAMPLE
<iomanip> OUTPUT
87
CONTROL STRUCTURES
Computer program can be executed:
• In sequence
• By Selection (Branch): Making a choice
• By Repetition (Iterative): Looping
88
QUICK EXERCISE
For example:
90
QUICK EXERCISE
Write a program for the problem below:
QUICK EXERCISE
Write a program for the problem below:
𝟐
Volume of cylinder = 𝝅𝒓 h
Radius = diameter / 2
92 BASIC ELEMENTS OF COMPUTER PROGRAM
MAR 2017
94
REFERENCES
Malik, D.S (2010). “C++ Programming: From Problem Analysis to
Program Design”. Cengage Learning
Najwa Abd Ghafar. (2018). CSC128: Chap 2 - Basic Elements of
Computer Program [PowerPoint slides in PDF].
Variable, constants and datatype. Retrieved at
http://codefap.com/2012/07/c-tutorial-2-variable-constants-and-
datatypes/
Unary operators in C/C++ Retrieved at
https://www.geeksforgeeks.org/unary-operators-cc/
95