PLD Notes - Mar 2023-24
PLD Notes - Mar 2023-24
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.
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,
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.
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.
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
// 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;
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 …”;
/*
/*
type variableName1, variableName2, …, variableNameN;
variableName1 = variableName2 = … = variableNameN = value;
*/
NOTE: use the const keyword to declare a constant (unchangeable and read-only)
Example,
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;
#include <iostream>
using namespace std;
#include <string> // Include the string library
main()
{
string fullName;
7
// also, use append() function to concatenate strings
// use append() function to copy a string to another empty string
Example,
z = x + y;
cout << z; // The output will be an integer (30)
However,
z = x + y;
cout << z; // The output will be a string “1020”
Example,
s2.swap(s1);
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>
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;
}
Example,
#include <iostream>
#include <string>
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>
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;
}
Example,
#include <iostream>
#include <string>
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>
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;
}
Example,
#include <iostream>
#include <string>
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,
// Or
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)
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.
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.
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.
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,
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,
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.
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.
#include <iostream>
#include <ctime>
int main()
{
int num, lower, upper;
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
}
/*
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 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,
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.
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].
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,
// 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”;
Example,
29
Change an Array Element
NOTE: To change the value of a specific element, refer to the index number
Example,
cars[0] = “Opel”;
cout << cars[0]; // Now outputs Opel instead of Volvo
Example,
Example,
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" }
};
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
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.
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.
#include <iostream>
#include <ctime>
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
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,
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;
}
Example,
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,
int main() {
int firstNum = 10;
int secondNum = 20;
return 0;
}
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>
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();
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>
int main()
{
string str = "hj;pq910js45";
int check;
int size = str.length();
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
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.
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.
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.
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,
int main() {
car myCar1; // Create a car structure and store it in myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
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)
cout << "the value is: " << myAge << "\n\n";
cout << *ptr << "\n\n";
return 0;
}
44