Loops in SAPL

Learn how to automate repetitive tasks using different loop structures

Learning Objectives

  • Understand the concept of loops and why they're essential in programming
  • Learn how to use for loops to iterate a specific number of times
  • Master while loops for condition-based iteration
  • Explore loop control statements like break and continue
  • Apply loops to solve practical programming problems

Introduction to Loops

Loops are programming constructs that allow you to execute a block of code multiple times. They are essential for automating repetitive tasks, processing collections of data, and implementing algorithms that require iteration.

Imagine you need to print the numbers from 1 to 100. Without loops, you would have to write 100 separate print statements. With loops, you can accomplish this task with just a few lines of code. This makes your programs more concise, readable, and maintainable.

SAPL supports two main types of loops: for loops for iterating a specific number of times, and while loops for iterating as long as a condition is true.

For Loops

The for loop in SAPL is used when you know in advance how many times you want to execute a block of code. It's particularly useful for iterating through ranges of numbers or collections of items.

Basic For Loop

The basic for loop in SAPL uses the ለ keyword followed by a variable name and እስከ (until) with an end value. This loop starts from 0 and goes up to (but not including) the end value.

# Print numbers from 0 to 9
ለ i እስከ 10:
    አሳይ(i)
SAPL

Output:

0 1 2 3 4 5 6 7 8 9

For Loop with Range

You can specify a start value, end value, and step size for more control over the loop iteration.

# Print numbers from 1 to 10
ለ i በ ውስጥ(1, 11):
    አሳይ(i)

# Print even numbers from 2 to 10
አሳይ("Even numbers:")
ለ i በ ውስጥ(2, 11, 2):
    አሳይ(i)

# Count down from 10 to 1
አሳይ("Countdown:")
ለ i በ ውስጥ(10, 0, -1):
    አሳይ(i)
SAPL

Output:

1 2 3 4 5 6 7 8 9 10 Even numbers: 2 4 6 8 10 Countdown: 10 9 8 7 6 5 4 3 2 1

Looping Through Collections

For loops are commonly used to iterate through collections like lists (arrays) and strings.

# Looping through a list
ፍራፍሬዎች = ["ሙዝ", "አፕል", "ብርቱካን", "ፓፓያ"]
አሳይ("ፍራፍሬዎች:")
ለ i እስከ ብዛት(ፍራፍሬዎች):
    አሳይ(ፍራፍሬዎች[i])

# Looping through a string
ቃል = "አማርኛ"
አሳይ("ፊደላት:")
ለ i እስከ ብዛት(ቃል):
    አሳይ(ቃል[i])
SAPL

Output:

ፍራፍሬዎች: ሙዝ አፕል ብርቱካን ፓፓያ ፊደላት: አ ማ ር ኛ

While Loops

While loops execute a block of code as long as a specified condition is true. They're useful when you don't know in advance how many iterations you need.

Basic While Loop

The while loop in SAPL uses the ሁኔታ keyword followed by a condition. The loop continues as long as the condition evaluates to እውነት (true).

# Print numbers from 1 to 5 using a while loop
ቁጥር = 1
ሁኔታ ቁጥር <= 5:
    አሳይ(ቁጥር)
    ቁጥር = ቁጥር + 1
SAPL

Output:

1 2 3 4 5

While Loop with User Input

While loops are often used to process user input until a certain condition is met.

# Keep asking for input until the user enters "exit"
ግቤት = ""
ሁኔታ ግቤት != "exit":
    ግቤት = ጠይቅ("Enter something (type 'exit' to quit): ")
    አሳይ("You entered: " + ግቤት)
SAPL

Sample Interaction:

Enter something (type 'exit' to quit): hello You entered: hello Enter something (type 'exit' to quit): SAPL You entered: SAPL Enter something (type 'exit' to quit): exit You entered: exit

Loop Control Statements

SAPL provides special statements to control the flow of loops: አቋርጥ (break) and ቀጥል (continue).

