Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
38 views65 pages

COS 102 Practical

COS102 is an introductory course on problem solving that covers algorithm development, implementation strategies, and representation methods such as flowcharts and pseudocode. The course includes practical examples of algorithms for various problems and introduces C++ programming, emphasizing its features and usage. Students will learn to create and implement algorithms in C++ while understanding fundamental programming concepts.

Uploaded by

chizzyonodugo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views65 pages

COS 102 Practical

COS102 is an introductory course on problem solving that covers algorithm development, implementation strategies, and representation methods such as flowcharts and pseudocode. The course includes practical examples of algorithms for various problems and introduces C++ programming, emphasizing its features and usage. Students will learn to create and implement algorithms in C++ while understanding fundamental programming concepts.

Uploaded by

chizzyonodugo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

COS102, Introduction to Problem Solving

Course Content:
Problem solving strategies, Concepts and properties of Algorithms, Role of algorithm in problem
solving process, Characteristics of good algorithms, Steps involved in algorithm development,
Problem solving strategies: top down and bottom-up methods, Implementation strategies, Develop
algorithms for simple problems, Representation of algorithms: Flowchart and Pseudocodes,
Development of flowchart and pseudocodes, Flowchart symbols and uses, Program objects,
Implementation of algorithm in any programming language such as Visual Basic, Java, C or C++

By

Asso. Prof. Osondu Oguike and Dr Adaora Obayi


Department of Computer Science,
University of Nigeria, Nsukka, Enugu State, Nigeria.

1
1.1Problem Solving Using Algorithm and
Flowchart
Dr. Adaora Obayi

1.2Examples of Algorithm and Flowchart


Development
Dr. Adaora Obayi

The following Examples illustrate problem solving through the development of Algorithms.

Example 1 Develop an algorithm in pseudo-code that ask the user for two integer values and compute and
displays their sum and product.
1. Request Data
1.1 Request X
1.2 Request Y
2. Process/Calculate Results
2.1 Calculate total = X+Y
2.2 Calculate product = X*Y
3. Display Results
3.1 Display total
3.2 Display product

Example 2. Develop an algorithm in pseudo code that will read in the width and length of a rectangular
plot in feet, and the price per square foot, the algorithm will compute and display the total price of the plot.
1. Request Data
1.1 Request Length
1.2 Request width
1.3 Request Unit_Price
2. Calculate Total Price
2.1 Calculate Area = Length*Width
2.2 Calculate Total_Price = Area*Unit_Price
3. Display Total Price

2
Example 3 Develop an algorithm in pseudo code that will request for the following as input: age of staff,
normal pay rate per hour, number of hours worked, and the algorithm will calculate the pay as follows:
If the age of the staff is less than eighteen years, the pay rate will be 2/3 of the normal pay rate; otherwise,
the normal pay rate will be used.
Solution:
From the above problem, we can identify the following steps that sole the problem:
1. Request Data
2. Calculate Pay
3. Display Pay
Applying stepwise refinement to each of the steps where necessary, we have the following refinements:
1. Request Data
1.1 Request age
1.2 Request pay rate
1.3 Request hours
2. Calculate Pay
2.1 IF age ‹ 18 THEN
2.1.1 Calculate pay = 2/3*pay rate*hours ELSE
2.1.2 Calculate pay = pay rate*hours
3. Display Pay

Example 4: Develop an algorithm in pseudo code that will request for an integer number of students,
afterwards, it will request for score of each of the students and it will calculate and display the total score.
1. Request n
2. Calculate total
2.1 Calculate count = 0
2.2 Calculate total = 0
2.3 Calculate count = count + 1
2.4 Request score
2.5 Calculate total = total + score
2.6 Repeat 2.3, 2.4, 2.5 until count = n
3. Display total

Example 5: Develop an algorithm in pseudo code that will request for an integer number, as the number of
students, afterwards, it will request for an n different scores and it will determine and display the minimum
of the scores.
1. Request n
2. Determine minimum
2.1 Initialize count = 1
2.2 Request score
2.3 Initialize minimum score = score
2.4 Calculate count = count + 1
2.5 Request score
2.6 Calculate minimum = score IF score ‹ minimum
2.7 Repeat 2.4, 2.5, 2.6 until count = n
3. Display minimum

Example 6: Write an algorithm to calculate the simple interest using the formula:
3
Simple Interest = 𝑃 ∗ 𝑁 ∗ 𝑅 /100, Where 𝑃 is principle Amount, 𝑁 is the number of years and 𝑅 is the rate
of interest.
Step 1: Read the three input quantities’ P, N and R.
Step 2: Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

Example 7: Write an algorithm to find the area of the triangle.


