0% found this document useful (0 votes)
2 views21 pages

104 - Array Practice - Loops and Array Comprehensive Practice

This lesson focuses on using simple loops with arrays in C++ to solve basic problems, including filling arrays, processing data for sums and averages, and creating visual patterns. It provides practical examples such as counting stickers, generating number sequences, and analyzing test scores. Key takeaways include understanding basic loop patterns, simple math applications in programming, and the use of nested loops.

Uploaded by

haiconnie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

104 - Array Practice - Loops and Array Comprehensive Practice

This lesson focuses on using simple loops with arrays in C++ to solve basic problems, including filling arrays, processing data for sums and averages, and creating visual patterns. It provides practical examples such as counting stickers, generating number sequences, and analyzing test scores. Key takeaways include understanding basic loop patterns, simple math applications in programming, and the use of nested loops.

Uploaded by

haiconnie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

C++ Programming Lesson 105: Array Practice - Simple Loops

and Array Exercises


📚 Learning Objectives
By the end of this lesson, you will be able to:

Use simple loops with arrays to solve basic problems

Fill arrays with patterns and sequences


Process arrays to find sums, averages, and counts

Create simple visual patterns using loops and arrays

Apply basic math concepts through programming

🌟 Introduction: Why Practice with Simple Examples?


Real-Life Examples for Kids!
Example 1: Counting Your Stickers You have a sticker collection with different numbers each day:

Monday: 5 stickers
Tuesday: 8 stickers

Wednesday: 3 stickers
Thursday: 7 stickers
Friday: 6 stickers

Questions: How many total? What's the average per day? Which day had the most?

Example 2: Making a Simple Pattern Drawing stars in rows:


*
**
***
****
*****

Example 3: Test Scores in Your Class Your class has 10 students with test scores. You want to:

Find the highest score


Count how many students passed (score ≥ 70)

Calculate the class average

These are perfect for practicing loops with arrays!

💻 Simple Examples (Perfect for Beginners)


Example 1: Number Sequence Generator (Very Easy)
Problem: Create arrays with different number patterns. Real-life: Like counting by 2s, 5s, or 10s in
math class.

SECTION A: Creating Even Numbers Purpose: Fill an array with even numbers: 2, 4, 6, 8, 10...
cpp

#include <iostream>
using namespace std;

int main() {
cout << "=== Even Numbers Generator ===" << endl;

int evenNumbers[10]; // Array to store 10 even numbers

// Fill array with even numbers


for (int i = 0; i < 10; i++) {
evenNumbers[i] = (i + 1) * 2; // 1*2=2, 2*2=4, 3*2=6, etc.
}

// Display the even numbers


cout << "First 10 even numbers: ";
for (int i = 0; i < 10; i++) {
cout << evenNumbers[i] << " ";
}
cout << endl;

return 0;
}

What this does:

Makes an array that holds 10 numbers

Uses a loop to fill it with even numbers (2, 4, 6, 8...)

Uses another loop to print all the numbers


SECTION B: Creating Times Table Purpose: Make a times table (like 5 × 1 = 5, 5 × 2 = 10...)

cpp

int main() {
cout << "=== Times Table Generator ===" << endl;

int timesTable[10];
int multiplyBy = 5; // Let's do the 5 times table

// Fill array with 5 times table


cout << "The " << multiplyBy << " times table:" << endl;
for (int i = 0; i < 10; i++) {
timesTable[i] = multiplyBy * (i + 1); // 5×1, 5×2, 5×3, etc.
cout << multiplyBy << " × " << (i + 1) << " = " << timesTable[i] << endl;
}

return 0;
}

SECTION C: Sum of Number Sequence Purpose: Add up all numbers in our array
cpp

int main() {
cout << "=== Adding Up Numbers ===" << endl;

int numbers[5] = {10, 20, 30, 40, 50};


int sum = 0;

// Add up all numbers


cout << "Numbers: ";
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
sum = sum + numbers[i]; // Keep adding to sum
}
cout << endl;

cout << "Total sum: " << sum << endl;


cout << "Average: " << sum / 5 << endl;

return 0;
}

What you learned:

How to fill arrays with patterns (even numbers, times tables)

How to add up all numbers in an array


How to calculate averages

Example 2: Simple Star Patterns (Easy)


Problem: Draw different star patterns using loops. Real-life: Like making decorations or art
patterns.

