SEHH2041 Applied Computing Tutorial 2
Tutorial 2: C++ Programming Lab One
Learning Outcomes
• Online compiler
• Writing, compiling, and executing C++ programs
Online Compiler
You may use any online compiler in this subject.
http://cppshell.com/
https://www.programiz.com/cpp-programming/online-compiler/
https://replit.com/languages/cpp
https://www.onlinegdb.com/online_c++_compiler
https://www.tutorialspoint.com/compile_cpp_online.php
First Program in C++
Note: C++ program is case-sensitive. That means, for example, int is different
from INT
Look at the main.cpp program with the line numbers at the left as follows:
1. #include <iostream>
2.
3. int main(){
4. std::cout << "Hello World!\n";
5. }
Each line represents part of C++ statement or one whole C++ statement. Typically, a
C++ statement ends with a semi-colon ;. In some structures a whole if…else
structure, details of which are shown later, contains some C++ statements. The C++
statements are instructions to a computer to execute particular tasks. These
statements are executed one by one from the top first line down to the bottom line.
The first line #include <iostream> allows the program to output data to the
screen. Any line that begins with a # sign is a preprocessor directive which notifies
the preprocessor to include in the program the contents of a specific header file. In
this example, #include <iostream> tells the preprocessor to include in the
main.cpp C++ program the contents of the input/output stream header file
<iostream>.
At line 3, int main() is found in almost every C++ program; int indicates the data
type returned by the function called main. The parentheses after main indicate the
input into the main function. In this case, the blank inside the parentheses indicate
that there are no inputs into the main function.
The left brace { at line 3 indicates the beginning of a function while the right brace }
at line 5 marks the end of the function.
Page 1 of 7
SEHH2041 Applied Computing Tutorial 2
The entire line std::cout << "Hello World!\n"; at line 4 is a statement. A
statement must end with a semi-colon ;. The notation std::cout instructs the
computer to print the string enclosed by the double quotation marks "Hello
World!\n". The std::cout notation specifies that the standard output stream
(cout) is used. Other standard streams include standard input stream (cin) and
standard error stream (cerr). The << operator is a stream insertion operator which
tells the computer to insert the operator’s right operand "Hello World!\n" in the
output stream. The \n characters are not printed on the screen. The backslash \ is
an escape character which indicates that a special character is to be output. The
following table shows some special characters:
Escape
Meaning Action
Sequence
\n Position the cursor to the starting point of a
Newline
new line.
\t Tab Position the cursor to the next tab stop.
\r Position the cursor to the starting point of the
Carriage Return
current line; it does not jump to the new line.
\\ Backslash Print a backslash character.
\’ Single Print a single quotation mark.
Quotation Mark
\” Double Print a double quotation mark.
Quotation Mark
At line 5, add a line “return 0; ”.
This statement indicates the value 0 is output when the function ends. The program
will omit the statements, if any, after the return statement.
Page 2 of 7
SEHH2041 Applied Computing Tutorial 2
Comments
Comments are used to document a program and to make the program readable and
understandable. Comments are not compiled into machine codes. So, comments and
the statements marked as comments do not cause a computer to run.
There are two types of comments – single-line comment and multiple-line comment.
Double slash // indicates a single-line comment which tells that the remainder of a
line is a comment. Multiple-line comment begins with /* and ends with */.
For example, we add a multiple-line comment before the line 1 of the main.cpp
program and add a single-line comment at line 5:
/* Programmer Name: Peter Martins
Function: to print out a Hello World message */
1. #include <iostream>
2.
3. int main(){
4. std::cout << "Hello World!\n";
5. return 0; // return a dummy value zero when this program ends
6. }
Variables and Constants
A variable is a memory location that stores a value. The value in a variable can
change during runtime of the program. A constant is also a memory location that
stores a value. In contrast, the value stored in a constant remains unchanged during
runtime of the program.
Both variable and constant must be assigned with a name in accordance with the
following naming conventions:
1. The name must start with a letter. So, the variable name 1stname is not
acceptable while the variable name firstname is acceptable.
2. The name can contain only letters, digits, and the underscore character. No other
characters e.g. spaces, $, #, … are allowed in the name. So, the variable name
last name is not acceptable while the variable name lastname or last_name
is acceptable.
3. The name is case-sensitive e.g. the variable name Sales is different from sales.
4. The name cannot be any of the following reserved words in C++:
and and_eq asm auto bitand
bitor bool break case catch
char class const const_cast continue
default delete do double dynamic_cast
else enum explicit export extern
false float for friend goto
if inline int long mutable
namespace new not not_eq operator
or or_eq private protected public
register reinterpret_cast return short signed
Page 3 of 7
SEHH2041 Applied Computing Tutorial 2
sizeof static static_cast struct switch
template this throw true try
typedef typeid typename union unsigned
using virtual void volatile wchar_t
while xor xor_eq
Sample program:
1. #include <iostream>
2.
3. int main(){
4. int score;
5. score = 1;
6. std::cout << score;
7. return 0;
8. }
Data Type
In C++, data stored in a variable and a constant can be set to a specific type e.g.
integer, character and Boolean data types. The following table shows the commonly
used data types in C++:
Data Type Meaning of the Data Type
short Storing an integer in the range -32,768 to 32,767
int Storing an integer in the range -2,147,483,648 to
2,147,483,647
float Storing a real number in the range -3.4 × 1038 to 3.4 × 1038
double Storing a real number in the range -1.7 × 10308 to 1.7 × 10308
bool Storing a Boolean value which is either true or false
char Storing a single character ‘a’ ‘b’
string Storing zero or more characters “Hello World”
For example, the following statement declares an integer variable with the variable
name sum:
int sum;
Operators and Their Order of Precedence
C++ uses the symbols + - * / for addition, subtraction, multiplication and division.
For example, 5*3 means that 5 × 3 (i.e. 5 times 3 which gives 15); 7 / 2 means
7
(i.e. 7 is divided by 2 which gives 3.5). The order of precedence is shown below:
2
Page 4 of 7
SEHH2041 Applied Computing Tutorial 2
Precedence Operation
First Parentheses ( ), evaluated starting with the innermost pair.
Multiplication * and division / with equal precedence,
Second
evaluated from left to right.
Addition + and subtraction - with equal precedence,
Third
evaluated from left to right.
For example, 5 * 7 + 3 gives 38 where 5 * 7 is computed first, then its result 35 adds
to 3 which gives 38. (5 * (7 + 3)) gives 50 where 7 + 3 is computed first, then its
result 10 is multiplied by 5 to give 50.
Sample program:
1. #include <iostream>
2.
3. int main(){
4. int score;
5. score = 5 * 7 + 3 ;
6. std::cout << “First Score: ” << score;
7. score = (5 * (7 + 3)) ;
8. std::cout << “Second Score: ” << score;
9. return 0;
10. }
Assignment Operator
C++ uses the equal sign = to assign a value to a variable. For example, x = 3 is to
assign the value 3 to the variable x. The assignment operator = in C++ is different
from the equal sign = in Mathematics. So, typing the command x = x + 2 is allowed
in C++, but it is undefined in Mathematics. The command x = x + 2 means adding 2
to the current value of the variable x, and its result replaces the current value of x. If
the current value of x is 5, then issuing the command x = x + 2 will assign 7 to the
variable x.
Sample program:
1. #include <iostream>
2.
3. int main(){
4. int score;
5. score = 2;
6. score = score + 3;
7. std::cout << “Score: ” << score;
8. return 0;
9. }
Page 5 of 7
SEHH2041 Applied Computing Tutorial 2
Namespaces
If one specifies using namespace std; at the beginning of a C++ program, then
one does not have to put std:: throughout the program. The program will know to
look in the std library to find the function e.g. cout and cin.
For example, the following C++ program accepts a user input and prints it out:
/* Programmer Name: Peter Martins
Function: to display the user input */
#include <iostream>
int main() {
int score; // a variable storing the score
std::cout << "Enter a score: "; // prompt user for a score
std::cin >> score; // read the user input into score
std::cout << "The score is: " << score << "\n"; // print
return 0; // return a dummy value zero when this program ends
}
If we add using namespace std; at the beginning of the above C++ program right
after #include <iostream>, then we can take out std:: throughout the program
as follows:
/* Programmer Name: Peter Martins
Function: to display the user input */
#include <iostream>
using namespace std;
int main() {
int score; // a variable storing the score
cout << "Enter a score: "; // prompt user for a score
cin >> score; // read the user input into score
cout << "The score is: " << score << "\n"; // print
return 0; // return a dummy value zero when this program ends
}
Page 6 of 7
SEHH2041 Applied Computing Tutorial 2
C++ Exercise 1
1. Write the C++ program that prompts a user to enter an integer value as follows:
Enter an integer:
The program takes the user-input integer value and stores it into the variable
called x. The x variable has the int data type. The program then displays the
user-input integer value as follows if the user-input integer value is 8:
The integer you have just entered is: 8
2. Modify the above C++ program such that it computes the user input value plus 3,
and the result times 9. The program then displays the computation result as
follows if the user-input integer value is 8:
The integer you have just entered plus 3,
then the result times 9: 99
3. Write the C++ program that takes a user-input value and stores it into the variable
called Celsius. The Celsius variable has the float data type. The program
then converts the user input into a new value based on the following formula,
stores the new value into the float variable called Fahrenheit and displays
the Fahrenheit value:
Fahrenheit = Celsius × + 32
Page 7 of 7