Let 𝑏, 𝑐 be the sides of the triangle 𝐴𝐵𝐶 and 𝐴 the included angle between the given sides.
Step 1: Input the given elements of the triangle namely sides 𝑏, 𝑐 and angle between the sides 𝐴
Step 2: Area = 1/2 ∗ 𝑏 ∗ 𝑐 ∗ (𝐴)
Step 3: Output the Area
Step 4: Stop.

Example 8: Write an algorithm to find the largest of three numbers X, Y, Z


Step 1 Read the numbers ,,.
Step 2 If (X > Y)
Big = X
Else big = Y
Step 3 If (big < Z)
Big = Z
Step 4 Print Big
Step 5 Stop.
Example 9: Write an algorithm to find the largest data value of a set of given data values
Solution: Algorithm to find Largest Data Value
Step 1: LARGE = 0
Step 2: read NUM
Step 3: While NUM > = 0 do
3.1 If NUM > LARGE then
3.1.1 LARGE = NUM
3.2. Read NUM
Step 4: Write “largest data value is”, LARGE
Step 5: Stop

Example 10: Write an algorithm which will test whether a given integer value is prime or not.
Algorithm to test for Prime
Step 1: M = 2
Step 2: read N
Step 3: MAX = SQRT (N)
Step 4: While M < = MAX do
4.1 If (M * (N/M) = N then
4.1.1 Goto step 7
Step 4.2. M = M+1
Step 5: Write “number is prime”
Step 6 Goto step 8
Step 7 Write “number is not a prime”

4
Step 8 End

Example 11: Write algorithm to find the factorial of a given number N


Algorithm to find factorial
Step 1: PROD = 1
Step 2: I = 0
Step 3 read N
Step 4: While I < N do
4.1 I = I + 1
Step 4.2. PROD = PROD* I
Step 5: Write “Factorial of N is”, PROD
Step 6: End

Example 12: Write an algorithm to calculate the perimeter and area of rectangle. Given its length and
width.
Step 1: Read length and width of the rectangle
Step 2: Calculate perimeter = 2* (length + width)
Step 3: Calculate area = length *width.
Step 4: Print perimeter
Step 5 Print area
Step 6: Stop

2. Implementation of Algorithms Using C++


Dr. O. E. Oguike

2.0 Introduction to C++


What is C++?

C++ is a cross-platform language that can be used to create high-performance applications.

C++ was developed by Bjarne Stroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and memory.

The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14,
C++17, C++20.

Why Use C++

C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.

5
C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.

C++ is fun and easy to learn!

As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa.

Difference between C and C++

C++ was developed as an extension of C, and both languages have almost the same syntax.

The main difference between C and C++ is that C++ support classes and objects, while C does
not.

C++ Get Started

To start using C++, you need two things:

• A text editor, like Notepad, to write C++ code


• A compiler, like GCC, to translate the C++ code into a language that the computer will
understand

There are many text editors and compilers to choose from. In this tutorial, we will use an IDE
(see below).

C++ Install IDE

An IDE (Integrated Development Environment) is used to edit AND compile the code.

Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and they can
be used to both edit and debug C++ code.

Note: Web-based IDE's can work as well, but functionality is limited.

We will use Code::Blocks in our tutorial, which we believe is a good place to start.

You can find the latest version of Codeblocks at http://www.codeblocks.org/. Download


the mingw-setup.exe file, which will install the text editor with a compiler.

6
You can make programming fun by making the C++ Compiler handy. You can install a version of
C++ Compiler on your Android phone. This can be done by going to Play Store, search for C++
Compiler, a list of different C++ Compiler will appear. Choose one, I have chosen Coding C++,
and install it on your Android phone. Coding can then start with you Android phone.

C++ Quickstart

Let's create our first C++ file.

Open Codeblocks and go to File > New > Empty File.

Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters.
For now, focus on how to run the code.

In Codeblocks, it should look like this:

Then, go to Build > Build and Run to run (execute) the program. The result will look something
to this:

7
Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.

Example explained

Line 1: #include <iostream> is a header file library that lets us work with input and output
objects, such as cout (used in line 5). Header files add functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and variables from the
standard library.

Don't worry if you don't understand how #include <iostream> and using namespace std works.
Just think of it as something that (almost) always appears in your program.

Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.

Line 4: Another thing that always appear in a C++ program, is int main(). This is called
a function. Any code inside its curly brackets {} will be executed.

Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<)
to output/print text. In our example it will output "Hello World".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the main function.

Omitting Namespace

You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:

#include <iostream>

8
int main() {
std::cout << "Hello World!";
return 0;
}

