1. Basic elements of a C++ program.
1.1. Simple C++ program
1.2. Data types
1.3. Arithmetic expression
1.4. Additional operators
1.1. Simple C++ program
An example of a simple program is as below:
Figure 1.1 My program_______________________________________
1 // Writing my age
2
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int age; // input - age
9
10 // Get data on age
11 cout << "Enter your age => ";
12 cin >> age;
13
14 //Display message
15 cout << "I am " << age << " years old" << endl;
16 return 0;
17 }
Enter your age => 20
I am 20 years old
comment line
1st line is a comment line which describe the purpose of the
program.
Begin with a double slash (//)
Ignored by compiler, only used to assist the reader of the program
#include <iostream>
preprocessor directive
begin with symbol #
<iostream> is called library – header file name enclosed in bracket
library is a collection of useful functions, operators and symbols
that may be accessed by a program
<iostream> library defines the names cin and cout the operators >>
and <<
using namespace std;
to give instruction to the compiler to use function in standard
library.
allows the program to access all the names that are grouped as
the collective named std.
statement
one or more lines of code ends with a semicolon ;
int main ()
main function of the program
consist of one or more statement enclosed in curly bracket { }
Names and keyword
Names:
use to define constants and variables
sensitive to upper and lower cases
use underscore for two or more words
can contain digit but cannot begin with digit
Keyword:
several collection of letters cannot be use as names for constants
or variables since they have been reserve for special purposes in
the language as listed in Figure 1.1
Figure 1.1: C++ Keywords (Appendix F Hanly 2002)
cout <<
format: cout << “ ”;
statement enclosed in qoutes (“ ”) display the message on the
screen
an interactive message which the program asking for data from
the user as input data is called a prompt
Insertion operators (<<)
cout refers to the output stream of the associated in the program’s
output device, typically the screen
output stream is an output destination for a continous stream of
characters
the insertion operator (<<) inserts characters in an output stream
cin >>
format: cin >> variable name;
copy the value type by user –variable input
the variable name has to be defined earlier
Extraction operators (>>)
the program can also views the characters typed at the keyboard
as a stream
cin is the name of the input stream associated with the standard
input device, typically the keyboard
the extraction operator (>>) extracts one or more characters from
the input stream for storage as a data value
endl;
terminates a line of output and starts a new one
return 0;
the final line of a program
by returning (0) indicates that the program has ran normally
1.2 Data Types
Sample program:
****************************************************************
// Writing my personal details
#include <iostream>
using namespace std;
int main()
{
string name; // input - name
int age; // input - age
double height; // input - height
char blood; // input - blood type
// Get data on name
cout << "Enter your name => ";
cin >> name;
// Get data on age
cout << "Enter your age => ";
cin >> age;
// Get data on height
cout << "Enter your height => ";
cin >> height;
// Get data on blood type
cout << "Enter your blood type => ";
cin >> blood;
//Display message
cout << "My name is " << name << endl;
cout << "I am " << age << " years old" << endl;
cout << "I am " << height << "m tall" << endl;
cout << "My name blood type is " << blood << endl;
return 0;
}
Numbers
Floating point numbers
Numbers with fractional part/decimal place
Can be written as decimal points, eg.:
0.573 0.9
or with exponents, eg.:
76e+2 13E-3
where “e” or “E” can be read as “times 10 to the power of”.
76e+2 = 76 × 102 = 7600 13E-3 = 13 × 10-3 = 0.0013
3 types of floating point numbers: float, double and long double.
Use to determine the number range.
Table 1.1 Floating point types in C+++
Type Approximate range
float 10-37 .. 1038
double 10-307 .. 10308
long double 10-4931 .. 104932
Integers
Exact numbers without decimal place eg.:
10 -76 0 +37
Types of integers:
Table 1.2 Integer types in C++
Type Range
short -32,767 .. 32,767
unsigned short 0 .. 65,535
int -2,147,483,647 .. 2,147,483,647
unsigned 0 .. 4,294,967,295
long -2,147,483,647 .. 2,147,483,647
unsigned long 0 ..4,294,967,295
Characters
Store single characters – char
Enclosed the characters in single quotes
Strings
Group of characters
Use double quotes to enclose a string’s value in a program
1.3 Arithmetic Expression
Multiple operators
Step-by-step evaluation rules of an expression containing several
operators:
Table 1.2: Evaluation of Expressions
1. Parentheses Evaluate parenthesized subexpressions first.
2. Precedence Evaluate operators according to this precedence:
i) unary+ unary-
ii) * / %
iii) binary+ binary-
3. Associativity If there is a sequence of two or more operators of the
same precedence, evaluate unary operators right to left
(right associativity) and binary operators left to right (left
associativity).
Can include additional parentheses to improve the readability of
complex subexpression e.g:
p / –q + ( r – s + t ) * n => ( p / (-q) ) + ( ( r – s + t ) * n )
Table 1.3: Step-by-step evaluation:
n p q r s t
10.0 4.8 –2.0 8.5 12.0 0.5
p / –q + (r – s + t ) * n Within parentheses, – and + are of the
–3.5___ same precedence: apply left
____ –3.0 associativity.
___ 2.0 Unary operators have highest
2.4 _____________ precedence. / and * have same
–30.0 precedence: apply left associativy.
–27.6 + has lowest precedence.
Operators / and %
Calculate the integer quotient and remainder.
E. g: 38/7 -> 5, 38%7 -> 3
Rounding
To round a positive value of type double to the nearest integer, add
0.5 before explicitly converting to an int to avoid loss of the value’s
fractional part.
1.4 Additional Operators
C++ provides predefined units called functions for operators other than
+−*/
A program that uses functions must have access to the C++ math library,
a collection of predefined mathematical functions.
The list of names and descriptions of some of the most commonly used
functions along with the name of the file to #include in order to gain
access to each function is as in table below:
The abs function return int value while fabs for floating point arguments.
The arguments for log and log 10 must be positive.
The arguments for sin, cos and tan must be expressed in radians, not
degrees.
Example 1:
Ask the user to enter 3 numbers and calculate the average of the numbers.
Sample program:
****************************************************************
#include <iostream>
using namespace std;
int main()
{
double num1, num2, num3, average;
cout << "Please enter 3 numbers: " ;
cin >> num1 >> num2 >> num3;
average = (num1+num2+num3)/3;
cout << "The average of these numbers is " <<
average << endl;
return 0;
}
Example 2:
Calculate the volume, of a sphere of radius, using the formula:
Sample program:
****************************************************************
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double volume, radius=3.3, pi=3.142;
volume = 4*pi*pow(radius,3)/3;
cout << "Volume of the sphere is " << volume << "
cm^3." << endl;
return 0;
}