You are on page 1of 95

1

CSC128 FUNDAMENTALS OF COMPUTER


PROBLEM SOLVING
TOPIC 2 – BASIC ELEMENTS OF
COMPUTER PROGRAM
2

Basic Elements of Computer Program


3 BASIC ELEMENTS OF COMPUTER PROGRAM

✓ Understand basic program components


✓ Define and use the identifier, variable,
constant and statement
✓ Understand the standard data type (int,
float, double, char, char[ ], const)
✓ Understand the assignment statement (=)
✓ Use the input and output statement
✓ Use the function of cin.getline(), strcpy()
✓ Use the arithmetic operator (+, -, *, /, %)
✓ Understand mathematical predefined
function (sqrt(), abs(), pow() etc.)
✓ Write simple programs
4

Basic Elements of Computer Program

PART (I)
WEEK #2
5

✓To understand basic program components


6

COMPUTER
PROGRAM?
DEFINITION

a set of instructions that tells a computer what to do


1 • Get a glass
INSTRUCTION SETS
2 • Put water Input Process Output
3 • Add a lemon
4 • Add sugar
5 • Taste it
7
A C++ PROGRAM

When you execute this


program, it will print out the
sentence “Hello, welcome to
C+ Programming!!” on the
screen
THE BASICS OF A C++ PROGRAM
8 Every C++ program has a function called main

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.

• C++’s tokens can be divided:


✓ Special symbols
✓ Word symbols
✓ Identifiers
THE BASICS OF A C++ PROGRAM
14

TOKENS: SPECIAL
SYMBOLS
ADD SUBTRACT MULTIPLICATION DIVISION

+ - *
QUESTION MARK
/
COMMA
MATHEMATICAL SYMBOLS

FULLSTOP SEMICOLON
. ; ? , PUNCTUATION MARKS

<= != == >= MADE UP OF 2 CHARACTERS


= SINGLE SYMBOL
= NO CHARACTER IN
BETWEEN 2 CHARACTERS
THE BASICS OF A C++ PROGRAM
15

TOKENS: WORD
SYMBOLS
RESERVED WORDS (KEYWORDS)

• Word symbols = reserved words = keywords


• Letters that make up a reserved word are ALWAYS lowercase
• Cannot be used for anything other than their intended use
• Cannot be refined within any program
EXAMPLE OF RESERVED WORDS
int char
float const
double void
return
THE BASICS OF A C++ PROGRAM
16

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

χ EXAMPLE OF ILLEGAL IDENTIFIERS


ILLEGAL IDENTIFIERS DESCRIPTIONS
employee Salary There can be no space between employee and Salary.
Hello! The exclamation mark (!) cannot be used in an identifier.
one + two The symbol (+) cannot be used in an identifier.
2nd An identifier cannot begin with a digit.
In C++, identifiers can be of any length.
THE BASICS OF A C++ PROGRAM
19

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 :

• Each variable must be declared before they can be used in


the program
EXAMPLE OF VARIABLE DECLARATION IN C++ PROGRAM

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

• The syntax to declare variable:


data-type variable-name;
E X A M P L E O F VA R I A B L E D E C L A R AT I O N

int num1;
int num2;

We can even write these two lines as a comma separated list:


int num1, num2;
THE BASICS OF A C++ PROGRAM
21

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

✓To understand the standard data type (int, float,


double, char, char[ ], const)
THE BASICS OF A C++ PROGRAM
26

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

DATA TYPES: INTEGER


int
• = whole numbers that can either be negative, positive or zero
• CANNOT use comma ( , ) as a separator, within an integer 1,000

✓ EXAMPLE OF INTEGERS

-6728 -10 0 78 +763


I N T E G E R D ATA T Y P E I N C + +

int num1 = 15, num2 = 21;


THE BASICS OF A C++ PROGRAM
28

DATA TYPES: FLOATING-POINTS


float & double
• = decimal numbers
✓ E X A M P L E O F F L O AT I N G - P O I N T S

75.924 0.18 0.0000453 -1.432 7800.0

F L O AT I N G - P O I N T S D ATA T Y P E I N C + + Maximum number of decimal places is 6 or 7

float num1 = 15.7, num2 = 21.3;


