Mada za sehemu hiiDeveloping programs using functions and arraysMada 3
- Constructing reusable functions
- Implementing single-dimensional and multi-dimensional arrays
- Using control structures to traverse and process arrays
Using Control Structures to Traverse and Process Arrays
When you have an array containing multiple values, you often need to work with all its elements — for example, to calculate a total, find the highest score, or search for a specific name. Traversing an array means accessing each element one by one in a systematic way. Control structures such as for loops and while loops allow you to repeat an action for every element in the array.
A for loop is ideal when you know how many elements are in the array. You can use the array's Length property to determine the number of elements, which makes your code work for any array size.
The general pattern is:
for (int i = 0; i < arrayName.Length; i++)
{
// Process arrayName[i]
}
The index i starts at 0 (the first position) and increases until it reaches arrayName.Length - 1 (the last position).
Worked Example: Printing All Array Elements
The following program creates an array of temperatures for Dodoma and prints each temperature:
using System;
class Program
{
static void Main()
{
int[] temperatures = { 28, 32, 35, 30, 27 };
Console.WriteLine("Daily temperatures for Dodoma:");
for (int i = 0; i < temperatures.Length; i++)
{
Console.WriteLine($"Day {i + 1}: {temperatures[i]}°C");
}
}
}
Output:
Daily temperatures for Dodoma:
Day 1: 28°C
Day 2: 32°C
Day 3: 35°C
Day 4: 30°C
Day 5: 27°C
Notice how temperatures.Length automatically gives the size of the array (5), so the loop works even if you add more temperatures later.
A while loop is useful when the number of iterations is not known in advance or when you need more control over when the loop ends. You must manage the loop variable yourself.
The general pattern is:
int i = 0;
while (i < arrayName.Length)
{
// Process arrayName[i]
i++; // Don't forget to increment!
}
Worked Example: Calculating the Total
This program calculates the sum of all marks in an array:
using System;
class Program
{
static void Main()
{
int[] marks = { 75, 82, 60, 91, 55 };
int total = 0;
int i = 0;
while (i < marks.Length)
{
total = total + marks[i];
i++;
}
Console.WriteLine($"Total marks: {total}");
}
}
Output:
Total marks: 363
Finding the Maximum Value
To find the highest value, start with the first element as a temporary maximum, then compare every other element:
int[] scores = { 45, 78, 92, 65, 88 };
int max = scores[0]; // Assume first element is largest
for (int i = 1; i < scores.Length; i++)
{
if (scores[i] > max)
{
max = scores[i];
}
}
Console.WriteLine($"Highest score: {max}");
Output:
Highest score: 92
Finding the Minimum Value
Similarly, find the lowest value by starting with the first element and checking each subsequent element:
int[] prices = { 1500, 2200, 800, 3500, 1200 };
int min = prices[0];
for (int i = 1; i < prices.Length; i++)
{
if (prices[i] < min)
{
min = prices[i];
}
}
Console.WriteLine($"Lowest price: {min} TSh");
Output:
Lowest price: 800 TSh
Calculating the Average
Sum all elements, then divide by the number of elements:
int[] sales = { 50000, 75000, 62000, 80000, 45000 };
int sum = 0;
for (int i = 0; i < sales.Length; i++)
{
sum = sum + sales[i];
}
double average = (double)sum / sales.Length;
Console.WriteLine($"Average sales: {average} TSh");
Output:
Average sales: 62400 TSh
Searching for a Specific Value
To find whether a particular value exists in the array, check each element until you find a match:
string[] fruits = { "Mango", "Banana", "Papaya", "Orange", "Apple" };
string searchItem = "Papaya";
bool found = false;
for (int i = 0; i < fruits.Length; i++)
{
if (fruits[i] == searchItem)
{
found = true;
Console.WriteLine($"Found {searchItem} at position {i}");
break; // Stop searching once found
}
}
if (!found)
{
Console.WriteLine($"{searchItem} not found in the list");
}
Output:
Found Papaya at position 2
Modifying Array Elements
You can change the value at a specific index:
int[] inventory = { 10, 25, 15, 30, 20 };
// Reduce inventory by 5 for the first item
inventory[0] = inventory[0] - 5;
Console.WriteLine($"Updated first item quantity: {inventory[0]}");
Output:
Updated first item quantity: 5
In Tanzania, shop owners often keep track of daily sales in a list. Using loops, they can calculate total revenue for the month, find which product sold the most, or check if a particular item is in stock. For example, aduka in Mwanza can use a loop to sum all sales from an array of 30 daily values to know whether they have met their monthly target of 1,500,000 TSh.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Write control structures to traverse arrays efficiently using loopsand conditionals.
- Implement logic to process arrays, such as filtering or updating data.
Tathmini ya matokeo
Programs that use control structures effectively to traverse and process arrays are created.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Use loops like for, while, and foreach to traverse arrays.
- Implement conditional statements to process specific elements in arrays.
Principles: The student should explain the principle of:
- Array indexing and its role in traversal.
- Error handling during array traversal to avoid runtime issues.
Theories: The trainee should explain: The trainee should explain:
- The impact of loop structures on the efficiency of array operations.
- The relationship between control structures and array manipulation in solving complex problems.
Circumstantial knowledge:
Detailed knowledge about:
- Common errors in array traversal, such as off-by-one errors, and strategies to resolve them.
- Best practices for using nested loops with multidimensional arrays.
Swali
What is the correct for loop syntax to traverse all elements of an integer array called scores?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado