0% found this document useful (0 votes)
20 views

Chapter 3-Basic Elements of Computer Program

notess

Uploaded by

elnini8412
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Chapter 3-Basic Elements of Computer Program

notess

Uploaded by

elnini8412
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

CHAPTER 3:

BASIC ELEMENTS OF COMPUTER


PROGRAM

Prepared for:
CSC 402 – Programming 1

© Najwa Abd Ghafar – UiTM Johor


© Rose Hafsah Ab Rauf – UiTM Shah Alam
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

OBJECTIVES OF THIS CHAPTER

In this chapter, you will:


 Understand basic program components
 Define and use the identifier, variable, constant and statement
 Understand the standard data type (int, float, double, char, char[ ], const)
 Use the input and output statement
 Understand mathematical predefined function (sqrt(), abs(), pow() etc.)
 Use the function of cin.getline(), strcpy()
 Use the arithmetic operator (+, -, *, /, %)
 Understand the assignment statement (=)
 Write simple programs
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

INTRODUCTION

What is a Computer
Program?
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

COMPUTER PROGRAM

What is a Computer Program?


 Consists of a set of instructions that tells a computer what to
do
Get a glass

Put water
INSTRUCTION SET
Add a lemon

Add sugar

Taste it
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

A C++ PROGRAM

When you execute this program, it will print out the


sentence “Welcome to C+ Programming!!” on the
screen
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

THE BASICS OF A C++ PROGRAM


Function (Subprogram):
 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 (Predefined Function)

Every C++ program


has a function called
main
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

THE BASICS OF A C++ PROGRAM

Syntax Rules:
 Are 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

Semantic Rules:
 Are rules that determine the meaning of the instructions

2 + 3 * 5 and (2 + 3) * 5 give different meaning


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

COMMENTS

Comments:
 Are meant only for the readers, not for the compiler
 The compiler will ignore comments placed inside the program

Single line comments:


Begin with //

Multiple line comments:


Enclosed between
/* and */
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

SPECIAL SYMBOLS
Token:
 Is the smallest individual unit of a program written in any language
 C++ tokens include:
 Special symbols
 Word Symbols
 Identifiers

Examples of special symbols:


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

WORD SYMBOLS

Reserved Words (Keywords):


 Are word symbols
 Cannot be used for anything other than their intended use
 Cannot be refined within any program

Examples of reserved words:


 int
 float
 double
 char
 const
 void
 return
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

IDENTIFIERS
Identifiers:
 Are names of things that appear in a program
 This includes:
 Variables
 Constants
 Functions
 Can either be:
 Predefined identifiers:
• cout
• cin
 Identifiers defined by users
 Consists of letters, digits and underscore character ( _ )
 Must only begin with letter or underscore ( _ )
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

IDENTIFIERS

 Examples of legal identifiers:


salary
total_sum
payRate
counter1

 Examples of illegal identifiers:


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

VARIABLE
Variable:
 Is an identifier that refers to memory location, which can hold values
 However, it can only store ONE value at a time

Variable Declaration:
 Each variable must be declared before they can be used in the
program

dataType variableName;

For example: int total;


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

DATA TYPES

Data Types:
 Are used on identifiers that store data
 It specify the type of data the identifiers can hold
 This include:
 Integer
 Floating-point
 Boolean
 Single character
 String of characters
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

DATA TYPES

Integers:
 Are whole numbers that can either be negative, positive or zero
 Cannot use comma ( , ) within an integer
 For example:

-6728 -10 0 78 +763

int

Eg: int number = 100;


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

DATA TYPES

Floating-points:
 Are decimal numbers
 For example:

75.924 0.18 0.0000453 -1.432 7800.0

float Maximum number of decimal places is 6 or 7


Eg: float number = 10.5;

double Maximum number of decimal places is 15


Eg: double number = 10.184739209;
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

DATA TYPES

Boolean (Logical Values):


 Only has two values:
 true
 false
 It is used to manipulate logical expressions

bool

Eg: bool isAvailable = true;


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

DATA TYPES

Single character:
 Represents only one character, which include:
 Letters
 Digits
 Special symbols
 Each character is enclosed using single quotation marks ‘ ’
 For example:

‘A’ ‘a’ ‘0’ ‘+’ ‘&’ ‘ ’

char
Eg: char grade = ‘A’;
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

DATA TYPES
String of 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
 For example:
“Hello” “hard work is the key to success!!”