SECTION A: Growing Star Pattern Purpose: Make a triangle of stars

cpp

#include <iostream>
using namespace std;

int main() {
cout << "=== Growing Star Pattern ===" << endl;

int height = 5; // 5 rows of stars

// Each row has more stars than the previous


for (int row = 1; row <= height; row++) {

// Print stars for this row


for (int star = 1; star <= row; star++) {
cout << "* ";
}

cout << endl; // Go to next line


}

return 0;
}

Output:
*
* *
* * *
* * * *
* * * * *

SECTION B: Number Triangle Purpose: Make a triangle with numbers instead of stars

cpp

int main() {
cout << "=== Number Triangle ===" << endl;

int height = 4;

for (int row = 1; row <= height; row++) {

// Print numbers for this row


for (int num = 1; num <= row; num++) {
cout << num << " ";
}

cout << endl;


}

return 0;
}

Output:
1
1 2
1 2 3
1 2 3 4

SECTION C: Simple Rectangle Pattern Purpose: Make a rectangle of stars

cpp

int main() {
cout << "=== Rectangle Pattern ===" << endl;

int width = 6;
int height = 4;

for (int row = 1; row <= height; row++) {

for (int col = 1; col <= width; col++) {


cout << "* ";
}

cout << endl;


}

return 0;
}

Output:
* * * * * *
* * * * * *
* * * * * *
* * * * * *

What you learned:

How to use nested loops (loop inside a loop)

How to make patterns with stars and numbers

How rows and columns work together

Example 3: Class Test Score Analyzer (Easy)


Problem: Analyze test scores for a small class. Real-life: Like what your teacher does with your test
results.

SECTION A: Input and Display Scores Purpose: Store and show test scores for 5 students
cpp

#include <iostream>
#include <string>
using namespace std;

int main() {
cout << "=== Class Test Score Analyzer ===" << endl;

int scores[5];
string names[5] = {"Alice", "Bob", "Charlie", "Diana", "Eve"};

// Get scores from user


cout << "Enter test scores for 5 students:" << endl;
for (int i = 0; i < 5; i++) {
cout << names[i] << "'s score: ";
cin >> scores[i];
}

// Display all scores


cout << "\n=== All Test Scores ===" << endl;
for (int i = 0; i < 5; i++) {
cout << names[i] << ": " << scores[i] << endl;
}

return 0;
}

SECTION B: Find Highest and Lowest Scores Purpose: Find the best and worst scores
cpp

// ... (previous code)

// Find highest score


int highest = scores[0];
int highestStudent = 0;

for (int i = 1; i < 5; i++) {


if (scores[i] > highest) {
highest = scores[i];
highestStudent = i;
}
}

// Find lowest score


int lowest = scores[0];
int lowestStudent = 0;

for (int i = 1; i < 5; i++) {


if (scores[i] < lowest) {
lowest = scores[i];
lowestStudent = i;
}
}

cout << "\n=== Best and Worst Scores ===" << endl;
cout << "Highest score: " << names[highestStudent] << " (" << highest << ")" << endl;
cout << "Lowest score: " << names[lowestStudent] << " (" << lowest << ")" << endl;

 

SECTION C: Calculate Class Average Purpose: Find the average score for the class
cpp

// ... (previous code)

// Calculate total and average


int total = 0;
for (int i = 0; i < 5; i++) {
total = total + scores[i];
}

double average = (double)total / 5; // Convert to decimal

cout << "\n=== Class Statistics ===" << endl;


cout << "Total points: " << total << endl;
cout << "Class average: " << average << endl;

SECTION D: Count Passing Students Purpose: Count how many students passed (score ≥ 70)
cpp

// ... (previous code)

// Count passing students


int passCount = 0;
cout << "\n=== Pass/Fail Analysis ===" << endl;

for (int i = 0; i < 5; i++) {


if (scores[i] >= 70) {
cout << names[i] << ": PASS (" << scores[i] << ")" << endl;
passCount++;
} else {
cout << names[i] << ": FAIL (" << scores[i] << ")" << endl;
}
}

cout << "\nTotal students who passed: " << passCount << " out of 5" << endl;

return 0;
}

What you learned:

How to store related information (names and scores)

How to find maximum and minimum values


How to calculate averages and totals

How to count items that meet a condition (passing grades)

