Topic 3 - Basic Elements of A Computer Program
Topic 3 - Basic Elements of A Computer Program
PROGRAMMING 1
LECTURE: 03 – BASIC ELEMENTS OF A COMPUTER PROGRAM
2
Learning Objectives:
After completing this chapter, you will be able to:
• describe the basic components of a C++ program, including
functions, special symbols, and identifiers
• use simple data types and examine the string data type
• describe how to input data into memory using input statements
• describe how to use arithmetic operators
• use of increment and decrement operators
• output results using output statements
• properly structure a program, including using comments to
document a program
• use built-in function
• write a C++ program
3
Introduction
• Computer program: sequence of statements
designed to accomplish some task
• Programming: planning/creating a program
• Syntax: rules that specify which statements
(instructions) are legal
• Programming language: a set of rules, symbols,
and special words
• Semantic rule: meaning of the instruction
4
C++ Programs
Symbols
• Special symbols
− Include mathematical symbols and
punctuation marks
− Blank also special symbol
+ ?
- ,
* <=
/ !=
. ==
; >=
7
• Word symbols
− Another type of token
− Reserved words or keywords
− Reserved words: always lowercase, each considered
to be single symbol with special meaning
− Example:
• int
• float
• double
• char
• void
• return
8
A Sample Program
data type
variables
void main()
{
int yearBorn, age; Output Statement
A Sample Program
#include <iostream.h>
Preprocessor directives
void main()
{
int yearBorn; Main function
int curYear;
int age; Variables declaration
curYear = 2004;
cout << "Please enter the year you were born: ";
cin >> yearBorn;
Statements
age = curYear - yearBorn;
Take note of the semicolon
cout << "Your age is " << age; at the end of each variable
cout << endl;
} declarations and statement
(instructions)
10
Identifier
• Another type of token
• Identifiers: used as names for variables, constants,
and functions
• Identifiers: consist of letters, digits, and underscore
character (_)
• Identifiers: must begin with letter or underscore
(best not to use underscore for portability)
• C++: case sensitive
• Some predefined identifiers (cout and cin)
• Unlike reserved words, predefined identifiers may
be redefined--but generally not good idea
11
Identifier
• Although identifiers can be formed by freely
combining the letters, digits and underscores,
common sense tells us that we should give
them suggestive names, that is, names that
reflect the data items that they are going to
store. Identifiers can be of any length
although in practice they seldom exceed 25
characters.
Identifier
Here are some valid and invalid identifiers.
Valid Invalid
x “x”
sumx2 2sumx
hourly_rate hourly-rate
_name name@
GROSS_PAY GROSS PAY
Identifier
bool type
– Has two values, true and false
– Manipulate logical (Boolean) expressions
true and false are called logical values
bool, true, and false are reserved words
char Data Type
• The smallest integral data type
• Used for characters: letters, digits, and
special symbols
• Each character is enclosed in single quotes
• Some of the values belonging to char data
type are: 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character and is written ' ',
with a space left between the single quotes
Floating-Point Data Types
C++ uses scientific notation to represent real numbers
(floating-point notation)
Floating-Point Data Types (cont.)
• float: represents any real number
− Range: -3.4E+38 to 3.4E+38
• Memory allocated for the float type is 4 bytes
• double: represents any real number
− Range: -1.7E+308 to 1.7E+308
• Memory allocated for double type is 8 bytes
• On most newer compilers, data types double
and long double are same
string Type
• Programmer-defined data type (not included in earlier
versions of C++)
• To use string data type, string library must be included
(include file)
• Sequence of zero or more characters
• Enclosed in double quotation marks (e.g., "r")
• null string: string with no characters
string Type (cont.)
• Each character in string has a relative position
• Position of first character is 0 (zero), 2nd character is
1, etc.
• Length of string is total number of characters (e.g., "C
++" length = 3)
Arithmetic Operators
• C++ Operators
+ addition
- subtraction
* multiplication
/ division
% remainder (mod operator)
• +, -, *, and / can be used with integral and floating-
point data types
• Unary operator - has only one operand
• Binary Operator - has two operands
Order of Precedence
• All operations inside of () are evaluated first
• *, /, and % are at the same level of
precedence and are evaluated next
• + and – have the same level of precedence
and are evaluated last
• When operators are on the same level
− Performed from left to right
Expressions
• If all operands are integers
− Expression is called an integral expression
• If all operands are floating-point
− Expression is called a floating-point expression
• An integral expression yields integral result
• A floating-point expression yields a floating-point result
• Mixed expression:
− Has operands of different data types
− Contains integers and floating-point
− 5.4 * 2 – 13.6 + 18 / 2
Input, Memory, and Data
Using Input:
integer int 16
character char 8
• Example:
const double PI = 3.14;
Input, Memory, and Data (Cont.)
Storing Data into Variables (declaring and initializing variables):
• Variables can be declared anywhere in program
• Must be declared before can be used
• In C++, = called assignment operator
• Data stored in memory (using name of variable or constant), either using assignment
statement or input statement
• C++ does not automatically initialize variables
• When variable declared, only memory is allocated
• When variable declared with no value, memory cell may contain value from setting of
bits from previous use
• Expression on right side is evaluated, then its value is assigned to variable (a
memory location) on left side
• Variable initialization: variable given a value at declaration (good programming
principle)
• Remember: assignment (=) is NOT equality (==)
Input, Memory, and Data (Cont.)
Assignment Statement Examples:
variable = expression;
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus division
++ Increment by 1
-- Decrement by 1
Arithmetic operators
Operator Action Example (no1 = 7, no2=2) Result
+ Addition no1 + no2 9
++ Increment by 1 no1- - 6
-- Decrement by 1 no2 + + 3
Arithmetic Operators
• Caution on divide rules:
–5/2=2
– 5.0 / 2 = 2.5
– 5 / 2.0 = 2.5
– 5.0 / 2.0 = 2.5
– double answer = 5 / 2; // 2
– int answer = 5 / 2; // 2
– int answer = 5.0 / 2 ; // 2
Increment & Decrement Operators
• Increment operator: increment variable by 1
• Decrement operator: decrement variable by 1
• Pre-increment: ++variable
• Post-increment: variable++
• Pre-decrement: --variable
• Post-decrement: variable--
Example
• Caution on increment/decrement
operators:
– int no1 = 5, no2 = 5;
– no1++;
– ++no2;
– cout<<no1<<" "<<no2<<endl; // 6 6
– cout<<(++no1)<<endl; // 6
– cout<<(no2++)<<endl; // 5
More on Assignment Statements:
Compound assignment statements: shorthand method of assignment
Compound assignment defined: op is binary arithmetic operator, op=
Simple assignment statement variable = variable op (another variable or
expression);
Rewritten as compound assignment: variable op= (another variable or
expression);
Example:
+=, -=, *=, /=, and %=
x *= y; //equivalent to x = x * y;
Relational and Logical Operators
The six relational operators in C++ are shown next.
Operator Meaning
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal
!= not equal
Relational and Logical Operators
• The results of evaluation of a relational
operation is either true (represented by
1) or false (represented by 0).
• For example, if a = 7 and b = 5, then
a < b yields 0 and a != b yields 1.
Relational and Logical Operators
The three logical operators in C++ are shown below.
Operator Meaning
&& AND
|| OR
! NOT
Relational and Logical Operators
The result of the logical operations on a and b are summarized in
the following table.
a b a || b a && b !a
0 0 0 0 1
0 1 1 0 1
1 0 1 0 0
1 1 1 1 0
Hierarchy of operations
• There are times when you combine several operators in
one statement. For example, total = a + b / c.
The statement codes both the addition and division
operators. So, the question which operation will be
performed first arises; is it addition first, division later or
what?
• In this situation, you need to know the hierarchy of
operator precedence.
• The hierarchy of operator precedence reflects the order
of evaluation that will take place.
Hierarchy of operations
The hierarchy of operator precedence from highest to lowest is
summarized below.
Operator Category Operator Associativity
Parentheses () Left to right
Unary ++ - - - + Left to right
49
Output statement (Cont.)
For example:
51
Built-in functions
Built-in functions are also known as library functions.
We need not to declare and define these functions
as they are already written in the C++ libraries such
as iostream, cmath etc. We can directly call them
when we need.
Commonly used header files:
<iostream> //input/output
<cmath> //math functions
<string> //string functions
<iomanip> //formatting manipulations for input/output
Formatted Output
• setprecision manipulator(to control the output of floating-point numbers)
– setprecision(n)
• fixed manipulator(to output floating-point numbers in a fixed decimal format)
– cout<<fixed;
• showpoint manipulator(to force the output to show the decimal point and
trailing zeros)
– cout<<fixed<<showpoint;
• setw manipulator(to output the value of an expression in a specific number
of columns)
– setw(n)
– cout<<setw(5)<<x<<endl;
• setfill manipulator(to fill the unused columns with a character other than a
space)
– cout<<setfill(‘*’); 54
Formatted Output
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{ double x, y, z;
x = 15.674;
y = 235.73;
z = 9525.9864;
cout<< fixed << showpoint;
cout<<setprecision(2)<<x<<"\n"<<y<<"\n"<<z<<endl;
cout<<setprecision(5)<<x<<"\n"<<y<<"\n"<<z<<endl;
cout<<"123456789012345678901234567890"<<endl;
cout<<setw(5)<< x <<endl;
cout<<setw(10)<< y <<endl;
cout<<setw(15)<< z <<endl;
cout<<setfill('*')<<x<<endl;
cout<<setw(10)<<setfill('*')<<y<<endl;
cout<<setw(15)<<setfill('*')<<z<<endl;
55
}
Formatted Output
56
Formatted Output
• Be comfortable with the arithmetic operations
• +-*/%
• Remember division depends on the data type.
• cout << 3.0/4.0; //OUTPUTS 0.75
• cout << 3.0/4; //OUTPUTS 0.75
• cout << 3/4; //OUTPUTS 0
• The mod operator % gives remainder after integer
• division. Useful for detecting odd/even numbers.
• cout << 19%7; //OUTPUTS 5
• cout << 3%4; //OUTPUTS 3
• More complicated operations (sin,cos,pow,sqrt)
• require to #include <cmath> library.
57
Formatted Output
• Input/Output
• Watch the direction of your I/O push & pulls.
• Output push: cout << x;
• Input pull: cin >> x;
• Remember the basic escape characters.
• \n new line \t tab
• \\ backslash \a alert beep
• \" double quote \' single quote
• Remember the computer won't show spaces unless
• we tell it to.
• cout << 2 << 3; //OUTPUTS 23
• cout << 2 << " " << 3; //OUTPUTS 2 3
58
Formatted Output
• We can line items up in columns with setw(w).
• Remember it only affects the next push.
• cout<<setw(10) << "Hello" << "Gandalf";
• We can specify the number of decimal places with
setprecision(n). Affects all couts that follow.
• Remember it won't print trailing zeros unless we use the command
fixed first.
• cout << setprecision(2) << 3.12 << 3.1 << 3.0 << 3;
• To use these functions, we need to #include the library
<iomanip>
59
Formatted Output
• The String Class
• You should be comfortable with the basic member functions of
the string class: length, substr, erase, insert, find.
• We concatenate (add on) pieces to the string with the plus sign
+: string s = "Hello" + s2;
• To use any of these functions, be sure to #include <string>
• Remember strings are indexed from position 0 and end at
position length-1.
• If we want to read in more than one word, use
getline(cin, my_string) rather than cin>>my_string.
60
Formatted Output
61
Formatted Output
1 char szString[255];
2 cin.getline(szString, 255);
3 cout << "You entered: " << szString << endl;
62
Formatted Output
63
Formatted Output
It is better to use strncpy(), which takes a length parameter to prevent buffer overflow:
Other useful functions:
strcat() — Appends one string to another (dangerous)
strncat() — Appends one string to another (with buffer length check)
strcmp() — Compare two strings (returns 0 if equal)
strncmp() — Compare two strings up to a specific number of characters (returns 0 if equal)
strlen() — Returns the length of a string (excluding the null terminator)
64
Exercises:
65
Exercises
66
Exercises
a. 3 / 2 + 5.5
b. 15.6 / 2 + 5
c. 4 + 5 / 2.0
d. 4 * 3 + 7 / 5 – 25.5
67
THANK YOU…