You are on page 1of 21

1 C++ Programming Manual

WEEK ONE PRACTICAL

Objective:

a. Know the basic structure of a C++ Program


b. Know about comment in C++

Basic Structure of a C++ Program

Probably the best way to start learning a programming language is by writing a program.
Therefore, here is our first program:

The first panel shows the source code for our first program. The second one shows the result of
the program once compiled and executed. The way to edit and compile a program depends on the
compiler you are using. Depending on whether it has a Development Interface or not on its
version. Consult the compilers section and the manual or help included with your compiler if you
have doubts on how to compile a C++ console program.

The previous program is the typical program that programmer apprentices write for the first time,
and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest
programs that can be written in C++, but it already contains the fundamental components that
every C++ program has. We are going to look line by line at the code we have just written:

// my first program in C++

This is a comment line. All lines beginning with two slash signs (//) are considered comments
and do not have any effect on the behavior of the program. The programmer can use them to
include short explanations or observations within the source code itself. In this case, the line is a
brief description of what our program is.

#include <iostream>
2 C++ Programming Manual

Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular
code lines with expressions but indications for the compiler's preprocessor. In this case the
directive #include <iostream> tells the preprocessor to include the iostream standard file. This
specific file (iostream) includes the declarations of the basic standard input-output library in C+
+, and it is included because its functionality is going to be used later in the program.

using namespace std;

All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this
expression that we will be using these entities. This line is very frequent in C++ programs that
use the standard library, and in fact it will be included in most of the source codes included in
these tutorials.

int main ()

This line corresponds to the beginning of the definition of the main function. The main function
is the point by where all C++ programs start their execution, independently of its location within
the source code. It does not matter whether there are other functions with other names defined
before or after it the instructions contained within this function's definition will always be the
first ones to be executed in any C++ program. For that same reason, it is essential that all C++
programs have a main function.

The word main is followed in the code by a pair of parentheses (()). That is because it is a
function declaration: In C++, what differentiates a function declaration from other types of
expressions are these parentheses that follow its name. Optionally, these parentheses may enclose
a list of parameters within them.

Right after these parentheses we can find the body of the main function enclosed in braces ({}).
What is contained within these braces is what the function does when it is executed.

cout << "Hello World!";


3 C++ Programming Manual

This line is a C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a visible
effect in our first program.

cout represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen). cout is declared in the iostream standard file
within the std namespace, so that's why we needed to include that specific file and to declare that
we were going to use this specific namespace earlier in our code.

Notice that the statement ends with a semicolon character (;). This character is used to mark the
end of the statement and in fact it must be included at the end of all expression statements in all
C++ programs (one of the most common syntax errors is indeed to forget to include some
semicolon after a statement).

return 0;

The return statement causes the main function to finish. return may be followed by a return code
(in our example is followed by the return code 0). A return code of 0 for the main function is
generally interpreted as the program worked as expected without any errors during its execution.
This is the most usual way to end a C++ console program.

You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by //). There were lines
with directives for the compiler's preprocessor (those beginning by #). Then there were lines that
began the declaration of a function (in this case, the main function) and, finally lines with
statements (like the insertion into cout), which were all included within the block delimited by
the braces ({}) of the main function.

Comment in C++
4 C++ Programming Manual

Comments are parts of the source code disregarded by the compiler. They simply do nothing.
Their purpose is only to allow the programmer to insert notes or descriptions embedded within
the source code.

C++ supports two ways to insert comments:

// line comment

/* block comment */