C++ Output (Print Text)

The cout object, together with the << operator, is used to output values/print text:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

You can add as many cout objects as you want. However, note that it does not insert a new line
at the end of the output:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}

You can add as many cout objects as you want. However, note that it does not insert a new line
at the end of the output:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning C++";

9
return 0;
}

New Lines

To insert a new line, you can use the \n character:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}

Tip: Two \n characters after each other will create a blank line:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}

Another way to insert a new line, is with the endl manipulator:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}

10
C++ Comments

Comments can be used to explain C++ code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment
cout << "Hello World!";

This example uses a single-line comment at the end of a line of code:

Example
cout << "Hello World!"; // This is a comment

C++ Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Single or multi-line comments?

It is up to you which you want to use. Normally, we use // for short comments, and /* */ for
longer.

C++ Variables

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

11
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• double - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
• string - stores text, such as "Hello World". String values are surrounded by double quotes
• bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

Syntax
type variableName = value;

Where type is one of C++ types (such as int), and variableName is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


cout << myNum;

You can also declare a variable without assigning the value, and assign the value later:

Example
int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

12
Other Types

A demonstration of other data types:

Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

You will learn more about the individual types in the Data Types chapter.

Display Variables

The cout object is used together with the << operator to display variables.

To combine both text and a variable, separate them with the << operator:

Example
int myAge = 35;
cout << "I am " << myAge << " years old.";

Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";

Add Variables Together

To add a variable to another variable, you can use the + operator:

Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;

13
Exercise:

Create a variable named myNum and assign the value 50 to it.

Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list:

Example
int x = 5, y = 6, z = 50;
cout << x + y + z;

One Value to Multiple Variables

You can also assign the same value to multiple variables in one line:

Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;

C++ Identifiers

All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

Example
// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is

14
int m = 60;

The general rules for naming variables are:

• Names can contain letters, digits and underscores


• Names must begin with a letter or an underscore (_)
• Names are case sensitive (myVar and myvar are different variables)
• Names cannot contain whitespaces or special characters like !, #, %, etc.
• Reserved words (like C++ keywords, such as int) cannot be used as names

Constants

When you do not want others (or yourself) to override existing variable values, use
the const keyword (this will declare the variable as "constant", which means unchangeable and
read-only):

Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are unlikely to
change:

Example
const int minutesPerHour = 60;
const float PI = 3.14;

C++ User Input

You have already learned that cout is used to output (print) values. Now we will use cin to get
user input.

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).

In the following example, the user can input a number, which is stored in the variable x. Then we
print the value of x:

Example
int x;
cout << "Type a number: "; // Type a number and press enter

15
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value

Good To Know

cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)

cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)

Creating a Simple Calculator

In this example, the user must input two numbers. Then we print the sum by calculating (adding)
the two numbers:

Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;

Exercise:

Use the correct keyword to get user input, stored in the variable x:

C++ Data Types

As explained in the Variables chapter, a variable in C++ must be a specified data type:

Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String

16
Try it Yourself »

Basic Data Types

The data type specifies the size and type of information the variable will store:

Data Type Size Description

Boolean 1 byte Stores true or false values

Char 1 byte Stores a single character/letter/number, or ASCII values

Int 2 or 4 bytes Stores whole numbers, without decimals

Float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 7 decimal digits

Double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 15 decimal digits

You will learn more about the individual data types in the next chapters.

Exercise:

Add the correct data type for the following variables:

myNum = 9;
myDoubleNum = 8.99;
myLetter = 'A';
myBool = false;

17
myText = "Hello World";
Numeric Types

Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.

int
int myNum = 1000;
cout << myNum;

float
float myNum = 5.75;
cout << myNum;

double
double myNum = 19.99;
cout << myNum;

float vs. double

The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is only six or seven decimal digits, while double variables
have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;

Boolean Types

A boolean data type is declared with the bool keyword and can only take the values true or false.

When the value is returned, true = 1 and false = 0.

18
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

Boolean values are mostly used for conditional testing, which you will learn more about in a
later chapter.

Character Types

The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':

Example
char myGrade = 'B';
cout << myGrade;

Alternatively, you can use ASCII values to display certain characters:

Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;

Tip: A list of all ASCII values can be found in our ASCII Table Reference.

String Types

The string type is used to store a sequence of characters (text). This is not a built-in type, but it
behaves like one in its most basic usage. String values must be surrounded by double quotes:

Example
string greeting = "Hello";
cout << greeting;

To use strings, you must include an additional header file in the source code,
the <string> library:

19
Example
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";

// Output string value


cout << greeting;

C++ Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;

Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Try it Yourself »

C++ divides the operators into the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

Arithmetic Operators

