You are on page 1of 69

Components of a

Programming Language
Topic 2
Contents
 Creating a C++ program
 Program Style and Form
 Documentation
 Basic Operations
 Program Elements
 Storage
 Input and Output
 Arithmetic Operations

2
Creating a C++ Program
 C++ program has two parts:
 Preprocessor Directives
 The Program
 Preprocessor directives and program statements
constitute C++ source code
 Source code must be saved in a file with the file extension
.cpp
 Compiler generates the object code and saved in a file
with file extension .obj
 Executable code is produced and saved in a file with the
file extension .exe
3
Creating a C++ Program
 Preprocessor Directives
 Many functions and symbols needed to run a C++ program
are provided as collection of libraries.
 Every library has a name and is referred to by a header file
 Preprocessor directives are commands supplied to the
preprocessor
 All preprocessor commands begin with #
 No semicolon at the end of these commands
 Syntax to include a header file
#include <headerFileName>
 Causes the preprocessor to include the header file
iostream in the program
 The syntax is:
#include <iostream>
4
Creating a C++ Program
 Header Files and Namespace std
 ANSI C++ removes the extension .h in the header
files
 The descriptions of the functions needed to perform
I/O are contained in iostream
 cin and cout are declared in the header file
iostream, but within a namespace named std
 To use cin and cout in a program, use the following
two statements:
#include <iostream>
using namespace std;
5
Creating a C++ Program
 The program part
 Every C++ program has a function main
 Basic parts of function main are:
 The heading
 The body of the function
 The heading part has the following form:
typeOfFunction main(argument list)
 Example:

6
Creating a C++ Program
 Variables can Declaration statements have the following
syntax:
int a, b, c;
double x, y;
 be declared anywhere in the program but they must be
declared before they can be used.
 Executable statements have three forms:
 Assignment statement
a = 4;
 Input statement
cin >> b;
 Output statement
cout << a << " " << b << endl;
7
Program Style and Form
 Use of Blanks
 One or more blanks separate input numbers
 Blanks are also used to separate reserved words and identifiers
from each other and other symbols
 Blanks between identifiers in the second statement are
meaningless:
int a,b,c;
int a, b, c;
 In the statement: inta,b,c;
 no blank between the t and a changes the reserved
word int and the identifier a into a new identifier,
inta.
8
Program Style and Form
 Commas separate items in a list
 All C++ statements end with a semicolon
 Semicolon is also called a statement terminator
 { and } are not C++ statements
 Consider two ways of declaring variables:
 Method 1
int feet, inch;
double x, y;
 Method 2
int a,b;double x,y;
 Both are correct, however, the second is hard to read.

9
Documentation
 Comments can be used to document code Single line
comments begin with // anywhere in the line
//This program has two functions
 Multiple line comments are enclosed between /* and */
 Name identifiers with meaningful names
 Run-together-words can be handled either by using CAPS
for the beginning of each new word or an underscore
before the new word
numOfStudent
size_item

10
Basic Operations
 6 types of operations in programming:
1. Receive input (e.g cin)
2. Produce output (e.g cout)
3. Assign value into storage (e.g equation sign is used
to assign value to variable, a = 2, weight = 5)
4. Perform arithmetic and logic operation (e.g
symbols like + - * / and || && !=)
5. Make selection (e.g if, if-else, switch)
6. Repeating a set of actions (e.g for, while, do-while)

11
Program Elements
 A C++ program is a collection of one or more subprograms,
called functions.
 Every C++ program has a function called main
 Generally a computer program has the following elements:
1. Input section
2. Storage allocation
 Constants
 Variables
 Data Structures
 Files
3. Processing using arithmetic or logic operation and control
with either sequential, selection or and repetition structure.
4. Output Section

12
Program Elements
int number1, number2, total;
Computer program
cin >> number1 >> number2;

total = number1 + number2;

cout << total << endl

Arithmetic Logic

total = number1 + number2;


Input Output
Processing
cin >> number1 >> number2; cout << total << endl

constant

Storage variable

int number1, number2, total;

13
Reserved words or Keywords
 Reserved words
 Symbols which are defined to have a unique meaning within a C++
program.
 These symbols (reserved words) must not be used for any other
purposes.
 Examples:
int float double case char
void return using sizeof true
false break while not long
void switch catch continue for
 Special symbols
Examples :
+ - * / ; , . ? <= != == >=

14
Storage
 One of the essential resource of a program
 A location in computer memory that is allocated to the
program
 Used to hold value of specific data type
 Categories:
 Constants
 Variables
 Data Structure
 Files
 Data Types
 Integer number
 Floating point number
 Character

15
Storage (cont.) - Identifier
 Identifier is the name given to specific storage
 Identifiers consist of letters, digits, and the underscore
