0% found this document useful (0 votes)
14 views44 pages

PLD Notes - Mar 2023-24

Notes on programming logic and design
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)
14 views44 pages

PLD Notes - Mar 2023-24

Notes on programming logic and design
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/ 44

Introduction

When programmers begin a new project, they never jump right in and start writing code as the first step. They begin by
creating a design of the program. After designing the program, the programmer begins writing code in a high-level
language.

A language’s syntax rules dictate things such as how key words, operators, and punctuation characters can be used. A
syntax error occurs if the programmer violates any of these rules.

If the program contains a syntax error, or even a simple mistake such as a misspelled key word, the compiler or
interpreter will display an error message indicating what the error is.

Once the code is in an executable form, it is then tested to determine whether any logic errors exist. A logic error is a
mistake that does not prevent the program from running but causes it to produce incorrect results.

If there are logic errors, the programmer debugs the code. This means that the programmer finds and corrects the code
that is causing the error. Sometimes during this process, the programmer discovers that the original design must be
changed. This entire process, which is known as the program development cycle, is repeated until no errors can be found
in the program.

The process of designing a program:

- Understand the task that the program is to perform.


The programmer studies the information that was gathered from the customer during the interviews and creates a list of
different software requirements.
A software requirement is simply a single function that the program must perform to satisfy the customer. Once the
customer agrees that the list of requirements is complete, the programmer can move to the next phase.

1
- Determine the steps that must be taken to perform the task.
Once you understand the task that the program will perform, you begin by breaking down the task into a series of logical
steps (Algorithm) using Pseudo-code or Flowchart.

Pseudo-code:

NOTEs:
1. Pseudo-code (fake code) is an informal language that has no syntax rules and is not meant to be compiled or
executed.
2. Each statement in the pseudo-code represents an operation that can be performed in any high-level language.

Example,

// Pay Calculating Program

Display "Enter the number of hours the employee worked."


Input hours
Display "Enter the employee's hourly pay rate."
Input payRate
Set grossPay = hours * payRate
Display "The employee's gross pay is $", grossPay

Flowcharts:

NOTEs:
1. A flowchart is a diagram that graphically depicts the steps that take place in a program.
2. Each of these symbols represents a step in the program. The symbols are connected by arrows that represent the
“flow” of the program.

There are three types of symbols in the flowchart:

The ovals (terminal symbols); the Start terminal symbol marks the program’s starting point and the End terminal symbol
marks the program’s ending point.

The parallelograms; are used for both input symbols and output symbols.

The rectangles; are used as processing symbols.

2
Computer programs typically perform the following three-step process:

- Input is received
- Some process is performed on the input
- Output is produced

3
#include <iostream> // header file library that lets us work with input and output objects
using namespace std; // using namespace std means that we can use names for objects and variables from the
standard library

int main() // main() function. Any code inside it will be executed


{
// Code statements
return 0; // function returns 0
}

// Or

main()
{
// Code statements
}