20
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Exercise:

Multiply 10 with 5, and print the result.

cout << 10 5;
Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:

21
Example
int x = 10;

Try it Yourself »

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;
x += 5;

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

22
|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison Operators

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true (1) or false (0).

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3

Try it Yourself »

A list of all comparison operators:

Operator Name Example

== Equal to x == y

!= Not equal x != y

23
> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical Operators

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true

C++ Strings

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type string and assign it a value:

string greeting = "Hello";

24
To use strings, you must include an additional header file in the source code,
the <string> library:

Example
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";

C++ Exercises
Test Yourself With Exercises
Exercise:

Fill in the missing part to create a greeting variable of type string and assign it the value Hello.

= ;
String Concatenation

The + operator can be used between strings to add them together to make a new string. This is
called concatenation:

Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;

In the example above, we added a space after firstName to create a space between John and Doe
on output. However, you could also add a space with quotes (" " or ' '):

Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;

Append

25
A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. For example, you can also concatenate strings with the append() function:

Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;

Adding Numbers and Strings

WARNING!

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)

If you add two strings, the result will be a string concatenation:

Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

If you try to add a number to a string, an error occurs:

Example
string x = "10";
int y = 20;
string z = x + y;

String Length

To get the length of a string, use the length() function:

26
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();

Tip: You might see some C++ programs that use the size() function to get the length of a string.
This is just an alias of length(). It is completely up to you if you want to use length() or size():

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();

Access Strings

You can access the characters in a string by referring to its index number inside square
brackets [].

This example prints the first character in myString:

Example
string myString = "Hello";
cout << myString[0];
// Outputs H

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

This example prints the second character in myString:

Example
string myString = "Hello";
cout << myString[1];
// Outputs e

Change String Characters

To change the value of a specific character in a string, refer to the index number, and use single
quotes:

Example
string myString = "Hello";
myString[0] = 'J';
cout << myString;

27
// Outputs Jello instead of Hello

User Input Strings

It is possible to use the extraction operator >> on cin to display a string entered by a user:

Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;

// Type your first name: John


// Your name is: John

However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):

Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

// Type your full name: John Doe


// Your name is: John

From the example above, you would expect the program to print "John Doe", but it only prints
"John".

That's why, when working with strings, we often use the getline() function to read a line of text.
It takes cin as the first parameter, and the string variable as second:

Example
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

28
// Type your full name: John Doe
// Your name is: John Doe

Omitting Namespace

You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for string (and cout) objects:

Example
#include <iostream>
#include <string>

int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}

It is up to you if you want to include the standard namespace library or not.

C++ Math

C++ has many functions that allows you to perform mathematical tasks on numbers.

Max and min

The max(x,y) function can be used to find the highest value of x and y:

Example
cout << max(5, 10);

Try it Yourself »

And the min(x,y) function can be used to find the lowest value of x and y:

29
Example
cout << min(5, 10);

Try it Yourself »

C++ <cmath> Header

Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm),
can be found in the <cmath> header file:

Example
// Include the cmath library
#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

Other Math Functions

A list of other popular Math functions (from the <cmath> library) can be found in the table
below:

Function Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x
asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x


cbrt(x) Returns the cube root of x
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x
cosh(x) Returns the hyperbolic cosine of x
exp(x) Returns the value of Ex

30
expm1(x) Returns ex -1
fabs(x) Returns the absolute value of a floating x
fdim(x, y) Returns the positive difference between x and y

floor(x) Returns the value of x rounded down to its nearest integer


hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
fma(x, y, z) Returns x*y+z without losing precision
fmax(x, y) Returns the highest value of a floating x and y
fmin(x, y) Returns the lowest value of a floating x and y

fmod(x, y) Returns the floating point remainder of x/y


pow(x, y) Returns the value of x to the power of y
sin(x) Returns the sine of x (x is in radians)
sinh(x) Returns the hyperbolic sine of a double value
tan(x) Returns the tangent of an angle

tanh(x) Returns the hyperbolic tangent of a double value

C++ Exercises
Test Yourself With Exercises
Exercise:

Use the correct function to print the highest value of x and y.

int x = 5;
int y = 10;
cout << (x, y);

C++ Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

• YES / NO
• ON / OFF
• TRUE / FALSE

31
For this, C++ has a bool data type, which can take the values true (1) or false (0).

Boolean Values

A boolean variable is declared with the bool keyword and can only take the values true or false:

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

From the example above, you can read that a true value returns 1, and false returns 0.

However, it is more common to return boolean values from boolean expressions (see next page).

Boolean Expression

A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false).

You can use a comparison operator, such as the greater than (>) operator to find out if an
expression (or a variable) is true:

Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9