double num1 = 15.7312312;
Maximum number of decimal places is 15
THE BASICS OF A C++ PROGRAM
29

DATA TYPES: BOOLEAN (LOGICAL


bool VALUES)
• Only has TWO values:
✓ true
✓ false
• It is used to manipulate logical expressions
✓ B O O L E A N D ATA T Y P E I N C + +

bool isAvailable = true;


THE BASICS OF A C++ PROGRAM
30

DATA TYPES: SINGLE CHARACTER


char
• Represents only one character, which include:
• Letters
• Digits
• Special symbols
• Each character is enclosed using single quotation marks ‘ ’
✓ EXAMPLE OF SINGLE CHARACTER
‘A’ ‘a’ ‘0’ ‘+’ ‘&’
✓ S I N G L E C H A R A C T E R D ATA T Y P E I N C + +

char grade = ‘A’;


THE BASICS OF A C++ PROGRAM
31

DATA TYPES: STRING OF


char varName[size] CHARACTERS
• Represents a sequence of characters
• Each string is enclosed in a double quotation marks “ ”
• Contains a null terminator (\0), therefore the size of string
must be declared one character longer than it actually is
✓ EXAMPLE OF STRING OF CHARACTERS

‟Assalamualaikum.” ‟Hardwork is the key to success”

✓ S T R I N G C H A R A C T E R D ATA T Y P E I N C + +

char grade[10] = “Excellent”;


32
32

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 :

a. myFirstProgram RULES FOR NAMING IDENTIFIERS:


b. MIX-UP ✓The first character in a variable
c. C++Program2 name must be an ALPHABET or
d. quiz7 an UNDERSCORE.
✓No commas or blank spaces are
e. _part_2 allowed within a variable name.
f. full name ✓No special symbol other than an
g. total_fees underscore ( _ ) can be used in a
h. 3rdNumber variable name.
35

QUICK EXERCISE

Are the identifiers


firstName and
FirstName the same?
THE BASICS OF A C++ PROGRAM
36

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

✓To use the arithmetic operator (+, -, *, /, %)


40

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:

• Operator that has only one operand -5;


▪ This include: +, - -(3+8)*(9-4)
BINARY OPERATOR: Example:
• Operator that has two operands 9%4;
• This include: +, -, *, /, % (6/2)*2;
STRUCTURE OF A OF A C++ PROGRAM
42

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

() Parenthesis HIGHEST level


of precedence
*,/,% Multiplication
Division
Modulus Higher level is evaluated first

+,- Addition
Subtraction LOWEST level of
Are evaluated from left to right precedence

Same level of precedence


44

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

• If the operator has both types of operands, then the


integer will be changed to a floating point. Therefore, it
will yield a floating-point result
49

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

INCREMENT AND DECREMENT


OPERATORS
Are usually used to keep track of how many times certain
things have happened For example:
int count = 6;
1.INCREMENT OPERATOR: count++;
• Increase the value of variable by 1 cout<< count;
Output
Syntax: variableName++; On screen
7

2.DECREMENT OPERATOR:
• Decreasethe value of variable by 1 For example:
Syntax: variableName--; count--;
54

Basic Elements of Computer Program

PART (II)
WEEK #3
55

✓To understand the assignment statement (=)


THE BASICS OF A C++ PROGRAM
56

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:

num = 5; ←Read from right to left


“Five is ASSIGNED TO
a variable named num”
THE BASICS OF A C++ PROGRAM
58

SAVING VALUES IN VARIABLES


• Suppose that num1, num2 and num3 are int variables and
the following statements are executed in sequence:
1 num1 = 18;
2 num1 = num1 + 1; 19/5
3/2
3 num2 = num1;
4 num3 = num2 / 5;
5 num3 = num3 / 2;
int
19 19
18 3
1
num1 num2 num3
59

✓To use the input and output statement


THE BASICS OF A C++ PROGRAM
60

PROMPT LINE
• Will inform the user what to do when interacting with the
program
• ALWAYS include prompt line when getting input from user

cout << “Please enter your age”;


cin >> age;
THE BASICS OF A C++ PROGRAM
61

INPUT (READ) STATEMENT


• Is used to read data entered by the user
• The value entered will be stored inside a variable
• The syntax to read input from user and store in variable:
cin >> variableName;
For example:
cin >> age;