The first of them, known as line comment, discards everything from where the pair of slash signs
(//) is found up to the end of that same line. The second one, known as block comment, discards
everything between the /* characters and the first appearance of the */ characters, with the
possibility of including more than one line.

We are going to add comments to our second program:

If you include comments within the source code of your programs without using the comment
characters combinations //, /* or */, the compiler will take them as if they were C++ expressions,
most likely causing one or several error messages when you compile it.

Lab Exercise:

a. Write the basic structure of a C++ Program


b. Write what you understand by comments in C++
5 C++ Programming Manual
6 C++ Programming Manual

WEEK TWO PRACTICAL

Objectives

Write a simple C++ program involving variables.

Key in the program below and answer the questions that follow by test running the program.

Note that the line numbers are not part of the program. This is the same program presented in the
lecture notes. Similar method will be applied for most of the practical work you will be required
to complete in the subsequent weeks.

// operating with variables

#include <iostream>

using namespace std;

int main ()

// declaring variables:

int a, b,c,d;

float sum,avg;

cout << Enter the value of a :;

cin >> a;

cout << Enter the value of b: ;

cin >> b;

cout << Enter the value of c: ;

cin >> c;

cout << Enter the value of d: ;


7 C++ Programming Manual

cin >> d;

sum = a + b + c + d;

avg = sum / 4;

cout << Sum = << sum;

cout << '\n';

cout <<Average = << avg;

cout << '\n';

return 0;

Questions:

a. What is the output of the program, use 12, 9, 15, 3 for values of a,b,c and d
b. Use 5,10,15,25 for a,b,c,d

______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
8 C++ Programming Manual

WEEK THREE PRACTICAL

Objectives

Write a simple C++ program using if statements.

#include <iostream>

#include <string>

using namespace std;

int main(){

string gender;

cin >> gender;

if(gender == "Male" or gender == "male" or gender == "MALE"){

cout << "See the rector";

}else if(gender == "Female" or gender == "female" or gender == "FEMALE"){

cout << "See the registrar";

return 0;

Question:

a. Run the program and enter Male as gender


b. Run the program and enter Female as gender

______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
9 C++ Programming Manual

WEEK FOUR PRACTICAL

Objectives:

a. Data types
b. Variables

Data types

Primitive Data types

Intuitively, something is different between data consisting of numeric values (such food prices at
McDonald's or the number of tacos you can get for a buck at Taco Bell) and data consisting of
strings of characters (such as the names of your best friends or the lyrics to your favorite song).
In one case we can meaningfully apply mathematical operations such as addition and subtraction,
while in the other we cannot. In programming terminology we say that the two groups of data are
of different type.

The C++ programming language accounts for several elementary types of data. All other types of
data are constructed as conglomerates of these primitive types. Our goal for now is to learn the
fundamentals of three basic types: integer, real, and character.

The integer data type encompasses the counting numbers and their negatives:

. . . -4, -3, -2, -1, 0, 1, 2, 3, 4, . . .

In contrast, the data type real includes numeric values with fractional components as 1.5, 10.999,
and 2.53. As explained in Computer Science: An Overview, objects of type integer are normally
stored within a machine's memory using two's complement notation, whereas objects of type real
are normally stored using floating-point notation.

The data type character accounts for data consisting of a single symbol such as a letter of the
alphabet, a punctuation mark, or any special symbol, such as $, %, and @. Data items of type
character are normally stored using ASCII code in C++ applications. In future sessions you will
learn how words and sentences can be constructed as collections of data of type character.
10 C++ Programming Manual

Run the following programs and write there output

Lab 4.1

#include <iostream>

using namespace std;

int main ()

// declaring variables:

int a, b;

int result;

a = 15;

b = 4;

a = a + 1;

result = a - b;

cout << result;

cout << '\n';

return 0;

}
11 C++ Programming Manual

Lab 4.2:

#include <iostream>

using namespace std;

int main ()

int a=5; // initial value = 5

int b(2); // initial value = 2

int result; // initial value undetermined

a = a + 3;

result = a - b;

cout << result;

cout << '\n';

return 0;

Lab 4.3:

#include <iostream>
12 C++ Programming Manual

using namespace std;

int a=5; // initial value = 5

int b(2); // initial value = 2

int result; // initial value undetermined

int main ()

int d = 10;

a = a + 3;

result = a - b;

d = d + result;

cout << result;

cout << '\n\';

cout << d;

cout << '\n';

return 0;

______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
13 C++ Programming Manual
14 C++ Programming Manual

WEEK FIVE PRACTICAL

Lab 5.1:

Execute the following program. In response to the first request, type one integer (8) followed by
the Enter key. In response to the second request, type two integers (7,10) followed by the Enter
key. Record and explain the results.

#include <iostream>

Using namespace std;

int main()

{int a, b, c;

cout << "Enter an integer.\n";

cin >> a;

cout << "\nThe value entered was " << a << endl;

cout << "Enter two integers.\n";

cin >> b >> c;

cout << "\nThe values entered were "<<b<<" and "<<c << endl;

return 0;

______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
_____________________________________________________________________________
15 C++ Programming Manual

Lab 5.2:

#include <iostream>

Using namespace std;

int main()

int a, b, c;

a = 7 % 3;

b = 8 % 3;

c = 8 % 4;

cout << a << " " << b << " " << c << endl;

return 0;

a. Run the code and write the output


b. The operator % is called the modulus operator. What does it do?
c. Change the statement a = 7 % 3; to a = 7.0 % 3.0; and try to execute the program. What
can you conclude?

______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
_____________________________________________________________________________

WEEK SIX PRACTICAL


16 C++ Programming Manual

Objectives:

a. Knows the while statement

The While Statement

Normally, instructions in a C++ program are executed in the order in which they appear. While
this may be sufficient for simple programs, it is not flexible enough for more complex tasks.
Thus, C++ provides a variety of control statements for redirecting the flow of execution. One of
these is the while control statement. The while control statement is used to execute a certain
block of code repetitively; the general form of the while statement is

while (condition)

{body}

where body is a statement or a sequence of statements. If body consists of only one statement,
then the opening and closing braces of the while statement can be omitted.

Execution of the while statement begins with testing the condition. If true, the statement or
statements within the body will be executed, and the condition will be tested once again. This
cyclic process continues until the condition is found to be false, at which time control skips to the
statements following the closing brace of the while statement

Lab 6.1:

#include <iostream>

Using namespace std;

int main()

int i;

i = 5;

while (i > 0)
17 C++ Programming Manual

cout << "Recycle!\n";

i--;

return 0;

a. What is the output of the program


b. Change cout << "Recycle!\n"; to cout << Recycle << i << \n; What will be the
output?

Lab 6.2

What is the output of the program below?

#include <iostream>

Using namespace std;

int main()

int i;

i = 1;

while (i < 10)

i++;

cout << i << endl;

}
18 C++ Programming Manual

return 0;

______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
__________________________________
19 C++ Programming Manual

WEEK SEVEN PRACTICAL

Objectives:

Knowing how if structure works

Lab 7.1

Consider the code below

#include <iostream>

#include <string>

using namespace std;

int main(){

int score;

string grade;

cin >> score;

if((score>=75) && (score<=100)){

grade= "A";

else if(score>=70 && score<=74){

grade= "AB";

}
20 C++ Programming Manual

else if(score>=65 && score<=69){

grade="B";

else if(score>=60 && score<=64){

grade="C";

else if(score>=55 && score<=59){

grade="CD";

else if(score>=50 && score<=54){

grade="D";

else if(score>=45 && score<=49){

grade="DE";

else if(score>=40 && score<=44){

grade="E";

else{

grade="F";

}
21 C++ Programming Manual

cout << grade << "\n";

return 0;

a. What will be the result of the code if 78 is entered


b. What will be the result of the code if 39 is entered
c. What will be the result of the code if 62 is entered
d. What will be the result of the code if 41 is entered

You might also like