Try it Yourself »

Or even easier:

Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9

Try it Yourself »

In the examples below, we use the equal to (==) operator to evaluate an expression:

Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is equal to 10

32
Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15

Booleans are the basis for all C++ comparisons and conditions.

You will learn more about conditions (if...else) in the next chapter.

C++ Exercises
self With Exercises
Exercise:

Fill in the missing parts to print the values 1 (for true) and 0 (for false):

isCodingFun = true;
isFishTasty = false;
cout << ;
cout << ;
C++ Conditions and If Statements

C++ supports the usual logical conditions from mathematics:

• Less than: a < b


• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C++ has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is true


• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of C++ code to be executed if a condition is true.

33
Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition
is true, print some text:

Example
if (20 > 18) {
cout << "20 is greater than 18";
}

We can also test variables:

Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}

Example explained

In the example above we use two variables, x and y, to test whether x is greater than y (using
the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the
screen that "x is greater than y".

C++ Exercises
Test Yourself With Exercises
Exercise:

Print "Hello World" if x is greater than y.

int x = 50;
int y = 10;

34
(x y) {
cout << "Hello World";
}Bottom of Form
The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition is false. Because of this, we
move on to the else condition and print to the screen "Good evening". If the time was less than
18, the program would print "Good day".

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true

35
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first condition is false. The next
condition, in the else if statement, is also false, so we move on to the else condition
since condition1 and condition2 is both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Short Hand If...Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands. It can be used to replace multiple lines of code with a single line. It is often used
to replace simple if else statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

Example
int time = 20;
if (time < 18) {
cout << "Good day.";

36
} else {
cout << "Good evening.";
}

You can simply write:

Example
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;

C++ Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• The break and default keywords are optional, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
37
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)

The break Keyword

When C++ reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more
testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.

The default Keyword

The default keyword specifies some code to run if there is no case match:

Example
int day = 4;
switch (day) {
case 6:

38
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"

Note: The default keyword must be used as the last statement in the switch, and it does not need
a break

C++ Exercises
Test Yourself With Exercises
Exercise:

Insert the missing parts to complete the following switch statement.

int day = 2;
switch ( ){
1:
cout << "Saturday";
break;
2:
cout << "Sunday";
;
}
C++ Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

C++ While Loop

The while loop loops through a block of code as long as a specified condition is true:

39
Syntax
while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as a variable (i)
is less than 5:

Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never
end!

C++ Exercises
Tesself With Exercises
Exercise:

Print i as long as i is less than 6.

int i = 1;
(i < 6) {
cout << i << "\n";
;
}
The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.

Syntax
do {
// code block to be executed
40
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:

Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C++ For Loop

When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}

41
Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is
true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Another Example
This example will only print even values between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}

C++ Exercises
Test Yourself With Exercises
Exercise:
Use a for loop to print "Yes" 5 times:

(int i = 0; i < 5; ) {
cout << << "\n";
}

C++ Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

42
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}

C++ Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}

Break and Continue in While Loop


You can also use break and continue in while loops:

Break Example
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

Continue Example
int i = 0;
while (i < 10) {

43
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}

C++ Exercises
Test Yourself With Exercises
Exercise:
Stop the loop if i is 5:

for (int i = 0; i < 10; i++) {


if (i == 5) {
;
}
cout << i << "\n";
}

Online C++ Compiler (Editor)


Online C++ compiler with Editor is available, you can edit C++ code, and view the result in your
browser. Consider the C++ codes below, and right click on the link, “Try it Yourself”, below it,
open the link and see how it works.

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Hello World!

Try it Yourself »

44
Online C++ Compiler Explained
The window to the left is editable - edit the code and click on the "Run" button to view the result
in the right window.

The icons are explained in the table below:

Icon No Description

1 Go to www.w3schools.com

2 Menu button for more options

3 Change orientation (horizontally or vertically)

4 Change color theme (dark or light)

After editing the C++ code, just click Run to execute the C++ code.

C++ Exercise:
1. Insert the missing part of the code below to output "Hello World!".

int main() {
<< "Hello World!";
return 0;
}

2. Insert a new line after "Hello World", by using a special character:

45
int main() {
cout << "Hello World! ";
cout << "I am learning C++";
return 0;
}

3. Comments in C++ are written with special characters. Insert the missing parts:

This is a single-line comment


This is a multi-line comment

4. Create a variable named myNum and assign the value 50 to it.

= ;

5. Display the sum of 5 + 10, using two variables: x and y.

= ;
int y = 10;
cout << x + y;

6. Create a variable called z, assign x + y to it, and display the result.

int x = 5;
int y = 10;
= x + y;
cout << ;

