EEB 334 LAB 02 COMPUTER PROGRAMMING
NAME: NONOFO
SURNAME: SEOKOLO
STUDENT ID: 202305350
INTRODUCTION
This lab2 on Computer programming introduces fundamental programming concepts in C++
focusing mainly on operators, variables, control structures, and data containers. The aim of the
lab is to build a foundation in structured programming by learning how to declare and
manipulate variables of different types, to perform arithmetic operations, and to apply order of
precedence in expressions. We also explore the use of conditional statements and looping
constructs as mechanisms for controlling program flow.
Beyond basic operations, the lab extends into modern C++ data structures such as vectors,
tuples, and maps, which allow efficient storage, retrieval, and manipulation of data. This
requires implementing real-world examples such as processing lists, iterating through data sets,
and managing key value pairs, thereby reinforcing abstract programming concepts with hands-
on applications. By the end of the laboratory, we should be able to write simple but structured
C++ programs that incorporate variables, arithmetic, decision-making, loops, and collections,
providing a strong basis for more advanced programming topics.
Objectives
1. Declare and initialize variables using int, float, and string data types.
2. Use cout to display text and variable values to the console.
3. Perform basic arithmetic operations and understand order of precedence.
4. Use single-line and multi-line comments for code documentation.
5. Create and manipulate arrays and vectors.
6. Work with tuples and maps to store and retrieve multiple values.
7. Apply if, else if, and else statements to control program logic.
8. Use logical and comparison operators for decision-making.
9. Construct for and while loops for iteration.
10. Use break and continue within loops to control flow
Materials used
• A computer with the Code::Blocks IDE installed (with C++ compiler).
• A C++ development environment (SNU GCC or MSVC).
• Internet access (optional, for documentation and troubleshooting).
• A text editor (Notepad++, VSCode, or built-in Code::Blocks editor).
• Pen and notebook for planning, sketching logic, or taking notes.
QUESTIONS
1. How do you declare and initialize int, float, and string variables in C++?
int age = 20; // integer
float height = 5.9; // floating point
string name = "Joe”; // string
2. How do you output a single variable using cout?
cout << age;
3. How do you output multiple variables in one line?
You chain them together using the stream insertion operator <<
cout << name << " is " << age << " years old and " << height << " feet tall.";
4. How can you store the result of an arithmetic expression into a new variable?
You declare a new variable and assign it the value of the expression
int x = 10;
int y = 5;
int sum = x + y; // store the result of x+y into sum
5. If you reassign a value to an existing variable, how does it affect previous results?
Reassigning changes the value stored in the variable, but it does not affect past calculations
that used the old value.
int num = 5;
cout << num + 1; // prints 6
num = 10; // reassignment
cout << num + 1; // now prints 11 (not affected)
6. How do you perform addition, subtraction, multiplication, and division in C++?
int a = 10, b = 3;
cout << a + b; // 13 (addition)
cout << a - b; // 7 (subtraction)
cout << a * b; // 30 (multiplication)
cout << a / b; // 3 (integer division)
7. How is the modulus (%) operator used in C++?
The modulus operator gives the remainder after integer division.
int a = 10, b = 3;
cout << a % b; // 1 (since 10 ÷ 3 = 3 remainder 1)
8. How do you compute exponents in C++?
C++ doesn’t have a built-in operator for powers; instead, use the pow() function from like
below
#include <cmath>
cout << pow(2, 3); // 8 (which is 2 raised to 3)
9. What happens when you divide two integers in C++?
If both operands are integers, the result is integer division (fractional part is discarded).
cout << 7 / 2; // 3, not 3.5
10. How does C++ handle order of operations in complex arithmetic expressions?
C++ follows the standard precedence rules:
Parentheses () have highest precedence.
Then exponents (pow() when used).
Then multiplication *, division /, modulus %.
Finally addition + and subtraction -.
Operators with the same precedence are evaluated left to right.
int result = 2 + 3 * 4; // = 14 (not 20, since * before +)
int result2 = (2 + 3) * 4; // = 20
11. How can you override precedence using parentheses?
Wrap the part of the expression you want computed first in ().
int result = (10 - 2) * (5 + 3); // = 8 * 8 = 64
12. How do you write a single-line comment in C++?
Use // before the comment.
// This is a single-line comment
13. How do you print a simple string to the console?
Use cout with the string in quotes.
cout << "Hello, World!";
14. How can you print a multiline block of text using raw string literals?
Use R"( ... )" syntax for raw string literals.
cout << R"(This is line one
This is line two
This is line three)";
15. How do you escape a double quote (") inside a string?
Use a backslash \"
cout << "She said, \"Hello!\"";
16. How can you concatenate two or more strings in a cout statement?
Use the << operator to join outputs, or + to combine string variables.
string first = "Hello";
string second = "World";
cout << first + " " + second; // using +
cout << first << " " << second; // using <<
17. How do you print without a newline at the end of the line?
By default, cout does not add a newline unless you use endl or \n
cout << "Hello"; // no newline, next output continues on same line
18. How can you repeat printing an empty line five times using a loop?
Use a loop that prints cout << endl; five times.
for (int counter = 0; counter < 5; counter++) {
cout << endl;
19. How do you declare a vector of strings in C++?
#include <vector>
#include <string>
using namespace std;
vector<string> words; // empty vector of strings
vector<string> fruits = {"Apple", "Banana", "Mango"}; // initialized vector
20. How do you access the second element of a vector?
(Remember: indexing starts at 0)
cout << fruits[1]; // prints "Banana"
21. How do you modify an item at a specific index?
fruits[0] = "Orange"; // changes first element from "Apple" to "Orange"
22. How do you print all elements in a vector?
for (int i = 0; i < [Link](); i++) {
cout << fruits[i] << endl;
}
Or using a range-based loop:
for (string f : fruits) {
cout << f << endl;
23. How do you print a sublist or a range of items from a vector?
for (int i = 1; i < 3; i++) { // prints elements at index 1 and 2
cout << fruits[i] << endl;
24. How do you append a new item to the end of a vector?
fruits.push_back("Pineapple");
25. How do you insert an item at a specific position in a vector?
[Link]([Link]() + 1, "Kiwi"); // inserts at index 1
26. How do you remove an item at a specific index?
[Link]([Link]() + 2); // removes the item at index 2
3.1 How can you remove the string "Potatoes" from the grocery list?
Given:
vector<string> grocery_list = {"Juice", "Tomatoes", "Potatoes", "Bananas"};
grocery_list.erase(grocery_list.begin() + 2); // index of "Potatoes" is 2
3.2 How can you sort the grocery list in alphabetical order?
#include <algorithm>
sort(grocery_list.begin(), grocery_list.end());
3.3 How can you reverse sort the grocery list?
sort(grocery_list.rbegin(), grocery_list.rend()); // descending order
27. How do you declare a tuple in C++ with multiple integer values?
#include <tuple>
tuple<int, int, int> numbers(10, 20, 30);
28. How do you access values from a tuple using get<index>()?
cout << get<0>(numbers); // prints 10
cout << get<1>(numbers); // prints 20
29. How do you manually convert a tuple into a vector?
vector<int> v = {1, 2, 3};
tuple<int, int, int> t(v[0], v[1], v[2]);
30. How do you convert a vector back into a tuple?
(Manually assign elements from vector into tuple)
vector<int> v = {1, 2, 3};
tuple<int, int, int> t(v[0], v[1], v[2]);
4.1 How can you convert the grocery list (vector) into a tuple in C++?
vector<string> grocery_list = {"Juice", "Tomatoes", "Potatoes", "Bananas"};
auto grocery_tuple = make_tuple(grocery_list[0], grocery_list[1], grocery_list[2],
grocery_list[3]);
31. How do you declare a map with string keys and string values?
#include <map>
map<string, string> dictionary;
32. How do you access a value in a map using its key?
dictionary["Apple"] = "A fruit";
cout << dictionary["Apple"]; // prints "A fruit"
33. How do you find the number of key-value pairs in the map?
cout << [Link]();
34. How do you retrieve all the keys in a map?
for (auto const& pair : dictionary) {
cout << [Link] << endl; // prints keys
}
35. How do you retrieve all the values in a map?
for (auto const& pair : dictionary) {
cout << [Link] << endl; // prints values
}
36. How do you print all key-value pairs using a for loop?
for (auto const& pair : dictionary) {
cout << [Link] << " : " << [Link] << endl;
5.1 How do you delete the "Fiddler" entry and its associated value from the dictionary?
given:
map<string, string> super_villains = {
{"Fiddler", "Isaac Bowin"},
{"Captain Cold", "Leonard Snart"},
{"Weather Wizard", "Mark Mardon"},
{"Mirror Master", "Sam Scudder"},
{"Pied Piper", "Thomas Peterson"}
};
super_villains.erase("Fiddler");
5.2 How do you replace the value for "Pied Piper" with "Hartley Rathaway"?
super_villains["Pied Piper"] = "Hartley Rathaway";
37. How do you use an if statement to evaluate a condition?
int x = 10;
if (x > 5) {
cout << "x is greater than 5";
}
38. How do you use if...else to check alternative outcomes?
The else clause provides a block of code to execute if the if condition is false.
if (x % 2 == 0) {
cout << "Even";
} else {
cout << "Odd";
39. How do you use if...else if...else to check multiple conditions?
int score = 85;
if (score >= 90) {
cout << "Grade A";
} else if (score >= 75) {
cout << "Grade B";
} else if (score >= 60) {
cout << "Grade C";
} else {
cout << "Fail";
}
40. What are the comparison operators used in C++?
== : equal to
!= : not equal to
< : less than
> : greater than
<= : less than or equal to
>= : greater than or equal to
41. What are the logical operators used in C++?
&& : logical AND
|| : logical OR
! : logical NOT
Eg,
if (x > 0 && x < 100) {
cout << "x is between 1 and 99";
42. How do you write a for loop that prints numbers from 0 to 9?
for (int counter = 0; counter < 10; counter++) {
cout << i << " ";
43. How do you use a for loop to iterate through a vector of strings?
vector<string> names = {"Alice", "Bob", "Charlie"};
for (int i = 0; i < [Link](); i++) {
cout << names[i] << endl;
}
44. How do you use a for loop to iterate through a custom list of numbers?
vector<string> names = {"Alice", "Bob", "Charlie"};
for (int i = 0; i < [Link](); i++) {
cout << names[i] << endl;
or
for (string n : names) {
cout << n << endl;
45. How do you create a nested for loop to traverse a 2D array?
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
46. How do you use while to repeatedly generate and print a random number until
15 is generated?
#include <cstdlib>
#include <ctime>
srand(time(0));
int num;
while (true) {
num = rand() % 20 + 1; // random between 1–20
cout << num << endl;
if (num == 15) break;
47. How do you print only even numbers between 0 and 20 using a while loop?
int counter = 0;
while (i <= 20) {
cout << i << " ";
i += 2;
48. How do break and continue work in a while loop?
break; → exits the loop immediately.
continue; → skips the rest of the loop body and goes to the next iteration.
int i = 0;
while (i< 10) {
i++;
if (i== 5) continue; // skip printing 5
if (i == 8) break; // stop loop when i=8
cout << i << " ";
}
49. How do you increment an iterator inside a while loop?
int counter = 0;
while (i < 5) {
cout << i<< endl;
i++; // increment inside loop
7.1 Convert the following Python while loop into a for loop in C++:
x=1
while x < 10:
print x,
x += 1
for (int x = 1; x < 10; x++) {
cout << x << endl;
7.2 Convert the following Python for loop into a while loop in C++:
for i in range(1,50):
print i,
int i = 1;
while (i < 50) {
cout << i << endl;
i++;
}
DISCUSSION
This laboratory exercise provided a step-by-step introduction to C++ fundamentals
through 50 structured programming questions. The first sections was more focused on
variables, literals, arithmetic expressions, and assignment operators, which are the
building blocks of every program. For example, students practiced declaring variables of
different types, applying shorthand operators, and understanding precedence in
arithmetic operations. These exercises demonstrated how C++ manages data and
executes instructions, showing more of the importance of precision in both syntax and
logic (Savitch, 2011). The integration of Boolean logic, relational operators, and
conditional branching using if, if-else, and nested statements illustrated how programs
make decisions, enabling dynamic responses to different inputs (Deitel & Deitel, 2017).
The lab then explored flow control through loops (while, do-while, and for, which allow
repetition of tasks and efficient handling of iterative problems. Students also engaged
with higher-level data structures, including vectors, tuples, and maps, which are vital for
managing collections of data in real-world applications such as databases and
inventories (Stroustrup, 2013). These exercises highlighted how simple constructs scale
up to solve more complex computational tasks. By combining algorithms, pseudocode
and flowcharts and c++ coding, the lab bridged problem-solving strategies with practical
implementation, reinforcing the ability to write structured and efficient C++ programs
(McCoy, 2015).
CONCLUSION
This laboratory improved understanding of C++ basics by combining variables, operators,
branching, loops, and data structures into practical problem-solving exercises. It
strengthened both theoretical knowledge and coding skills also for preparing students
for more advanced programming tasks.
REFERENCES
Deitel, P., & Deitel, H. (2017). C++ How to Program (10th ed.). Pearson.
McCoy, J. (2015). Introduction to Computer Programming with C++. University of
Delaware.
Savitch, W. (2011). Problem Solving with C++: The Object of Programming (8th ed.).
Addison-Wesley.
Stroustrup, B. (2013). The C++ Programming Language (4th ed.). Addison-Wesley.