Break Statement

The አቋርጥ statement immediately exits the loop, regardless of the loop condition.

# Find the first even number greater than 10
ለ i በ ውስጥ(1, 100):
    አሳይ("Checking: " + i)
    i > 10 እና i % 2 == 0 ከሆነ:
        አሳይ("Found it: " + i)
        አቋርጥ  # Exit the loop
SAPL

Output:

Checking: 1 Checking: 2 Checking: 3 Checking: 4 Checking: 5 Checking: 6 Checking: 7 Checking: 8 Checking: 9 Checking: 10 Checking: 11 Checking: 12 Found it: 12

Continue Statement

The ቀጥል statement skips the rest of the current iteration and moves to the next iteration of the loop.

# Print only odd numbers from 1 to 10
ለ i በ ውስጥ(1, 11):
    i % 2 == 0 ከሆነ:
        ቀጥል  # Skip even numbers
    አሳይ(i)
SAPL

Output:

1 3 5 7 9

Nested Loops

You can place one loop inside another, creating what's called a nested loop. This is useful for working with multi-dimensional data or generating complex patterns.

# Print a multiplication table (1-5)
ለ i በ ውስጥ(1, 6):
    ለ j በ ውስጥ(1, 6):
        ውጤት = i * j
        አሳይ(i + " x " + j + " = " + ውጤት)
    አሳይ("-----")  # Separator between rows
SAPL

Output (partial):

1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5 ----- 2 x 1 = 2 2 x 2 = 4 ...

Practical Examples

Example 1: Sum of Numbers

Calculate the sum of numbers from 1 to 100.

# Calculate sum of numbers from 1 to 100
ድምር = 0
ለ i በ ውስጥ(1, 101):
    ድምር = ድምር + i

አሳይ("The sum of numbers from 1 to 100 is: " + ድምር)
SAPL

Output:

The sum of numbers from 1 to 100 is: 5050

Example 2: Finding Prime Numbers

Find all prime numbers between 1 and 20.

# Find prime numbers between 1 and 20
አሳይ("Prime numbers between 1 and 20:")

ለ ቁጥር በ ውስጥ(2, 21):
    ፕራይም_ነው = እውነት
    
    # Check if the number is divisible by any number from 2 to ቁጥር-1
    ለ i በ ውስጥ(2, ቁጥር):
        ቁጥር % i == 0 እና i != ቁጥር ከሆነ:
            ፕራይም_ነው = ሀሰት
            አቋርጥ  # No need to check further
    
    ፕራይም_ነው ከሆነ:
        አሳይ(ቁጥር)
SAPL

Output:

Prime numbers between 1 and 20: 2 3 5 7 11 13 17 19

Best Practices

  • Choose the right loop type

    Use for loops when you know the number of iterations in advance, and while loops when the number of iterations depends on a condition.

  • Avoid infinite loops

    Always ensure there's a way for your loop condition to eventually become false.

  • Keep loops simple

    If the body of your loop is getting complex, consider breaking it down into functions.

  • Use meaningful variable names

    Instead of generic names like i and j, use descriptive names that indicate what the variable represents.

  • Be cautious with nested loops

    Nested loops can be computationally expensive. Consider alternative approaches for large datasets.

Summary

Key Concepts Learned

  • Loops are used to execute a block of code multiple times
  • For loops (ለ) are used when you know the number of iterations in advance
  • While loops (ሁኔታ) continue as long as a specified condition is true
  • Loop control statements (አቋርጥ and ቀጥል) provide additional control over loop execution
  • Nested loops can be used for multi-dimensional data or complex patterns
  • Loops are essential for automating repetitive tasks and processing collections of data

Loops are one of the most powerful features in programming, allowing you to automate repetitive tasks and process large amounts of data efficiently. By mastering loops in SAPL, you've gained an essential skill that will be used in virtually every program you write.