46
7. Fill in the missing parts to create three variables of the same type, using a comma-
separated list:

x = 5 y = 6 z = 50;
cout << x + y + z;

8. Use the correct keyword to get user input, stored in the variable x:

int x;
cout << "Type a number: ";
>> ;

9. Fill in the missing parts to print the sum of two numbers (which is put in by the user):

int x, y;
int sum;
cout << "Type a number: ";
>> ;
cout << "Type another number: ";
>> ;
sum = x + y;
cout << "Sum is: " << ;

10. Add the correct data type for the following variables:

myNum = 9;
myDoubleNum = 8.99;
myLetter = 'A';
myBool = false;

47
myText = "Hello World";

11. Create two boolean variables, named yay and nay, and add appropriate values to them:

= ;
= ;

12. Create a greeting variable, and display the value of it:

= "Hello";
cout << ;

13. Multiply 10 with 5, and print the result.

cout << 10 5;

14. Divide 10 by 5, and print the result.

cout << 10 5;

15. Use the correct operator to increase the value of the variable x by 1.

int x = 10;
x;

16. Use the correct operator to increase the value of the variable x by 1.

48
int x = 10;
x;

17. Fill in the missing part to create a greeting variable of type string and assign it the
value Hello.

= ;

18. Use the correct operator to concatenate two strings:

string firstName = "John ";


string lastName = "Doe";
cout << firstName lastName;

19. Use the correct function to print the length of the txt string.

string txt = "Hello";


cout << . ;

20. Access the first character (H) in myString and print the result:

string myString = "Hello";


cout << ;

21. Change the first character (H) in myString to 'J':

string myString = "Hello";


;

49
cout << myString;

22. Use the correct function to print the highest value of x and y.

int x = 5;
int y = 10;
cout << (x, y);

23. Use the correct function to print the square root of x.

#include <iostream>
#include < >
using namespace std;

int main() {
int x = 64;
cout << (x);
return 0;
}

24. Use the correct function to round the number 2.6 to its nearest integer.

#include <iostream>
#include < >
using namespace std;

int main() {
cout << (2.6);
return 0;

50
}

25. Fill in the missing parts to print the values 1 (for true) and 0 (for false):

isCodingFun = true;
isFishTasty = false;
cout << ;
cout << ;

26. Fill in the missing parts to print the value true (for true):

int x = 10;
int y = 9;
cout << ( );

27. Print "Hello World" if x is greater than y.

int x = 50;
int y = 10;
(x y) {
cout << "Hello World";
}

28. Print "Hello World" if x is equal to y.

int x = 50;
int y = 50;
(x y) {

51
cout << "Hello World";
}

29. Print "Yes" if x is equal to y, otherwise print "No".

int x = 50;
int y = 50;
(x y) {
cout << "Yes";
} {
cout << "No";
}

30. Print "1" if x is equal to y, print "2" if x is greater than y, otherwise print "3".

int x = 50;
int y = 50;
(x y) {
cout << "1";
} (x y) {
cout << "2";
} {
cout << "3";
}

31. Insert the missing parts to complete the following "short hand if...else statement"
(ternary operator):

int time = 20;

52
string result = time < 18 "Good day."
"Good evening.";
cout << result;

32. Insert the missing parts to complete the following switch statement.

int day = 2;
switch ( ) {
1:
cout << "Saturday";
break;
2:
cout << "Sunday";
;
}

33. Complete the switch statement, and add the correct keyword at the end to specify
some code to run if there is no case match in the switch statement.

int day = 4;
switch ( ) {
1:
cout << "Saturday";
break;
2:
cout << "Sunday";
;
:
cout << "Weekend";
}

53
34. Print i as long as i is less than 6.

int i = 1;
(i < 6) {
cout << i << "\n";
;
}

35. Use the do/while loop to print i as long as i is less than 6.

int i = 1;
{
cout << i << "\n";
;
}
(i < 6);

36. Use a for loop to print "Yes" 5 times:

(int i = 0; i < 5; ) {
cout << << "\n";
}

37. Stop the loop if i is 5.

for (int i = 0; i < 10; i++) {


if (i == 5) {

54
;
}
cout << i << "\n";
}

38. In the following loop, when the value is "4", jump directly to the next value.

for (int i = 0; i < 10; i++) {


if (i == 4) {
;
}
cout << i << "\n";
}

2.1 Conversion of Algorithms into C++ Codes


Having introduced C++ programming language, we proceed by converting all the algorithms in
section 1 into C++ codes.

Example 1 Convert the algorithm that asks the user for two integer values and compute and displays their
sum and product, into C++ codes.