NOTEs:
1. C++ programs must include necessary header file(s) from library
2. White space(s) is/are ignored
3. Every C++ statement ends with a semicolon ;
4. Single-line comments start with two forward slashes (//)
5. Multi-line comments start with /* and ends with */

4
NOTEs:
1. The cout object, together with the << operator, is used to output values/print text
2. Use cout << as many as needed. Texts will be inserted after each other (No new line)
3. To insert a new line, use the \n character. Or use << endl manipulator after text
4. To insert a blank line, use the \n\n character
5. To insert a tab, use \t
6. To insert a \, use \\
7. To insert a “, use \”

Example,

#include <iostream>
using namespace std;

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

#include <iostream>
using namespace std;

int main()
{
cout << "Hello World! \n";

// Or
// cout << “Hello World!” << endl;

cout << "I am learning C++";


return 0;
}

5
NOTEs:
1. Names can contain letters, digits and underscores
2. Names must begin with a letter or an underscore (_)
3. Names are case sensitive (myVar and myvar are different variables)
4. Names cannot contain whitespaces or special characters like !, #, %, etc.
5. Reserved words (like C++ keywords, such as int) cannot be used as names

int stores integers (whole numbers), without decimals, such as 123 or -123
float/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
To use strings, must include header file library <string>
bool stores values with two states: true or false

/*
type variableName = value; // Assign value if needed
*/

/*
cout << variableName;
cout << “Text … ” << variableName << “ Text …”;
/*

One Value to Multiple Variables


NOTE: Can assign the same value to multiple variables in one line

/*
type variableName1, variableName2, …, variableNameN;
variableName1 = variableName2 = … = variableNameN = value;
*/

NOTE: use the const keyword to declare a constant (unchangeable and read-only)

Example,

const int minutesPerHour = 60;


const float PI = 3.14;

6
NOTEs:
1. A string variable contains a collection of characters surrounded by double quotes
2. cin considers a space (whitespace, tabs, etc) as a terminating character. To overcome this issue, use getline (cin,
stringVarible) function to read a line of text

Example,

#include <iostream>
using namespace std;
#include <string> // Include the string library

main()
{
string firstName;

cout << "Type your first name: ";


cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
}

#include <iostream>
using namespace std;
#include <string> // Include the string library

main()
{
string fullName;

cout << "Type your full name: ";


getline(cin, fullName); // get user input from the keyboard
cout << "Your name is: " << fullName;
}

C++ String Concatenation


NOTE: The + operator can be used between strings to add them together to make a new string

string firstName = "John";


string lastName = "Doe";
string fullName = firstName + " " + lastName; // You can use “ “ or ‘ ‘
cout << fullName;

7
// also, use append() function to concatenate strings
// use append() function to copy a string to another empty string

string firstName = "John ";


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

NOTE: The + operator is used to add numbers and concatenate strings

Example,

int x = 10, y = 20, z;

z = x + y;
cout << z; // The output will be an integer (30)

However,

string x = "10", y = "20", z;

z = x + y;
cout << z; // The output will be a string “1020”

C++ String Swap


NOTE: use swap() to swap one string with another

Example,

string s1 = “Hello World”;


string s2 = “Hello The Gambia”;

cout << s1 << endl;


cout << s2 << endl;

s2.swap(s1);

cout << s1 << endl;


cout << s2 << endl;

8
C++ String Copy
NOTE: strcpy() function include the null character (\0). Also, make sure that the destination array >= to the source array

Example,

#include <iostream>

using namespace std;

int main() {
char source[] = "Hello, World!"; // source string
char destination[20]; // destination character array
strcpy(destination, source); // copy the source string to the destination
cout << "Source string: " << source << endl;
cout << "Copied string: " << destination << endl;
return 0;
}

C++ String Comparison


NOTE: use compare() function to compare two strings. The function returns 0 when they are equal or a +ve / -ve value
depending on comparison

Example,

#include <iostream>
#include <string>

using namespace std;

int main()
{
string str1 = "apple";
string str2 = "banana";
int result = str1.compare(str2);

if (result == 0) {
cout << "The strings are equal." << endl;
} else if (result < 0) {
cout << "The string str1 is less than str2." << endl;
} else {
cout << "The string str1 is greater than str2." << endl;
}
return 0;
}

9
C++ String Conversion to Integer or Double
NOTE: use stoi() function to convert a string to integer or stod() function to convert a string to double

Example,

#include <iostream>

using namespace std;

int main()
{
string str = "123";
string str1 = "3.14";
int num = stoi(str);
double num1 = stod(str1);
cout << num << endl;
cout << num1 << endl;

return 0;
}

C++ Numeric to String Conversion


NOTE: use to-string() function to convert a numeric value to string

Example,

#include <iostream>
#include <string>

using namespace std;

int main()
{
int num = 42;
double num1 = 223.14999; // check the output and number of digits after decimal point
string str = to_string(num);
string str1 = to_string(num1);
cout << str << endl;
cout << str1 << endl;

return 0;
}

10
C++ String Substring
NOTE: use substr(start, length) function to extract a sub-string. The first character in a string starts with 0.

Example,

#include <iostream>
#include <string>

using namespace std;

int main()
{
string str = "Hello, World!";
string substring = str.substr(7, 5); // Extracts "World" from the original string
cout << "The substring is: " << substring << endl;

return 0;
}

C++ String Replacement


NOTE use replace(start, end, string) function to replace a portion of a string with another string

Example,

#include <iostream>
#include <string>

using namespace std;

int main()
{
string str = "Hello, World!";
str.replace(7, 5, "Universe"); // Replaces the substring "World" with "Universe"
cout << str << endl;

return 0;
}

11
C++ String Length
NOTE: use the length() or size() function

Example,

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is: " << txt.length();

// Or

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


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

C++ Access Strings


Example,

string myString = "Hello";


myString[0] = 'J';
cout << myString;

12
NOTE: Use cin with >> operator to get user input

Example,

int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value

// Scientific Numbers
float f1 = 35e3; // float uses 4 bytes
double d1 = 12E4; // double uses 8 bytes
cout << f1;
cout << d1;

13
+ 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

= 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

== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

NOTE: Comparison operators are used to compare two values (or variables). The return value of a comparison is either
true (1) or false (0)

Example,

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

&& 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 true !(x < 5 && x < 10)

14
NOTEs:
1. #include <cmath> is required before using any of the following functions
2. The angles are in radians ((angleDegrees * PI) / 180)

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
exp(x) Returns the value of Ex
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
max(x, y) Returns the highest value of integer x and y
fmin(x, y) Returns the lowest value of a floating x and y
min(x, y) Returns the lowest value of integer 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)
tan(x) Returns the tangent of an angle
sqrt(x) Returns the square root of x
round(x) Returns the round of x
log(x) Returns the natural logarithm of x

