Structured Programming and C++
Structured Programming and C++
Objectives:
● Understand the principles of structured programming.
● Get acquainted with the C++ programming environment.
● Write and run a simple C++ program.
Structured programming is a programming paradigm that aims to improve the clarity, quality,
and development time of software by using structured control flow constructs such as
sequences, selections, and loops. It emphasizes:
Modularity: Breaking down programs into smaller, manageable functions or modules.
Control Flow: Using clear control structures like loops, conditionals, and subroutines.
TopDown Design: Designing programs from the top level down to the details.
Key Features:
● Object Oriented Programming: Supports classes and objects.
● Standard Library: Includes a rich set of functions for various operations.
● Performance: Provides high performance with lowlevel memory manipulation.
● Portability: Programs written in C++ can run on different platforms with minimal
changes.
To start programming in C++, you need an Integrated Development Environment (IDE) and a
C++ compiler. Popular IDEs include:
Visual Studio Code: A lightweight, crossplatform editor with C++ extensions.
Code::Blocks: A free C++ IDE.
CLion: A crossplatform IDE for C++ by JetBrains.
1. Open your IDE: Open the IDE you installed and create a new project.
2. Create a New File: Create a new file with a .cpp extension (e.g., main.cpp).
3. Write the Code: Enter the following code into your file:
cpp
include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
4. Compile and Run: Use the IDE's builtin tools to compile and run the program. You should see
the output Hello, World! in the console.
Code Explanation:
include <iostream>: Includes the InputOutput stream library.
int main(): The main function where execution starts.
std::cout << "Hello, World!" << std::endl;: Prints "Hello, World!" to the console.
return 0;: Indicates that the program ended successfully.
5. Homework
Task:
Install a C++ IDE and compiler on your system.
Write a basic "Hello, World!" program using the steps outlined above.
Experiment with modifying the message in the std::cout statement.
Example:
cpp
include <iostream>
int main() {
std::cout << ["Hello, = Your Name ] !" << std::endl;
return 0;
}
Summary
In this first week, you've been introduced to structured programming principles, learned about
the history and features of C++, set up your development environment, and written your first
C++ program. These foundational steps will set the stage for deeper exploration and learning in
the weeks to come.
Additional Resources
Documentation = (https://en.cppreference.com/w/)
= Learn C++ = (https://www.learncpp.com/)
= Visual Studio Code C++ Setup = (https://code.visualstudio.com/docs/languages/cpp)
End of Week 1
Constant Declaration:
cpp
const int MAX_AGE = 100; // Declare a constant integer
Examples:
cpp
int number = 10;
float temperature = 36.6f;
double distance = 12345.6789;
char letter = 'A';
bool isValid = true;
int main() {
std::cout << "Enter your name: ";
return 0;
}
int main() {
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}
5. Homework
Task:
1. Write a program that asks the user for their age and then prints a message displaying their
age.
2. Write a program that asks the user to input two numbers and then prints the sum, difference,
product, and quotient of those numbers.
Example 1:
cpp
include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old." << std::endl;
return 0;
}
Example 2:
cpp
include <iostream>
int main() {
double num1, num2;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
Deliverable:
Submit the source code of the programs and screenshots showing the program output.
Summary
In this second week, you learned about the basic syntax and structure of C++ programs, how to
declare and initialize variables and constants, the fundamental data types in C++, and how to
perform basic input and output operations. These concepts are essential building blocks for
more advanced topics in C++.
Additional Resources
End of Week 2
Objectives:
● Understand and use conditional statements in C++.
1. IfElse Statements
The ifelse statement allows you to execute certain sections of code based on whether a
condition is true or false.
Syntax:
cpp
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
cpp
include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number > 0) {
std::cout << "The number is positive." << std::endl;
} else {
std::cout << "The number is not positive." << std::endl;
}
return 0;
}
You can place an ifelse statement inside another ifelse statement to create nested conditions.
Syntax:
cpp
Example:
cpp
include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number > 0) {
if (number % 2 == 0) {
std::cout << "The number is positive and even." <<
std::endl;
} else {
std::cout << "The number is positive and odd." <<
std::endl;
}
} else {
std::cout << "The number is not positive." << std::endl;
}
return 0;
}
3. SwitchCase Statements
The switchcase statement allows you to choose between multiple options based on the value of
a variable.
Example:
cpp
include <iostream>
int main() {
int day;
std::cout << "Enter a day (17): ";
std::cin >> day;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
std::cout << "Thursday" << std::endl;
break;
case 5:
std::cout << "Friday" << std::endl;
return 0;
}
Key Points:
Break Statement: The break statement exits the switchcase structure. Without it, execution
continues to the next case.
Default Case: The default case is executed if none of the specified cases match.
4. Homework
Task 1:
Write a program that asks the user to enter their age and then prints whether they are a minor,
an adult, or a senior citizen.
Example:
cpp
include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
return 0;
}
Task 2:
Write a program that asks the user to enter a number between 1 and 12 and then prints the
corresponding month name using a switchcase statement.
Example:
cpp
include <iostream>
int main() {
int month;
std::cout << "Enter a month (112): ";
std::cin >> month;
switch (month) {
case 1:
std::cout << "January" << std::endl;
break;
case 2:
std::cout << "February" << std::endl;
break;
case 3:
std::cout << "March" << std::endl;
break;
case 4:
std::cout << "April" << std::endl;
break;
case 5:
std::cout << "May" << std::endl;
break;
case 6:
std::cout << "June" << std::endl;
break;
case 7:
std::cout << "July" << std::endl;
break;
return 0;
}
Deliverable:
Submit the source code of both programs and screenshots showing the program output.
Summary
In this third week, you learned about control structures in C++ with a focus on conditional
statements, including ifelse, nested ifelse, and switchcase statements. These constructs are
essential for decisionmaking in your programs.
Additional Resources
Conditional Statements =
(https://www.tutorialspoint.com/cplusplus/cpp_conditional_statements.htm)
IfElse = (https://www.w3schools.com/cpp/cpp_conditions.asp)
SwitchCase = (https://www.cplusplus.com/doc/tutorial/control/)
End of Week 3
Objectives:
● Learn and apply looping constructs in C++.
1. For Loop
The for loop is used to repeat a block of code a known number of times.
Syntax:
cpp
for (initialization; condition; increment) {
// Code to be executed
}
Example:
cpp
include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << "Iteration " << i << std::endl;
}
return 0;
}
Explanation:
Initialization: Sets the starting point.
Condition: The loop runs as long as this condition is true.
Increment: Updates the loop control variable.
2. While Loop
The while loop is used to repeat a block of code as long as a condition is true.
Syntax:
cpp
while (condition) {
Example:
cpp
include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << "Iteration " << i << std::endl;
++i;
}
return 0;
}
Explanation:
The loop condition is checked before executing the code block.
The loop runs as long as the condition is true.
3. DoWhile Loop
The dowhile loop is similar to the while loop, but it guarantees that the code block is
executed at least once.
Syntax:
cpp
do {
// Code to be executed
} while (condition);
Example:
cpp
include <iostream>
int main() {
int i = 1;
do {
Explanation:
The code block is executed once before the condition is checked.
Syntax:
cpp
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
std::cout << "Iteration " << i << std::endl;
}
Continue Statement: Skips the current iteration and moves to the next one.
Syntax:
cpp
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
continue; // Skip the rest of the loop body when i equals 5
}
std::cout << "Iteration " << i << std::endl;
}
5. Homework
Task 1:
Write a program that prints the numbers from 1 to 10 using a for loop.
Example:
cpp
include <iostream>
Tenibiaje Mobolaji Olufemi
Structured Programming and C++ study Manual
int main() {
for (int i = 1; i <= 10; ++i) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Task 2:
Write a program that asks the user for a number and then prints the factorial of that number
using a while loop.
Example:
cpp
include <iostream>
int main() {
int num, factorial = 1;
std::cout << "Enter a number: ";
std::cin >> num;
int i = 1;
while (i <= num) {
factorial *= i;
++i;
}
std::cout << "Factorial of " << num << " is " << factorial <<
std::endl;
return 0;
}
Task 3:
Write a program that prints the numbers from 1 to 10 but skips the number 5 using a dowhile
loop and the continue statement.
Example:
cpp
include <iostream>
int main() {
Deliverable:
Submit the source code of the programs and screenshots showing the program output.
Summary
In this fourth week, you learned about different looping constructs in C++, including the for loop,
while loop, and dowhile loop. You also learned how to use the break and continue statements to
control the flow of loops. These looping constructs are fundamental for performing repetitive
tasks in your programs.
Additional Resources
Loops = (https://www.tutorialspoint.com/cplusplus/cpp_loops.htm)
For Loop = (https://www.w3schools.com/cpp/cpp_for_loop.asp)
While Loop = (https://www.cplusplus.com/doc/tutorial/control/)
End of Week 4
Objectives:
● Understand the use of functions to modularize code.
● Learn how to define and call functions.
● Understand function parameters, return values, and variable scope.
● Explore inline functions and function overloading.
Definition: A function is a block of code designed to perform a particular task, defined with a
name, and executed when called.
Syntax:
cpp
returnType functionName(parameters) {
// Function body
return value; // Optional, depending on returnType
}
Example:
cpp
include <iostream>
void printMessage() {
std::cout << "Hello, this is a function!" << std::endl;
}
int main() {
printMessage(); // Calling the function
return 0;
}
Explanation:
void: The return type, indicating the function does not return a value.
printMessage: The name of the function.
() : Parentheses indicate the function can take parameters (none in this case).
int main() {
printSum(5, 3); // Passing arguments to the function
return 0;
}
int main() {
int result = add(5, 3); // Storing the return value
std::cout << "Sum: " << result << std::endl;
return 0;
}
Explanation:
int add(int a, int b): Function with parameters and an int return type.
return a + b;: Returns the sum of a and b.
3. Scope of Variables
Local Variables: Declared within a function and accessible only within that function.
Global Variables: Declared outside any function and accessible throughout the program.
Example:
void printGlobal() {
std::cout << "Global variable: " << globalVar << std::endl;
}
int main() {
int localVar = 5; // Local variable
std::cout << "Local variable: " << localVar << std::endl;
printGlobal();
return 0;
}
Explanation:
globalVar: A global variable accessible in both printGlobal and main.
localVar: A local variable accessible only within main.
Inline Functions: Functions defined with the inline keyword to suggest to the compiler to
insert the function’s body directly into the code.
Syntax:
cpp
inline int square(int x) {
return x * x;
}
Function Overloading: Multiple functions with the same name but different parameters.
Example:
cpp
include <iostream>
int main() {
std::cout << "Sum of integers: " << add(5, 3) << std::endl;
std::cout << "Sum of doubles: " << add(2.5, 3.1) << std::endl;
return 0;
}
Explanation:
Two add functions, one for int and one for double.
5. Homework
Task 1:
Write a program with a function that takes an integer as an argument and returns its factorial.
Example:
cpp
include <iostream>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "Factorial: " << factorial(num) << std::endl;
return 0;
}
Task 2:
Tenibiaje Mobolaji Olufemi
Structured Programming and C++ study Manual
Write a program with overloaded functions named calculate that can either add two integers
or concatenate two strings.
Example:
cpp
include <iostream>
include <string>
int main() {
std::cout << "Sum of integers: " << calculate(5, 3) << std::endl;
std::cout << "Concatenated strings: " << calculate("Hello, ",
"world!") << std::endl;
return 0;
}
Deliverable:
Submit the source code of both programs and screenshots showing the program output.
Summary
In this fifth week, you learned about functions in C++, including defining and calling functions,
using parameters and return values, understanding the scope of variables, and exploring inline
functions and function overloading. Functions help in modularizing code and improving
readability and reusability.
Additional Resources
Functions = (https://www.tutorialspoint.com/cplusplus/cpp_functions.htm)
Function Overloading = (https://www.w3schools.com/cpp/cpp_function_overloading.asp)
Variable Scope = (https://www.cplusplus.com/doc/tutorial/variables/)
End of Week 5
Objectives:
● Understand the concept and use of arrays in C++.
● Learn how to manipulate strings.
● Perform basic operations on arrays and strings.
1. Arrays
An array is a collection of elements of the same type stored in contiguous memory locations.
Syntax:
cpp
dataType arrayName = arraySize = ;
Example:
cpp
include <iostream>
int main() {
int numbers = 5 = = {1, 2, 3, 4, 5}; // Declare and initialize an
array
return 0;
}
Explanation:
int numbers = 5 = : Declares an array of integers with 5 elements.
{1, 2, 3, 4, 5}: Initializes the array with values.
2. Multidimensional Arrays
Example:
cpp
include <iostream>
int main() {
int matrix = 2 = = 3 = = {
{1, 2, 3},
{4, 5, 6}
};
return 0;
}
Explanation:
int matrix = 2 = = 3 = : Declares a 2x3 matrix.
{{1, 2, 3}, {4, 5, 6}}: Initializes the matrix with values.
3. Strings
Strings in C++ are sequences of characters. The string class in the C++ Standard Library
provides an easier way to handle strings.
int main() {
std::string greeting = "Hello, World!";
std::cout << greeting << std::endl;
// String concatenation
std::string firstName = "John";
std::string lastName = "Doe";
std::string fullName = firstName + " " + lastName;
std::cout << "Full Name: " << fullName << std::endl;
// String length
std::cout << "Length of greeting: " << greeting.length() <<
std::endl;
return 0;
}
Explanation:
std::string: Declares a string variable.
+: Concatenates two strings.
.length(): Returns the length of the string.
Array Operations:
Initialization:
cpp
int arr = 5 = = {1, 2, 3, 4, 5};
Accessing Elements:
cpp
int firstElement = arr = 0 = ;
String Operations:
Initialization:
cpp
std::string str = "Hello";
Accessing Characters:
cpp
char firstChar = str = 0 = ;
Modifying Characters:
cpp
str = 1 = = 'a';
Appending Strings:
cpp
str += " World";
Finding Substrings:
cpp
size_t pos = str.find("World");
5. Homework
Task 1:
Write a program that reads 5 integers into an array and then prints them in reverse order.
int main() {
int numbers = 5 = ;
return 0;
}
Task 2:
Write a program that reads a string from the user and prints its length and the string in reverse
order.
Example:
cpp
include <iostream>
include <string>
include <algorithm> // For std::reverse
int main() {
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input);
std::reverse(input.begin(), input.end());
std::cout << "Reversed string: " << input << std::endl;
Deliverable:
Submit the source code of both programs and screenshots showing the program output.
Summary
In this sixth week, you learned about arrays and strings in C++. Arrays are used to store
multiple values of the same type, while strings handle sequences of characters. You explored
various operations on arrays and strings, which are essential for data manipulation in C++.
Additional Resources
Arrays = (https://www.tutorialspoint.com/cplusplus/cpp_arrays.htm)
Strings = (https://www.cplusplus.com/doc/tutorial/strings/)
Multidimensional Arrays = (https://www.w3schools.com/cpp/cpp_arrays_multi.asp)
End of Week 6