char [ ]

Eg: char grade[10] = “Excellent”;


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Determine whether the followings are valid C++ identifiers:

a) myFirstProgram
b) MIX-UP
c) C++Program2
d) quiz7
e) _part_2
f) full name
g) total_fees
h) 3rdNumber
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Are the identifiers firstName and FirstName the same?


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Give the most appropriate data type for the following values:

a) 23
b) ‘C’
c) 18.52
d) true
e) 2.452679753
f) “Michael Jackson”
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

WHITESPACES

Whitespaces:
 Are used to separate special symbols, reserved symbols and
identifiers
 It makes the program readable
 This include:
 Blanks
 Tabs
 Newline characters
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Declare the following variables:

a) age
b) grade
c) average
d) sum
e) address
f) totalCost
© Najwa Abd Ghafar – UiTM Johor

VARIABLE
©Rose Hafsah Ab Rauf – UiTM Shah Alam

Variable Initialization:
 Variables can be initialized after it was declared
 This is done by giving the variable a value, either by:
1. Assignment statement
variableName = expression; int age = 10;

2. Input from user


cin >> variableName; int age;
cin >> age

 This value placed inside must match the data type of variable
 This value will represent the first value that is placed inside the
variable
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

CONSTANTS

Constants:
 Are values that are fixed
 The content inside it will not change throughout the program execution

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


© Najwa Abd Ghafar – UiTM Johor

ASSIGNMENT STATEMENT
©Rose Hafsah Ab Rauf – UiTM Shah Alam

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

variableName = expression;

For example: num = 5;


© Najwa Abd Ghafar – UiTM Johor

SAVING VALUES IN VARIABLES


©Rose Hafsah Ab Rauf – UiTM Shah Alam

Suppose that num1, num2 and num3 are int variables and
the following statements are executed in sequence:

1. num1 = 18
2. num1 = num1 + 27
3. num2 = num1
4. num3 = num2 / 5
5. num3 = num3 / 3

What are the values of variables num1, num2 and num3?


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

PROMPT LINES

Prompt Lines:
 Will inform the user what to do when interacting with the program
 Always include prompt lines when getting input from user

cout << “Please enter your age”;


cin >> age;
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

INPUT (READ) STATEMENT


Input statement:
 Is used to read data entered by the user
 The value entered will be stored inside a variable

cin >> variableName;

For example: cin >> age;

cin >> variableName1 >> variableName2;


More than one
value read at
For example: cin >> gender >> age; a time
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

char[ ] DATA TYPE


The data type string:
 Is a programmer-defined data type
 To use it, you need to use a preprocessor directives

#include <cstring>
String input:
 Is a sequence of zero or more character and is enclosed in a double
quotation marks “ ”

cin.getline(variableName, size);

• cin function:
char name[30]; Will only input one word
For example: cin >> name; OR • cin.getline function:
cin.getline(name, 30); Will input more than one word
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

char[ ] DATA TYPE


Storing Strings:
 To store a string into a variable, the assignment statement (=) cannot be
used, except for initialization
For example: 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
 It will copy a string, y into a variable of type string, x

strcpy(x, y);

For example: char name[30] = “Michael Jackson”;


......
strcpy(name, “James Bond”); RIGHT
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

OUTPUT STATEMENT

Output statement:
 Is used to display messages or output data

cout << expression;

For example: cout << “Welcome to UiTM”; Output message

cout << name; Output value of variable

cout << “Welcome to UiTM “ << name; Output message


and
value of variable
at the same time
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

endl Manipulator

endl Manipulator:
 Causes the insertion point to move to the beginning of the next line

cout << expression << endl;


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

ESCAPE SEQUENCES

Escape Sequences:
 Allows you to control how your output looks
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

STRUCTURE OF A C++ PROGRAM

WHAT SHOULD BE
INSIDE A C++ PROGRAM?
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

PREPROCESSOR DIRECTIVES

Preprocessor Directives:
 Are commands given to the preprocessor to allow us to use predefined
functions contained inside a header file

#include <headerFileName>

For example: #include <iostream>

<iostream>:
 Allow us to use input and output functions
 cin
 cout
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

namespace

 cin and cout are declared in the header file iostream,


but within std namespace

using namespace std; Without this, cin and cout


will be in the form of:
 std::cin
 std::cout

 To use cin and cout in a program, use the following two statements:

#include <iostream>
using namespace std;
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