character ( _ )
 Must begin with a letter or underscore
 C++ is case sensitive
 Some predefined identifiers are cout and cin
 Unlike reserved words, predefined identifiers may be redefined,
but it is not a good idea
int number;
Data type Identifier

16
Storage (cont.) - Identifier
 Examples of valid or legal identifiers
number1
averageScore
latest_CGPA

 Examples of invalid or illegal identifiers

17
Storage (cont.) - Constant
 Constant
 To hold fixed value that cannot be altered during program
execution.
 Examples:
PI value  3.1416
Number of days per week  7
 Constant declaration:
const keyword is used to declare a constant and it must be
initialized.
<data type> const <identifier> = value;
 Example:
float const PI = 3.1416;

18
Storage (cont.) - Variable
 Variables
 To hold value that might be altered during program execution.
 Hold value on temporary basis
 Examples:
 score
 Temperature
 speedOfVehicle
 Length
 Variable declaration:
<data type> <identifier> [= initial value];
 Example:
int number;
float score1, score2;
int score;
float number;
int count = 0;

19
Storage (cont.) – Data Structure
 Data Structure
 An array or a pointer
 An array is a contagious memory locations that hold
more than one values of the same type.
 Hold value on temporary basis
 Examples:
 Name
 A set of students’ score
char name[20];
int score[20];

20
Storage (cont.) – Data Type
 Data Type : a set of values together with a set of
operations is called a data type

 C++ data can be classified into three categories:


 Simple data type (focus on this type)

 Structured data type

 Pointers

21
Storage (cont.) – Data Type
 Three categories of simple data types
 Integral: integers (numbers without a decimal)
 Floating-point: decimal numbers
 Enumeration type: user-defined data type

22
int Data Type bool Data Type char Data Type
 Examples:  bool type  The smallest integral data
-6728 type
 Has two values,
0 true and false  Used for characters:
78 letters, digits, and special
 Manipulate logical symbols
 Positive integers do not (Boolean)
have to have a + sign in expressions  Each character is
front of them enclosed in single quotes
 true and false are
 No commas are used  Some of the values
called logical values
within an integer belonging to char data
 Commas are used for  bool, true, and type are: 'A', 'a', '0',
separating items in a list false are reserved '*', '+', '$', '&'
words  A blank space is a
character and is written
' ', with a space left
between the single quotes
Storage (cont.) – Data Type
 Floating-Point Data Types
 C++ uses scientific notation to represent real numbers
(floating-point notation)
float Data Type double Data Type
 float: represents any real  double: represents any real
number number
 Range: -3.4E+38 to  Range: -1.7E+308 to 1.7E+308
3.4E+38  Memory allocated for double
 Memory allocated for the type is 8 bytes
float type is 4 bytes  On most newer compilers, data
 Maximum number of types double and long double
significant digits (decimal are same
places) for float values is 6  Maximum number of significant
or 7 digits for double is 15
 Float values are called single  Double values are called double
precision precision
 Precision: maximum number of
significant digits
Storage (cont.) – Data Type
 Basic Data Types C++ Data Types
 Integer (90, 0, -78) int or long
 Floating point (4.5,1.0,-0.67) float or double
 Character (‘A’, ‘a’, ‘*’, ‘1’) char

 Examples
int number;
int score;
long population;
float temperature;
double accountBalance;
char gender;

26
Input and Output
 Input Statement
 To received input from keyboard or read input from a
file.
 Data must be loaded into main memory before it can be
manipulated
 Storing data in memory is a two-step process:
 Instruct the computer to allocate memory
 Include statements to put data into allocated memory
 Using cin keyword and input stream (extraction) operator
(>>).
 Syntax:
cin >> <variable>;

 Example
cin >> number;
cin >> number1 >> number2;
cin >> weight;
cin >> height;

27
Input and Output (cont.)

 Example of a good input statement:


Prompt to the user to enter a value

cout << “Enter a score : ”;


cin >> score;

Read a value from the user

28
Input and Output (cont.)
 Output Statement
 To display output on screen or to write output into file.
 Using cout keyword and output stream (insertion) operator
(<<).
 Syntax:
cout << <string|constant|variable|expression>;

 Statements Output
cout << “Hello World”; Hello World
cout << 80; 80
cout << area; content of area
cout << 8 + 4; 12

29
Input and Output (cont.)
 Output Statement
 What is the output of the following statements?
 Statements Output
cout << “Total is ” << 8 + 2; ?
cout << “8 + 2 = ” << 8 + 2; ?

30
Input and Output (cont.)

 End of line
 endl keyword causes cursor to move to beginning the the
next line.
 New Line character (‘\n’) forces the cursor to be
positioned at the beginning of the new line.
 Examples:
 Code fragment Output
cout << 14; 1416
cout << 16;
cout << 14 << endl; 14
cout << 16 << endl; 16

cout << 14 << ‘\n’; 14