Example,

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

main()
{
int x = 10, y = -20;

cout << fdim(x, y); // The output will be the positive difference (30)
}

15
Programming Exercises:
1. Personal Information
Design a C++ program that displays the following information:
• Your name
• Your address, village/town/city, region
• Your telephone number
• Your email address
• Your college major

2. Sales Prediction
A company has determined that its annual profit is typically 23 percent of total sales. Design a C++ program that asks the
user to enter the projected amount of total sales, and then displays the profit that will be made from that amount.
Hint: Use the value 0.23 to represent 23 percent.

3. Land Calculation
One hectare of land is equivalent to 10,000 square meters. Design a C++ program that asks the user to enter the total
square meters in a tract of land and calculates the number of hectares in the tract.
Hint: Divide the amount entered by 10,000 to get the number of hectares.

4. Total Purchase
A customer in a store is purchasing five items. Design a C++ program that asks for the price of each item, and then
displays the subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is 6 percent.

5. Distance Traveled
Assuming there are no accidents or delays, the distance that a car travels down the interstate can be calculated with the
following formula:
Distance = Speed × Time
A car is traveling at 60 miles per hour. Design a C++ program that displays the following:
- The distance the car will travel in 5 hours
- The distance the car will travel in 8 hours
- The distance the car will travel in 12 hours

6. Sales Tax
Design a C++ program that will ask the user to enter the amount of a purchase. The program should then compute the
VAT tax. The program should display the amount of the purchase, the VAT tax, and the total of the sale (which is the sum
of the amount of purchase plus the VAT tax).
Hint: Use the value 0.15 to represent 15%.

7. Area of a Circle
Design a C++ program that will ask the user to enter the radius of a circle. The program should then compute the area of
the circle and display the result.

8. Swap Two Numbers


Design a C++ program that asks the user to enter two numbers. The program should swap the numbers and display.

16
9. Celsius to Fahrenheit Temperature Converter
Design a C++ program that converts Celsius temperatures to Fahrenheit temperatures.
The formula is as follows:
F = (9/5)C + 32
The program should ask the user to enter a temperature in Celsius, and then display the temperature converted to
Fahrenheit.

10. Stock Transaction Program


Last month Joe purchased some stock in Acme Software, Inc. Here are the details of the purchase:
• The number of shares that Joe purchased was 1,000.
• When Joe purchased the stock, he paid $32.87 per share.
• Joe paid his stockbroker a commission that amounted to 2 percent of the amount he paid for the stock.

Two weeks later Joe sold the stock. Here are the details of the sale:
• The number of shares that Joe sold was 1,000.
• He sold the stock for $33.92 per share.
• He paid his stockbroker another commission that amounted to 2 percent of the amount he received for the stock.

Design a C++ program that displays the following information:


• The amount of money Joe paid for the stock.
• The amount of commission Joe paid his broker when he bought the stock.
• The amount that Joe sold the stock for.
• The amount of commission Joe paid his broker when he sold the stock.
• Did Joe make money or lose money? Display the amount of profit or loss after Joe sold the stock and paid his broker
(both times).

17
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

The if Statement
NOTE: Use the if statement to specify a block of code to be executed if a condition is true

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

Example,

int x = 20, y = 18;

if (x > y)
{
cout << "x is greater than y";
}

C++ else
/*
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
}
*/

18
C++ else if
NOTE: Use the else if statement to specify a new condition if the first condition is false

/*
if (condition1)
{
// block of code to be executed if condition1 is true
}
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.";
}

19
/*
switch(expression)
{
case x:
// code block
break; // break is optional. Used to save time in execution
case y:
// code block
break;
default: // default is optional. It specifies some code to run if there is no case match
// code block
}
*/

Example,

int day = 4;
switch (day)
{
case 1:
cout << "Monday";
break;
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;
default:
cout << “Error!”
}

20
Programming Exercises:
1. Roman Numerals
Design a C++ program that prompts the user to enter a number within the range of 1 through 10. The program should
display the Roman numeral version of that number. If the number is outside the range of 1 through 10, the program
should display an error message.

2. Areas of Rectangles
The area of a rectangle is the rectangle’s length times its width. Design a C++ program that asks for the length and width
of two rectangles. The program should tell the user which rectangle has the greater area, or whether the areas are the
same.

3. Check Two Integers – Part1


Design a C++ program to check two given integers, and return true if one of them is 30 or if their sum is 30.

4. Check Two Integers – Part2


Design a C++ program to check a given integer and return true if it is within 10 of 100 or 200.

5. Check Three Integers


Design a C++ program to check the largest number among three given integers.

6. Mass and Weight