🎯 Key Takeaways and Summary


What You've Learned
1. Basic Loop Patterns:
Filling arrays: Put numbers in order (even numbers, times tables)

Processing arrays: Add them up, find biggest/smallest


Printing patterns: Stars, numbers, shapes

2. Simple Math with Programming:


Sequences: 2, 4, 6, 8... or 5, 10, 15, 20...
Averages: Add everything up, then divide by count

Comparisons: Finding highest and lowest values

3. Nested Loops (Loop inside Loop):


Outer loop: Controls rows

Inner loop: Controls what's in each row


Patterns: Stars, numbers, rectangles

Simple Patterns to Remember


cpp
// Pattern 1: Fill array with sequence
for (int i = 0; i < size; i++) {
arr[i] = i * 2; // Even numbers: 0, 2, 4, 6...
}

// Pattern 2: Add up all numbers


int sum = 0;
for (int i = 0; i < size; i++) {
sum = sum + arr[i];
}

// Pattern 3: Find biggest number


int biggest = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > biggest) {
biggest = arr[i];
}
}

// Pattern 4: Count things


int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] >= 70) { // Example: passing grades
count++;
}
}

// Pattern 5: Simple star triangle


for (int row = 1; row <= 5; row++) {
for (int star = 1; star <= row; star++) {
cout << "* ";
}
cout << endl;
}

🏋️ Practice Problems (Simple Level)


Problem 1: Favorite Numbers (Very Easy)
Problem: Store your 5 favorite numbers in an array, then find their sum and average.

Tips:

Make an array with 5 numbers

Use a loop to add them all up

Divide by 5 to get average

Problem 2: Countdown Timer (Easy)


Problem: Create an array that counts down from 10 to 1, then display it. Example: [10, 9, 8, 7, 6, 5,
4, 3, 2, 1]

Tips:

Use a loop where i goes from 0 to 9

Set arr[i] = 10 - i to get countdown

Print the array

Problem 3: Simple Times Tables (Easy)


Problem: Let user choose a number (like 7) and show its times table from 1 to 10. Example: If user
picks 7, show 7×1=7, 7×2=14, etc.
Tips:

Ask user for a number

Use loop from 1 to 10


Calculate number × i for each i

Problem 4: Star Square (Easy)


Problem: Draw a square of stars that's 4×4. Example:

* * * *
* * * *
* * * *
* * * *

Tips:

Use nested loops

Outer loop: 4 rows


Inner loop: 4 stars per row

Problem 5: Class Size Counter (Easy)


Problem: You have heights of 6 students. Count how many are taller than 150cm. Sample heights:
145, 155, 160, 148, 152, 158

Tips:

Store heights in array


Use loop to check each height
If height > 150, add 1 to counter

🔍 Common Mistakes to Avoid


Simple Debugging Tips
1. Array Size Errors:

cpp

// ❌ Wrong: array has 5 elements, but loop goes to 6


int arr[5];
for (int i = 0; i <= 5; i++) { // This is wrong!
arr[i] = i;
}

// ✅ Correct: loop goes from 0 to 4 (5 elements)


int arr[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}

2. Forgetting to Initialize:
cpp

// ❌ Wrong: sum starts with garbage value


int sum;
for (int i = 0; i < 5; i++) {
sum = sum + arr[i]; // Problem: what was sum before?
}

// ✅ Correct: always start sum at 0


int sum = 0;
for (int i = 0; i < 5; i++) {
sum = sum + arr[i];
}

3. Nested Loop Confusion:

cpp

// ❌ Wrong: using same variable name


for (int i = 0; i < 3; i++) {
for (int i = 0; i < 3; i++) { // This confuses the computer!
cout << "* ";
}
}

// ✅ Correct: use different names


for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
cout << "* ";
}
}
🚀 What's Next?
After you feel comfortable with these simple examples, you can try:

1. Slightly bigger arrays (10-20 elements instead of 5)


2. More complex patterns (diamonds, pyramids)

3. Simple games (guess the number, tic-tac-toe)

4. Basic sorting (putting numbers in order)

Remember: Programming is like learning to ride a bike - start slow, practice a lot, and don't worry
about making mistakes. Every programmer started with simple problems like these!

Keep practicing these basic patterns until they feel easy. Then you'll be ready for more
advanced challenges! 🎯

You might also like