cout << 16 << ‘\n’; 16

31
Input and Output (cont.)

32
Arithmetic Operations
 FIVE basic operations:
 Addition (+)  Sum of two numbers
 Subtraction (-)  Different of two numbers
 Multiplication (*)  Product of two numbers
 Division (/)  Quotient of two numbers
 Modulo (%)  Remainder of division operation

33
Arithmetic Operations (cont.)
 Examples
int number1, number2;
int sum, different, product, quotient, reminder;
number1 = 8;
number2 = 4;

sum = number1 + number2;


different = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;
remainder = number1 % number2;

 Invalid Statement!
number1 + number2 = total
34
Arithmetic Operations (cont.)
 Integer Division
 IF two integers are divided, the result will be an integer number. Any
fraction will be truncated.
int / int  int
Example:

int a = 5, b = 2;
float c;
c = a / b; //the new value of c is 2

cout << a / b; //2 will be displayed

35
Arithmetic Operations (cont.)
 Data type conversion
To avoid the effect of integer division the data type must be
converted to float.
Example:

int a = 5, b = 2,
float c;
c = float(a) / b; //the new value of c is 2.5
c = a / float(b); //the new value of c is 2.5

//2.5 will be displayed


cout << float(a) / b;
cout << a / float(b);

c = float(a / b); //2.0 will be stored in c


cout << float (a / b); //2.0 will be displayed

36
Arithmetic Operations (cont.)

 Type Conversion (Casting)


- store a value into a variable of a different type
- example : if you want to store a double value into an int variable
- expressed using static_cast keyword as follows :

static_cast<data_type>(expression)

- example :
int n = static_cast<int>(x + 0.5)

37
Arithmetic Operations (cont.)

38
Example :
#include <iostream.h>
//program to calculate area of a circle PI 3.1416

main()
{ radius ?
//variable and constant allocation
float const PI = 3.1416; area ?
float radius, area;

//input section
cout << “Enter a radius : ”;
cin >> radius;

area = PI * radius * radius; //processing

//output section
cout << “Area of the circle is ” << area << endl;

return 0;
}//end main()

39
Example :
#include <iostream.h>
//program to calculate area of a circle PI 3.1416

main()
{ radius ?
//variable and constant allocation
float const PI = 3.1416; area ?
float radius, area;

//input section
cout << “Enter a radius : ”; Enter a radius : 8
cin >> radius;

area = PI * radius * radius; //processing

//output section
cout << “Area of the circle is ” << area << endl;

return 0;
}//end main()

40
Examples
#include <iostream.h>
//program to calculate area of a circle PI 3.1416
main()
{ radius 8
//variable and constant allocation
float const PI = 3.1416;
float radius, area; area 201.0624

//input section
cout << “Enter a radius : ”;
cin >> radius;

area = PI * radius * radius; //processing

//output section
cout << “Area of the circle is ” << area <<
endl;
Enter a radius : 8
return 0; Area of the circle is 201.0624
}//end main()

41
Exercise 1
 Declare the suitable storage (data type and variable) to
hold the following data:
1. Number of days worked in a week
2. Student’s CGPA
3. Name of a person
4. Speed of a light
5. Gender
6. Average of scores

42
Exercise 2
 Given the following declaration:

int a, b, c, v1, v2;


a = 8;
c = b = 3;
c = c – 1;
v1 = a / b;
v2 = a / c;

What is the final content of a, b, c, v1 and v2?

43
Exercise 3
 Translate the following flow chart into source code:
Begin

Read totalScore

Read count

average = total / count

Display average

End

44
Exercise 4
Write a program that can execute the following :
1. Prompts the user to input two integer numbers
2. Find the sum, subtraction, and average of the
two integers

45
Exercise 5
 Try to write a program : Convert Length
Write a program that takes as input given lengths
expressed in feet and inches. The program should then
convert and out the length in centimeters. Assume that
the given lengths in feet and inches are integers. (One
feet is 12 inches; One inch is equal to 2.54 centimeters)

46
Arithmetic Expressions, Operators
and Assignment Concept

47
Contents
 Assignment Statement
 Operators (Shortcut Operator, Unary Operator)
 Arithmetic Operators
 Order of Precedence
 Mathematical Library Functions
 Formatting Program Output
 String Manipulation

48
Assignment Statement
 Assignment statement is the most basic C++ statement
 Store the value of an expression in a variable
 Use Assignment Operator (=)
 Syntax:

variable = <variable|constant|expression>

 Expression can be :
i. a constant
ii. another variable
iii. an arithmetic expression
iv. a function

49
Assignment Statement (cont.)
 Examples of Assignment Statements:
length = oldLength;
width = 50;
area = length * width;
moreData = true; //a boolean variable

50
Assignment Statement (cont.)
 Exercise 1:
Write a program that takes input of length in feet. The
program should then convert and display the length in
centimeter. Assume that the given lengths in feet is integer.

 Exercise 2:
Write a program that read the radius of a circle. The program
should able to calculate the area, then display the area of the
circle to the user.

51
Assignment Statement (cont.)
 Exercise 1:
Write a program that takes input of length in feet. The
program should then convert and display the length in
centimeter. Assume that the given lengths in feet is integer.
Answer: lengthInCM = lengthInFeet * 30.48;
 Exercise 2:
Write a program that read the radius of a circle. The program
should able to calculate the area, then display the area of the
circle to the user.
Answer: areaCircle = 3.14 * r * r;

52
Assignment Statement (cont.)
Variations of Assignment Operation :
 We can have assignment statement like this :
sum = sum + 10;

 This statement can be written using the following shortcut


assignment operators :

+= -= /= %= *=

 Hence, the equivalent “sum = sum + 10”, would be :

sum += 10;

53
Assignment Statement (cont.)

 Exercises:

Expression Equivalent to
price = price * rate;
count = count + 3
amount /= 2;
price *= rate + 1

54
Assignment Statement (cont.)

 Answers :

Expression Equivalent to
price = price * rate; price *= rate;
count = count + 3 count += 3
amount /= 2; amount = amount / 2;
price *= rate + 1 price = price * (rate + 1)
but not
price = price * rate + 1

55
Assignment Statement (cont.)
 For a variable to increase or decrease by 1, C++ provides
two unary operators :
(++) : increment operator
(--) : decrement operator

Expression Equivalent to
i = i + 1  ++i (prefix increment operator)
If x = 5; and y = ++x;
After the second statement both x and y are 6
 i++ (postfix increment operator)
If x = 5; and y = x++;
After the second statement y is 5 and x is 6
i = i - 1 --i

56
Assignment Statement (cont.)
 Exercises:

Expression Value X Value Y


X = 6; Y = ++X
Y = 10; X = Y++;
X = 5; Y = --X;
Y = 10; X = Y--;

57
Assignment Statement (cont.)
 Answers:

Expression Value X Value Y


X = 6; Y = ++X; 7 7
Y = 10; X = Y++; 10 11
X = 5; Y = --X; 4 4
Y = 10; X = Y--; 10 9

58
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
Arithmetic Operators
 Exercises: Rewrite the following statements in C++
format.
 a. 27
 15  8  15
5
 b. 13  2 16  3 18

3
 c. 12  3  15  5  3
4
Arithmetic Operators
 Exercises: Rewrite the following statements in C++
format.
Answer:
 a. 27
 15  8  15 (27 / 5) + (15 * 8) – 15
5
 b. 13  2 16  3 18 13 + (2 * 16 / 3) – 18

3
 c. 12  3  15  5  3 12 + (3 / 4) – 3 + (15 / 5 * 3)
4
Mathematical Library Functions
 Header file cmath (math.h)
#include <cmath>
 used in the following form :
function_name(argument)

Example :
sqrt(16) //square root of x
fabs(2.3 * 4.6) //absolute value |x|
tan(x) //tangent of x
floor(x) //largest integer <= x

64
Formatting Program Output
 Besides displaying correct results, it is extremely
important for a program to present its output attractively.
 To include manipulators within an output display, must
include the header file using the preprocessor command
as follows :
#include <iomanip>
 Most commonly used manipulators in a cout statement :

65
Formatting Program Output
Manipulator Action
endl Manipulator moves output to the beginning of the next
line
setfill(‘x’) Sets the fill character from its default of a blank space to
the character x
setprecision(n) Outputs decimal numbers with up to n decimal places
showpoint forces output to show the decimal point and trailing
zeros
scientific Use exponential notation on output
left Left justify output
fixed Outputs floating-point numbers in a fixed decimal format
setw Outputs the value of an expression in specific columns

66
Formatting Program Output
Manipulator Examples
endl cout << “Hello world!” << endl;
setfill(‘x’) cout << setfill(‘x’) << setw (10) << 8;
setw
setprecision(n) cout << setprecision(5) << 3.14159;
showpoint cout << showpoint << 30;
noshowpoint
scientific cout << scientific << 3.1416;
left cout << setw(15) << left << 3.1416;
right
fixed cout << fixed << setprecision(5) << 3.14159;

67
String Manipulations
 String input
- header file :
#include <cstring>

- can be declared and initialized as :


string name;
name = “Abdul”;

or to read a string from the keyboard


cout << “What is your name ?”;
cin >> name;

68
String Manipulations
 String function :
string-name.length():
- to know the numbers of character in a string

string-name.substr(m,n):
- to extract substring from a full string

 String concatenation : using symbol ‘+’


- joining two or more strings together to
become one long string.
const string hello = "Hello";
const string message = hello +
",world" +
"!";
69

You might also like