Scientists measure an object’s mass in kilograms and its weight in Newtons. If you know the amount of mass of an
object, you can calculate its weight, in Newtons, with the following formula:
Weight = Mass × 9.8
Design a C++ program that asks the user to enter an object’s mass, and then calculates its weight. If the object weighs
more than 1,000 Newtons, display a message indicating that it is too heavy. If the object weighs less than 10 Newtons,
display a message indicating that it is too light.

7. Magic Dates
The date June 10, 1960, is special because when it is written in the following format, the month times the day equals the
year:
6/10/60
Design a C++ program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program
should then determine whether the month times the day equals the year. If so, it should display a message saying the
date is magic. Otherwise, it should display a message saying the date is not magic.

8. Color Mixer
The colors red, blue, and yellow are known as the primary colors because they cannot be made by mixing other colors.
When you mix two primary colors, you get a secondary color, as shown here:
- When you mix red and blue, you get purple.
- When you mix red and yellow, you get orange.
- When you mix blue and yellow, you get green.
Design a C++ program that prompts the user to enter the names of two primary colors to mix. If the user enters anything
other than “red,” “blue,” or “yellow,” the program should display an error message. Otherwise, the program should
display the name of the secondary color that results.

21
9. Book Club Points
Serendipity Booksellers has a book club that awards points to its customers based on the number of books purchased
each month. The points are awarded as follows:
• If a customer purchases 0 books, he or she earns 0 points.
• If a customer purchases 1 book, he or she earns 5 points.
• If a customer purchases 2 books, he or she earns 15 points.
• If a customer purchases 3 books, he or she earns 30 points.
• If a customer purchases 4 or more books, he or she earns 60 points.
Design a C++ program that asks the user to enter the number of books that he or she has purchased this month and
displays the number of points awarded.

10. Software Sales


A software company sells a package that retails for $99. Quantity discounts are given according to the following table:
Quantity Discount
10–19 20%
20–49 30%
50–99 40%
100 or more 50%
Design a C++ program that asks the user to enter the number of packages purchased. The program should then display
the amount of the discount (if any) and the total amount of the purchase after the discount.

11. Shipping Charges


The Fast Freight Shipping Company charges the following rates:
Weight of Package Rate per Pound
2 pounds or less $1.10
Over 2 pounds but not more than 6 pounds $2.20
Over 6 pounds but not more than 10 pounds $3.70
Over 10 pounds $3.80
Design a C++ program that asks the user to enter the weight of a package and then displays the shipping charges.

12. Body Mass Index Program Enhancement


The Body Mass Index (BMI) is often used to determine whether a person with a inactive lifestyle is overweight or
underweight for his or her height. A person’s BMI is calculated with the following formula:
BMI = Weight × 703 / Height^2
In the formula, weight is measured in pounds and height is measured in inches. Design a C++ program that asks the user
to enter the weight and height. The program should calculate the BMI and display a message indicating whether the
person has optimal weight, is underweight, or is overweight. An inactive person’s weight is considered to be optimal if
his or her BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered to be underweight. If the
BMI value is greater than 25, the person is considered to be overweight.

13. Time Calculator


Design a C++ program that asks the user to enter a number of seconds, and works as follows:
• There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the
program should display the number of minutes in that many seconds.
• There are 3,600 seconds in an hour. If the number of seconds entered by the user is greater than or equal to 3,600,
the program should display the number of hours in that many seconds.
• There are 86,400 seconds in a day. If the number of seconds entered by the user is greater than or equal to 86,400,
the program should display the number of days in that many seconds.
22
14. Rock / Paper / Scissors
Design a C++ program that lets the user play the game of Rock, Paper, Scissors against the computer. The program should
work as follows:
i. When the program begins, a random number in the range of 1 through 3 is generated. If the number is 1, then the
computer has chosen rock. If the number is 2, then the computer has chosen paper. If the number is 3, then the
computer has chosen scissors. (Don’t display the computer’s choice yet).
ii. The user enters his or her choice of “rock,” “paper,” or “scissors” at the keyboard.
iii. The computer’s choice is displayed.
iv. The program should display a message indicating whether the user or the computer was the winner.
A winner is selected according to the following rules:
• If one player chooses rock and the other player chooses scissors, then rock wins. (The rock smashes the scissors).
• If one player chooses scissors and the other player chooses paper, then scissors wins. (Scissors cut paper).
• If one player chooses paper and the other player chooses rock, then paper wins. (Paper wraps rock).
• If both players make the same choice, the game must be played again to determine the winner.
Hint:
/*
To generate a random number in C++

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
int num, lower, upper;

lower = 1; // value from 1 to 3


upper = 3;

srand(time(0)); // let's set the seed with unix timestamp


num = (rand() % ((upper - lower + 1))) + lower;
printf("%d", num, "\n");

return 0;
} */