#include <iostream>
using namespace std;

int main()
{
int x = 0, y = 0, total = 0. product = 0;
cout << "Enter the first integer number: ";
cin>>x;
cout<<"Enter the first integer number: ";
cin>>y;
total = x+y;
product=x*y;
cout<<"The total of the two numbers are: "<<total<<"\n";
cout<<"The product of the two numbers are: "<<product<<"\n";

55
return 0;
}

Example 2. Convert the algorithm that will read in the width and length of a rectangular plot in
feet, and the price per square foot, the algorithm will compute and display the total price of the
plot, into C++ code.

Solution:

#include <iostream>
using namespace std;

int main()
{
int length = 0, width = 0, unit_price = 0. area = 0;, total_price = 0
cout << "Enter the Length : ";
cin>>length;
cout<<"Enter the Width : ";
cin>>width;
area = length*width;
total_price=area*unit_price;
cout<<"The total price is : "<<total_price<<"\n";
return 0;
}

Example 3. Convert the algorithm in Example 3, of section 1, into C++ program.

#include <iostream>
using namespace std;

int main()
{
double age = 0.0, pay_rate = 0.0, hours = 0.0, pay = 0.0;
cout << "Enter the age : ";
cin>>age;
cout<<"Enter the pay rate : ";
cin>>pay_rate;
cout<<"Enter the hours : ";
cin>>hours;
area = length*width;
total_price=area*unit_price;
if (age < 18.0)
{
pay = 2/3*pay_rate*hours;

56
}
else
{
pay = pay_rate*hours;
}
cout<<"The pay is : "<<pay<<"\n";
return 0;
}

Example 4: Convert the algorithm in Example 4 of section 1, into C++ program.

#include <iostream>
using namespace std;

int main()
{
double total = 0.0, score = 0.0;
int numb = 0, count = 0;
cout << "Enter the number of scores : ";
cin>>numb;
while (count < numb)
{
count += 1;
cout<<"Enter a score : ";
cin>>score;
total = total + score;
}
cout<<"The total score is : "<<total<<"\n";
}

Example 5: Convert the algorithm in Example 5 of section 1, into C++ program.

#include <iostream>
using namespace std;

int main()
{
double minimum = 0.0, score = 0.0;
int numb = 0, count = 1;
cout << "Enter the number of scores : ";
cin>>numb;
cin>>score;
minimum = score;
while (count < numb)
{
count += 1;

57
cout<<"Enter a score : ";
cin>>score;
if (score < minimum)
{
minimum = score;
}
}
cout<<"The minimum of the scores is : "<<minimum<<"\n";
}

Example 6: Convert the algorithm in Example 6 of section 1, into C++ program.

#include <iostream>
using namespace std;

int main()
{
double principal = 0.0, number = 0.0, rates = 0.0, interest = 0.0;
cout << "Enter the principal amount : ";
cin>>principal;
cout<<"Enter the number of years : ";
cin>>number;
cout<<"Enter the rates : ";
cin>>rates;
interest = (principal*number*rates)/100;
cout<<"The Simple Interest is : "<<interest;
}

Example 8: Convert the algorithm in Example 8 of section 1, into C++ program.

#include <iostream>
using namespace std;

int main()
{
double X = 0.0, Y= 0.0, Z = 0.0, Big = 0.0;
cout << "Enter the first number : ";
cin>>X;
cout<<"Enter the second number : ";
cin>>Y;
cout<<"Enter the third number : ";
cin>>Z;
if (X > Y)
{
Big = X;
}
else
58
{
Big = Y;
}
if (Big < Z)
{
Big = Z;
}
cout<<"The Largest of the three numbers is : "<<Big;
}

Example 9: Convert the algorithm in Example 8 of section 1, into C++ program.

#include <iostream>
using namespace std;

int main()
{
double maximum = 0.0, score = 0.0;
int numb = 0, count = 0;
cout << "Enter the number of scores : ";
cin>>numb;
cin>>score;
maximum = score;
while (count < numb)
{
count += 1;
cout<<"Enter a score : ";
cin>>score;
if (score > maximum)
{
maximum = score;
}
}
cout<<"The maximum of the scores is : "<<maximum<<"\n";
}

Example 11: Convert the algorithm in Example 11 of section 1, into C++ program.

#include <iostream>
using namespace std;

int main()
{
int prod = 1, I = 1, N = 0;
cout << "Enter the number of scores : ";
cin>>N;

59
while (I < N)
{
count += 1;
prod = prod * I;
}
cout<<"The factorial is : "<<prod<<"\n";
}

#include <iostream>
using namespace std;