SEMICOLONS, BRACKETS AND COMMAS

Semicolons:
 Every statement inside a C++ program will end with a semicolon ;

Braces: int main


{
 Are used to enclose the body of a function
........
}

Commas:
 Are used to separate items in a list float average, area, sum;
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

DEBUGGING

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
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

What would be displayed on the screen for the program


below:
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Write a simple program that displays:

Hello World!!
I am excited to learn C++ programming.
QUICK EXERCISE
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

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.
QUICK EXERCISE
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

Write a program by translating the


flowchart given as shown here. This
program will prompts the user for their
full name, age and gender (M/F).

Note: The data “Wonderful Programmer” will


replace the name entered by the user.
© Najwa Abd Ghafar – UiTM Johor

QUICK EXERCISE ©Rose Hafsah Ab Rauf – UiTM Shah Alam

Write a program that asks the user's full name, student ID,
gender (male/female) and the amount of fees paid for one
semester in UiTM. Then, display a welcoming message to the
user and display the details that were entered by the user.
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

ARITHMETIC OPERATORS

Arithmetic Operators:
 Are used to manipulate integral and floating-data types
 This include:
 + addition
 - subtraction Can be used with:
• Integral data type
 * multiplication
• Floating-point data type
 / division
(gives quotient in ordinary division)
 % modulus operator Can be used with:
(gives remainder in ordinary division) • Integral data type
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

ARITHMETIC EXPRESSION

Arithmetic Expression:
 Is constructed by using:
 Arithmetic operators
 Operands (are the numbers)

Unary Operator:
 Operator that has only one operand
 This include: +, -

Binary Operator:
 Operator that has two operands
 This include: +, -, *, /, %
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

ORDER OF PRECEDENCE

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 precedence

Same level of precedence

Are evaluated from left to right


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

EXAMPLE

Evaluate the following expressions:

1. X=8/2*3+4*5%3
2. X = 8 / 2 * (3 + 4) * 5 % 3
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

EXAMPLE

Evaluate the following expressions:

1. X=8/2*3+4*5%3
2. X = 8 / 2 * (3 + 4) * 5 % 3
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

EXPRESSIONS

Integral Expression:
 Is an expression when all of the operands (numbers) involved are integers
 For example:
2+3*5
 Will give out an integral result

Floating-point Expression:
 Is an expression when all of the operands (numbers) involved are floating-
point
 For example:
12.8 * 17.5 – 34.50
 Will give out a floating-point result
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

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
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Evaluate the following expressions:


a. x = 1 – 3 / 2 * 3
b. x = 3 * 3.142 + 5 / 3
c. x = 15.6 / 2 + 5
d. x = 4 * 3 % 5 + 3.14
e. x = 4 * 3 + 7 / 5 – 25.5
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

What is the output of the following program?


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK TIP!!
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

INCREMENT AND DECREMENT OPERATORS


Increment and Decrement Operators:
 Are usually used to keep track of how many times certain things have
happened
1. Increment operator:
Increase the value of variable by 1
For example:
variableName ++; count++;
This statement is equivalent to count = count +1;
2. Decrement operator:
Decrease the value of variable by 1
For example:
variableName --;
count--;

which is equivalent to count = count – 1;


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK QUESTION

WHY DO YOU NEED


PREPROCESSOR DIRECTIVES
INSIDE A PROGRAM?
PREPROCESSOR DIRECTIVES
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

<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
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK TIP!!
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE
PREPROCESSOR DIRECTIVES
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

<cstring>:
 Allow us to use predefined functions on cstring
 strcpy (x, y)
Will copy a string, y into a variable of type string, x

Output:

 strlen (x)
Will return the length of the string in x (excluding the null terminator)
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

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
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

EXAMPLE
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK TIP!!
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

CONTROL STRUCTURES

 A computer program can be executed:


 In sequence
 By Selection (Branch): Making a choice
 By Repetition (Iterative): Looping
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Write a program that will calculate the average


of 3 numbers
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK TIP!!!
© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Write a program for the problem below:

Calculate the total wages a student earns working a part time job, given their
hourly rate and hours worked in a month.

NOTE: Display the total wages in 2 decimal places.

HINT: Use setprecision()


© Najwa Abd Ghafar – UiTM Johor
©Rose Hafsah Ab Rauf – UiTM Shah Alam

QUICK EXERCISE

Write a program for the problem below:

NOTE: Use pow()

You might also like