23
NOTEs:
1. The while loop loops through a block of code as long as a specified condition is true
2. Initialize outside the loop to make condition true
3. Pre-Test the condition before executing the code
4. Inside the loop, have an option to change the condition to false (prevents infinite loop)

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

Example,

int i = 0; // initialize i to 0
while (i < 5) // Pre-Test the condition
{
cout << i << "\n";
i++; // Change the value
}

C++ do/while Loop


NOTEs:
1. The 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
2. Post-Test the condition
3. Inside the loop, have an option to change the condition to false (prevents infinite loop)

/*
do
{
// code block to be executed
}
while (condition); // Post-Test the condition
*/

24
NOTE: Use the for loop instead of a while loop when the number of looping through a block of code is known

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

Statement 1: sets a variable before the loop starts

Statement 2: defines the condition for the loop to run. If the condition is true, the loop will start over again, if it is false,
the loop will end.

Statement 3: increases / decreases a value each time the code block in the loop has been executed

Example,

for (int i = 0; i < 5; i++)


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

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


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

25
Nested Loops
NOTE: The "inner loop" will be executed one time for each iteration of the "outer loop"

Example,

// Outer loop
for (int i = 1; i <= 2; ++i)
{
cout << "Outer: " << i << "\n"; // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; ++j)
{
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}
}

26
1. Total of a Series of Numbers
Design a C++ program that asks the user to enter a positive integer number and calculates the total of the following
series of numbers: 1/n + 2/(n-1) + 3/(n-2) + 4/(n-3) + 5/(n-4) … + n/1
(Hint, if you enter 4 then the program will calculate the total of 1/4 + 2/3 + 3/2 + 4/1)

2. Calories Burned
Running on a particular treadmill you burn 3.9 calories per minute. Design a C++ program that uses a loop to display the
number of calories burned after 10, 15, 20, 25, and 30 minutes.

3. Sum of Numbers
Design a C++ program with a loop that asks the user to enter a series of positive numbers. The user should enter a
negative number to signal the end of the series. After all the positive numbers have been entered, the program should
display their sum.

4. Sum of a Series of Integers – Part1.


Design a C++ program to calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n). The output
should look like:
1*1 = 1
2*2 = 4
3*3 = 9

The sum of the above series is:

5. Sum of a Series of Integers – Part2.


Design a C++ program to calculate the series (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n). The output should
look like:
1=1
1+2 = 3
1+2+3 = 6

The sum of the above series is:

6. Right Angle Patter


Design a C++ program that makes a pattern such as a right-angle triangle using numbers that repeat.
1
22
333
4444
55555

nnnnn

7. Tuition Increase
At one college, the tuition for a full-time student is $6,000 per semester. It has been announced that the tuition will
increase by 2 percent each year for the next five years. Design a C++ program with a loop that displays the projected
semester tuition amount for the next five years.

27
8. Series of Integers
Design a C++ program to read a series of integers. The first integer is special, as it indicates how many more integers will
follow. The output of the program will be the calculated the sum and average of the integers [excluding the first integer].

9. Pennies for Pay


Design a C++ program that calculates the amount of money a person would earn over a period of time if his or her salary
is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the
user for the number of days. Display the total pay at the end of the period. The output should be displayed in a dollar
amount, not the number of pennies.

10. Largest and Smallest


Design a C++ program with a loop that lets the user enter a series of numbers. The user should enter –99 to signal the
end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers
entered.

11. First and Last


Design a C++ program that asks the user for a series of names (in no particular order). After the final person’s name has
been entered, the program should display the name that is first alphabetically and the name that is last alphabetically.
For example, if the user enters the names Kristin, Joel, Adam, Beth, Zeb, and Chris, the program would display Adam and
Zeb.

12. Pyramid
Design a C++ program to display a pattern like a pyramid.
1
22
333
4444
55555

28
NOTEs:
1. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value
2. Array indexes start with 0: [0] is the first element. [1] is the second element, etc. to SIZE-1

/*
DataType arrayName[SIZE];
*/

Example,

int myNum[3] = {10, 20, 30};

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

// Or

string cars[] = {"Volvo", "BMW", "Ford", "Mazda"}; // Omit the SIZE. The compiler will figure it out

// Or

string cars[4];

cars[0] = “Volvo”;
cars[1] = “BMW”;
cars[2] = “Ford”;
cars[3] = “Mazda”;

Access the Elements of an Array


NOTE: Access an array element by referring to the index number inside square brackets []

Example,

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

cout << cars[0]; // Outputs Volvo

29
Change an Array Element
NOTE: To change the value of a specific element, refer to the index number

Example,

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = “Opel”;
cout << cars[0]; // Now outputs Opel instead of Volvo

Loop Through an Array


NOTE: Use for loop to go through the elements of an array

Example,

string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

