Let's Think About This For a Second
This lesson isn't new teaching content — it's a task set for practicing, hands-on, the variable, datatype, operator, if-else, loop, array, and string topics you learned in the Basic chapter. Try writing each task yourself without googling it — even if you hit errors, debugging is part of the learning process. Only after that, compare the reference solution in the code block against your own.
Exercises
Task 1: Store 5 integers in an array and use a loop to calculate the sum and average. Task 2: Read an integer age from the user and classify it with if-else as "Minor", "Adult", or "Senior" (under 18, 18-59, 60 and above). Task 3: Read a string from the user and manually count its length (character count) with a loop — don't use the .length() function. Task 4: Print only the even numbers from 1 to 50 using a for loop.
Example Code
#include <iostream>
#include <string>
using namespace std;
int main() {
// Task 1: sum & average
int nums[5] = {4, 8, 15, 16, 23};
int sum = 0;
for (int i = 0; i < 5; i++) sum += nums[i];
cout << "Sum: " << sum << ", Average: " << (double)sum / 5 << "\n";
// Task 2: age classify
int age;
cout << "Enter age: ";
cin >> age;
if (age < 18) cout << "Minor\n";
else if (age < 60) cout << "Adult\n";
else cout << "Senior\n";
// Task 3: manual string length
string text;
cout << "Enter text: ";
cin >> text;
int count = 0;
for (char c : text) count++;
cout << "Length: " << count << "\n";
// Task 4: even numbers 1-50
for (int i = 1; i <= 50; i++) {
if (i % 2 == 0) cout << i << " ";
}
cout << "\n";
return 0;
}Running Task 4 should print the even numbers from 2 4 6 8 up to 50, separated by spaces, all on one line.5-Minute Try It
Set a 5-minute timer and write the code for Task 1 through Task 4 yourself without looking at any reference — then compare it against the code above.
A Quick Word of Caution
Watch out for integer division — if you don't cast like (double)sum / 5, the average will always come out rounded to an integer.