• The syntax to read multiple input at once:


cin >> variableName1 >> variableName 2;
For example: cin >> gender >> age;
62

✓To use the function of cin.getline(), strcpy()


THE BASICS OF A C++ PROGRAM
63

string data-type char[ ] DATA TYPE


• Is a programmer-defined data type
• To use it, you need to use a pre-processor directives
• The syntax to use a pre-processor directives for string:
#include <cstring>
string input:
• Is a sequence of zero or more character and is enclosed in
a double quotation marks “ ”
cin.getline(variableName, size);
For example:
char name[30];
cin >> name; OR ←cin function: Will only input one word
cin.getline(name, 30);← cin.getline function: Will input more than one word
THE BASICS OF A C++ PROGRAM
64

Storing string char[ ] DATA TYPE


• To store a string into a variable, the assignment
statement (=) cannot be used, except for initialization
char name[30] = “Michael Jackson”;

name = “James Bond”; ←WRONG
• Therefore, whenever you want to store a string into a variable, a
function called strcpy (string copy) needs to be used
strcpy(x, y); ← It will copy a string, y into a variable of type string, x
For example:
char name[30] = “Michael Jackson”;
......
strcpy(name, “James Bond”); ← CORRECT
THE BASICS OF A C++ PROGRAM
65

OUTPUT STATEMENT
• Is used to display messages or output data
cout << expression; ←Syntax to output
on the screen
For example:

cout << “Welcome to UiTM”; ←Output MESSAGE


cout << name; ←Output VALUE OF VARIABLE
cout << “Welcome to UiTM “ << name;
←Output MESSAGE and VALUE
For example:
OF VARIABLE at the same
time
THE BASICS OF A C++ PROGRAM
66

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

• What would be displayed on the screen for the program


below:
70

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>

For example: #include <iostream>

<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:

Without this, cin and cout will be in the form of:


• std::cin
• std::cout For example:

• To use cin and cout in a program, use the following


two statements: #include <iostream>
using namespace std;
STRUCTURE OF A OF A C++ PROGRAM
73

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

• Is the process of finding and fixing errors in a computer


program
• The compiler will identify the syntax error
• Therefore, syntax errors are found during compilation
75

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.

NOTE: The data “Wonderful Programmer” should be


stored.
78

✓To understand mathematical predefined function (sqrt(),


abs(), pow() etc.)
79

QUICK QUESTION

WHY DO YOU NEED


PREPROCESSOR
DIRECTIVES INSIDE
A PROGRAM?
For example:
80

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

setw(x) Set field width to x


left Places the characters to the left
instead of the right
setprecision(x) Set the floating point precision to x
fixed Display floating point values in
decimal notation
86

EXAMPLE
<iomanip> OUTPUT
87

CONTROL STRUCTURES
Computer program can be executed:
• In sequence
• By Selection (Branch): Making a choice
• By Repetition (Iterative): Looping
88

✓Write simple programs


89

QUICK EXERCISE

Write a program that will


calculate the average of 3
numbers

For example:
90

QUICK EXERCISE
Write a program for the problem below:

Calculate the total wages a student earns working a part


time job, given their wages and hours worked.
91

QUICK EXERCISE
Write a program for the problem below:

The program should calculate and display the volume of a


cylinder. It will prompt the user to enter the diameter and
height of the cylinder. The following formula is given to
calculate the volume of cylinder and the radius
respectively:

𝟐
Volume of cylinder = 𝝅𝒓 h
Radius = diameter / 2
92 BASIC ELEMENTS OF COMPUTER PROGRAM

✓ Understand basic program components


✓ Define and use the identifier, variable,
constant and statement
✓ Understand the standard data type (int,
float, double, char, char[ ], const)
✓ Understand the assignment statement (=)
✓ Use the input and output statement
✓ Use the function of cin.getline(), strcpy()
✓ Use the arithmetic operator (+, -, *, /, %)
✓ Understand mathematical predefined
function (sqrt(), abs(), pow() etc.)
✓ Write simple programs
93
93

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

TOPIC 2 – BASIC ELEMENTS OF


COMPUTER PROGRAM
COMPLETE

You might also like