for (int i = 0; i < 5; i++) // The loop will be from 0 to 4 (SIZE-1)


{
cout << cars[i] << "\n";
}

C++ Array Size


NOTE: sizeof() operator returns the size of a type in bytes

Example,

int myNumbers[5] = {10, 20, 30, 40, 50}, getArrayLength;

getArrayLength = sizeof(myNumbers) / sizeof(int); //size of an integer is 4 bytes

for (int i = 0; i < getArrayLength; i++)


{
cout << myNumbers[i] << "\n";
}

30
C++ Multi-Dimensional Arrays
NOTEs:
1. A multi-dimensional array is an array of arrays
2. To declare a multi-dimensional array:
a. define the variable type
b. specify the name of the array followed by square brackets which specify how many elements the main array
has
c. followed by another set of square brackets which indicates how many elements the sub-arrays have

/*
DataType arrayName[SIZE][SIZE_subArray] ;
*/

Example,

string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};

string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

cout << letters[0][2]; // Outputs "C" – first row (0) and third column (2)

31
Loop Through a Multi-Dimensional Array
Example,

string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

for (int i = 0; i < 2; i++)


{
for (int j = 0; j < 4; j++)
{
cout << letters[i][j] << "\n";
}
}

string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};

for (int i = 0; i < 2; i++)


{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
cout << letters[i][j][k] << "\n";
}
}
}

32
Programming Exercises:
1. Total Sales
Design a C++ program that asks the user to enter a store’s sales for each day of the week. The amounts should be stored
in an array. Use a loop to calculate the total and average sales for the week and display the result.

2. Rainfall Statistics
Design a C++ program that lets the user enter the total rainfall for each of 12 months into an array. The program should
calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and
lowest amounts.

3. Number Analysis Program


Design a C++ program that asks the user to enter a series of 20 numbers. The program should store the numbers in an
array and then display the following data:
• The lowest number in the array
• The highest number in the array
• The total of the numbers in the array
• The average of the numbers in the array

4. Charge Account Validation


Design a C++ program that asks the user to enter a charge account number. The program should determine whether the
number is valid by comparing it to the following list of valid charge account numbers:
5658845 4520125 7895122 8777541 8451277 1302850
8080152 4562555 5552012 5050552 7825877 1250255
1005231 6545231 3852085 7576651 7881200 4581002
These numbers should be stored in an array. If the number is in the array, the program should display a message
indicating the number is valid. If the number is not in the array, the program should display a message indicating the
number is invalid.

5. Payroll
Design a C++ program that uses the following parallel arrays:
• empId: An array of seven Integers to hold employee identification numbers.
The array should be initialized with the following numbers:
56588 45201 78951 87775 84512 13028 75804
• hours: An array of seven Integers to hold the number of hours worked by each employee.
• payRate: An array of seven Reals to hold each employee’s hourly pay rate.
• wages: An array of seven Reals to hold each employee’s gross wages.
The program should relate the data in each array through the subscripts. For example, the number in element 0 of the
hours array should be the number of hours worked by the employee whose identification number is stored in element 0
of the empId array. That same employee’s pay rate should be stored in element 0 of the payRate array.
The program should display each employee number and ask the user to enter that employee’s hours and pay rate. It
should then calculate the gross wages for that employee (hours times pay rate), which should be stored in the wages
array. After the data has been entered for all the employees, the program should display each employee’s identification
number and gross wages.

33
6. Driver’s License Exam
The local driver’s license office has asked you to design a C++ program that grades the written portion of the driver’s
license exam. The exam has 20 multiple choice questions. Here are the correct answers:
1. B 6. A 11. B 16. C
2. D 7. B 12. C 17. C
3. A 8. A 13. D 18. B
4. A 9. C 14. A 19. D
5. C 10. D 15. D 20. A
Your program should store these correct answers in an array. (Store each question’s correct answer in an element of a
String array.) The program should ask the user to enter the student’s answers for each of the 20 questions, which should
be stored in another array. After the student’s answers have been entered, the program should display a message
indicating whether the student passed or failed the exam. (A student must correctly answer 15 of the 20 questions to
pass the exam.) It should then display the total number of correctly answered questions, and the total number of
incorrectly answered questions.

7. Lottery Number Generator


Design a C program that generates a 7-digit lottery number. The program should have an Integer array with 7 elements.
Write a loop that steps through the array, randomly generating a number in the range of 0 through 9 for each element.
Then write another loop that displays the contents of the array.
Hint:
/*
To generate a random number in C++

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
int num, lower, upper;

lower = 1; // Choose value – Depending on lottery, the numbers may vary from 1 to 50 or 1 to 70
upper = 3; // Choose value

srand(time(0)); // let's set the seed with unix timestamp


num = (rand() % ((upper - lower + 1))) + lower;
printf("%d", num, "\n");

return 0;
} */