int main()
{
double length = 1.0, width = 1.0, Area = 1.0, Perimeter = 1.0;
cout << "Enter the Length : ";
cin>>length;
cout << "Enter the Width : ";
cin>>width;
Area = Length*Width;
Perimeter = 2.0*(Length + Width);
cout<<"The Area is : "<<Area<<"\n";
cout<<"The Perimeter is : "<<Perimeter<<"\n";
}

3. Laboratory Exercises
Laboratory Session 1.

Consider this C++ program:

#include <iostream>
using namespace std;

int main() {
cout << "Hello World ";
return 0;
}

0. Copy and run the program.

1. Modify the program so that it requests your name, stores it in a string variable, and prints
out your name as stored in the string variable, as follows:
My name is
Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.

60
2. Modify the program so that it requests for two integer numbers, stores them in integer
variables, a and b and displays the following results:
The values of a and b are:
a+b=
a -b=
a/b=
a%b=
Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.

Laboratory Session 2.

Consider this C++ program:

#include <iostream>
using namespace std;

int main() {
int numb = 0;
double score = 0.0;
double total = 0.0;
cout << "Enter the number of scores:";
cin >> numb;
for(int count = 1; count <=numb; count++)
{
cout << "Enter a score : ";
cin >> score;
total = total + score;
}
cout << "The total is : " << total;
return 0;
}

0. Copy, compile and execute the program. Understand what the program does. It computes
n
the total of n scores, using this statistical formula, X
i =1
i

Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.

1. Modify the program so that it computes the average of n scores, using this statistical
n

X
i =1
i
formula, . Run the program using number as 5 and the various values of scores as
n
shown in the Table below. Write the result that the program will display in the Table
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.

61
Scores 23 54 76 32 87
Average

2. Modify the program so that it computes the sum of squares of the scores, using this
n

X
2
statistical formula, i . Run the program using number as 5 and the various values of
i =1

scores as shown in the Table below. Write the result that the program will display in the
Table below. Make a screen print of the program, paste in a MS Word file, print it and
submit for assessment.

Scores 2 5 7 3 8
Sum of Square

3. Write an algorithm that will request for an integer, n, afterwards, it will request for n
different scores, Xi and compute computes and displays the sum of squares of the scores,
n

X
2
using this statistical formula, i .
i =1

4. Draw a flowchart that will represent the algorithm you have written in 3, above.

Laboratory Session 3.

Consider this C++ program:

#include <iostream>
using namespace std;

int main() {
int numb = 0;
double score = 0.0;
double total = 0.0;
cout << "Enter the number of scores:";
cin >> numb;
int count = 0;
while (count < numb)
{
cout << "Enter a score : ";
cin >> score;
total = total + score;
count += 1;
}
cout << "The total is : " << total;

62
return 0;
}

0. Copy and execute the program. Understand what the program does. It computes the total
n
of n scores, using this statistical formula, X
i =1
i

Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.

1. Modify the program so that it computes the average of n scores, using this statistical
n

X
i =1
i
formula, . Run the program using number as 5 and the various values of scores as
n
shown in the Table below. Write the result that the program will display in the Table
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.

Scores 25 55 75 35 85
Average

2. Modify the program so that it computes the sum of squares of the scores, using this
n

X
2
statistical formula, i .Write the result that the program will display in the Table
i =1

below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.

Scores 2 6 7 10 12
Sum of Square

3. Write an algorithm that will request for an integer, n, afterwards, it will request for n
different scores, Xi and compute computes and displays the sum of squares of the scores,
n

X
i =1
i
using this statistical formula, .
n

4. Draw a flowchart that will represent the algorithm you have written in 3, above.

Laboratory Session 4.

Consider this C++ program:

#include <iostream>
63
using namespace std;

int main() {
int numb = 0;
double score = 0.0;
double total = 0.0;
cout << "Enter the number of scores:";
cin >> numb;
int count = 0;
do
{
cout << "Enter a score : ";
cin >> score;
total = total + score;
count += 1;
}
while (count < numb);
cout << "The total is : " << total;
return 0;
}

0. Copy and execute the program. Understand what the program does. It computes the total
n
of n scores, using this statistical formula, X i =1
i

Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.

1. Modify the program so that it computes the average of n scores, using this statistical
n

X
i =1
i
formula, . Run the program using number as 5 and the various values of scores as
n
shown in the Table below. Write the result that the program will display in the Table
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.

Scores 25 55 75 35 85
Average

2. Modify the program so that it computes the sum of squares of the scores, using this
n

X
2
statistical formula, i .Write the result that the program will display in the Table
i =1

below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.

Scores 2 6 7 10 12

64
Sum of
Square

65

You might also like