Lesson 1: Getting Started
Activity 1: Find the Factors of 7 between 1 and 100 Using a while Loop
- Import all the required header files before the main function:
#include <iostream>
- Inside the main function, create a variable i of type unsigned, and initialize its value as 1:
unsigned i = 1;
- Now, use the while loop adding the logic where the value of i should be less than 100:
while ( i < 100){ }
- In the scope of the while loop, use the if statement with the following logic:
if (i%7 == 0) {
std::cout << i << std::endl;
}
- Increase the value of the i variable to iterate through the while loop to validate the condition:
i++;
The output of the program is as follows:
7
14
21
28
...
98
Activity 2: Define a Bi-Dimensional Array and Initialize Its Elements
- After creating a C++ file, include the following header file at the start of the program:
#include <iostream>
- Now, in the main function, create a bi-directional array named foo of type integer, with three rows and three columns, as shown here:
int main()
{
int foo[3][3];
- Now, we will use the concept of a nested for loop to iterate through each index entry of the foo array:
for (int x= 0; x < 3; x++){
for (int y = 0; y < 3; y++){
}
}
- In the second for loop, add the following statement:
foo[x][y] = x + y;
- Finally, iterate over the array again to print its values:
for (int x = 0; x < 3; x++){
for (int y = 0; y < 3; y++){
std::cout << “foo[“ << x << “][“ << y << “]: “ << foo[x][y] << std::endl;
}
}
The output is as follows:
foo[0][0]: 0
foo[0][1]: 1
foo[0][2]: 2
foo[1][0]: 1
foo[1][1]: 2
foo[1][2]: 3
foo[2][0]: 2
foo[2][1]: 3
foo[2][2]: 4