8. Vowels
Design a C++ program that will randomly generate 50 alphabet letters into an array. After that, the program will output
the randomly generated alphabet letters followed by the number of vowels a, e, i, o, u on the next line.
Hint: The ASCII values for A-Z are 65-90

34
9. Tic-Tac-Toe Game
Design a C++ program that allows two players to play a game of tic-tac-toe. Use a two-dimensional String array with
three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The
program should run a loop that does the following:
a. Displays the contents of the board array.
b. Allows player 1 to select a location on the board for an X. The program should ask the user to enter the row and
column number.
c. Allows player 2 to select a location on the board for an O. The program should ask the user to enter the row and
column number.
d. Determines whether a player has won or if a tie has occurred. If a player has won, the program should declare that
player the winner and end. If a tie has occurred, the program should say so and end.
e. Player 1 wins when there are three Xs in a row on the game board. Player 2 wins when there are three Os in a row on
the game board. The winning Xs or Os can appear in a row, in a column, or diagonally across the board. A tie occurs when
all of the locations on the board are full, but there is no winner.

35
NOTEs:
1. A function is a block of code which only runs when it is called
2. Functions are declared before they are called (above the function that calls them)
3. Functions can either return values or not. Functions that do not return values start with void. Function that return
values start with the data type that they return
4. Information can be passed to functions as a parameter. Parameters act as variables inside the function

/*
void myFunction() {
// code to be executed
}
*/

/*
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
*/

/*
DataType myFunction() {
// code to be executed
return result;
}
*/

Example,

void myFunction(string fname) {


cout << fname << "\n";
}

int main() {
myFunction("John");
myFunction("Mike");
myFunction("Mariam");
return 0;
}

36
int myFunction(int x, int y) {
return x + y;
}

int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}

Function with Default Parameter Value


NOTE: Use default value when expecting that the function might be called without an argument

Example,

void myFunction(string country = "Norway") {


cout << country << "\n";
}

int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}

Pass By Reference
NOTE: Use pass by reference if the value(s) of argument(s) might be changed

Example,

void swapNums(int &x, int &y) {


int z = x;
x = y;
y = z;
}

int main() {
int firstNum = 10;
int secondNum = 20;

cout << "Before swap: " << "\n";


cout << firstNum << secondNum << "\n";
37
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);

cout << "After swap: " << "\n";


cout << firstNum << secondNum << "\n";

return 0;
}

Pass Arrays as Function Parameters


Example,

void myFunction(int myNumbers[5]) {


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

int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}

38
C++ Character Functions
NOTE: include cctype library to use the following functions

// use isalpha() function to check if the given character is an alphabet or not. The function returns non-zero if the
character is an alphabet, otherwise returns zero

Example,

#include <iostream>
#include <cctype>

using namespace std;

int main()
{
int result = isalpha('7'); // check if '7' is an alphabet
cout << result;

return 0;
}

// use isblank() function to check if the given character is blank or not. The function returns non-zero value if the
character is a blank character, otherwise returns zero

Example,

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

int main() {
string str = " Hello, I am here. ";
int count = 0;
int size = str.length();

for (int i=0; i<size; i++)


{
if (isblank(str[i]))
count ++;
}
cout << "Number of blank characters: " << count << endl;
return 0;
}

39
// use isdigit() function to check if the given character is a digit or not. The function returns non-zero value if the
character is a digit, otherwise returns zero

Example,

#include <cctype>
#include <iostream>
#include <string>

using namespace std;

int main()
{
string str = "hj;pq910js45";
int check;
int size = str.length();

cout << "The digit in the string are:" << endl;


cout << size << "\n\n\n";

for (int i = 0; i < size; i++)


{

check = isdigit(str[i]);

if (check)
cout << str[i] << endl;
}

return 0;
}

// use islower() or isupper() functions are used to check if the given character is a lowercase or uppercase. The functions
return non-zero values if the character is lower or upper, respectively; otherwise return zero

// use tolower() or toupper() functions to convert a character to lowercase or uppercase, respectively.

40
Programming Exercises:
1. Kilometer Converter
Design a C++ modular program that asks the user to enter a distance in kilometers, and then converts that distance to
miles. The conversion formula is as follows:
Miles = Kilometers × 0.6214

2. Property Tax
A county collects property taxes on the assessment value of property, which is 60 percent of the property’s actual value.
For example, if an acre of land is valued at $10,000, its assessment value is $6,000. The property tax is then 64¢ for each
$100 of the assessment value. The tax for the acre assessed at $6,000 will be $38.40. Design a C++ modular program that
asks for the actual value of a piece of property and displays the assessment value and property tax.

3. Calories from Fat and Carbohydrates


A nutritionist who works for a fitness club helps members by evaluating their diets. As part of her evaluation, she asks
members for the number of fat grams and carbohydrate grams that they consumed in a day. Then, she calculates the
number of calories that result from the fat, using the following formula:
Calories from Fat = Fat Grams × 9
Next, she calculates the number of calories that result from the carbohydrates,
using the following formula:
Calories from Carbs = Carb Grams × 4
The nutritionist asks you to design a C++ modular program that will make these calculations.

4. Paint Job Estimator


A painting company has determined that for every 115 square feet of wall space, one gallon of paint and eight hours of
labor will be required. The company charges $20.00 per hour for labor. Design a C++ modular program that asks the user
to enter the square feet of wall space to be painted and the price of the paint per gallon. The program should display the
following data:
- The number of gallons of paint required
- The hours of labor required
- The cost of the paint
- The labor charges
- The total cost of the paint job

5. Feet to Inches
One foot equals 12 inches. Design a C program with function named feetToInches that accepts a
number of feet as an argument, and returns the number of inches in that many feet. Use the function in a program that
prompts the user to enter a number of feet and then displays the number of inches in that many feet.

6. Falling Distance
When an object is falling because of gravity, the following formula can be used to determine the distance the object falls
in a specific time period:
d = 1/2gt^2
The variables in the formula are as follows: d is the distance in meters, g is 9.8, and t is the amount of time, in seconds,
that the object has been falling. Design a C function named fallingDistance that accepts an object’s falling time (in
seconds) as an argument. The function should return the distance, in meters, that the object has fallen during that time
interval. Design a C program that calls the function in a loop that passes the values 1 through 10 as arguments and
displays the return value.
41
7. Kinetic Energy
In physics, an object that is in motion is said to have kinetic energy. The following formula can be used to determine a
moving object’s kinetic energy:
ke = 1/2mv^2
The variables in the formula are as follows: KE is the kinetic energy, m is the object’s mass in kilograms, and v is the
object’s velocity, in meters per second. Design a C++ function named kineticEnergy that accepts an object’s mass (in
kilograms) and velocity (in meters per second) as arguments. The function should return the amount of kinetic energy
that the object has. Design a C++ program that asks the user to enter values for mass and velocity, and then calls the
kineticEnergy function to get the object’s kinetic energy.

8. Test Average and Grade


Write a C++ program that asks the user to enter five test scores. The program should display a letter grade for each score
and the average test score. Design the following functions in the program:
- calcAverage – This function should accept five test scores as arguments and return the average of the scores.
- determineGrade – This function should accept a test score as an argument and return a letter grade for the score (as
a String), based on the following grading scale:
Score Letter Grade
90–100 A
80–89 B
70–79 C
60–69 D
Below 60 F

9. Prime Numbers
A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it
can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3,
and 6. Design a C++ Boolean function named isPrime, which takes an integer as an argument and returns True if the
argument is a prime number, or False otherwise. Use the function in a C program that prompts the user to enter a
number and then displays a message indicating whether the number is prime.

10. Capitalize the first word


Design a C++ program to capitalize the first letter of each word in a given string. Words must be separated by only one
space.

11. Count the word


Design a C++ program to count all the words in a given string.

12. Change the case


Design a C++ program to change the case (lower to upper and upper to lower cases) of each character in a given string.

13. Remove non-alphanumeric


Design a C++ program to remove all non-alphanumeric characters from a given string.

42
NOTEs:
1. Structures (also called structs) are a way to group several related variables into one place. Each variable in the
structure is known as a member of the structure
2. Unlike an array, a structure can contain many different data types (int, string, bool, etc.)

/*
struct myStructure { // Structure declaration and name
DataType myVar1; // Member
DataType myVar2; // Member
DataType myVar3; // Member
};
*/

Example,

// Declare a structure named "car"


struct car {
string brand;
string model;
int year;
};

int main() {
car myCar1; // Create a car structure and store it in myCar1;

myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;

car myCar2; // Create another car structure and store it in myCar2;

myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;

// Print the structure members


cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";

return 0;
}

43
NOTEs:
1. When a variable is created in C++, a memory address is assigned to the variable (where a value is stored)
2. To access the memory address, use &variableName
3. The memory address is in hexadecimal form (0x..) depending on the computer used
4. A pointer is a variable that stores the memory address as its value

Example,

#include <iostream>
using namespace std;

int main()
{
int myAge = 43;
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge

cout << "the value is: " << myAge << "\n\n";
cout << "the memory address is: " << &myAge << "\n\n"; // Outputs the memory address in hexadecimal

cout << ptr << "\n\n"; // Outputs the memory address in hexadecimal
cout << *ptr << "\n\n"; // Outputs the value of myAge with the pointer (43)

*ptr = 55; // Change the value of the pointer

cout << "the value is: " << myAge << "\n\n";
cout << *ptr << "\n\n";

return 0;
}

44

You might also like