Skip to content

T020 Exploring Loops and Conditionals

In this assignment, you’ll delve deeper into TypeScript by working with loops and conditional statements. You’ll practice using for, while, and if-else constructs to control the flow of your program.

Setup

  1. Create a new TypeScript file

Looping through Numbers

  1. Using a for loop, iterate from 1 to 10 and print each number using console.log.
  2. Using a while loop, iterate from 10 to 1 (in reverse) and print each number.

Conditional Number Checker

  1. Declare a variable named num of type number and assign it a value of your choice.
  2. Using an if-else statement, check if the number is even or odd and print the result. (Hint: Use the modulo operator %)

Looping through Strings

  1. Declare an array named colors of type string[] and initialize it with some colors (e.g., “red”, “blue”, “green”).
  2. Using a for loop, iterate through the array and print each color.
  3. Using a for-of loop, repeat the above step.

Conditional String Checker

  1. Declare a variable named fruit of type string and assign it a value of your choice.
  2. Using a switch statement, check the value of the fruit. If it’s “apple”, print “I like apples”. If it’s “banana”, print “Bananas are yellow”. For any other fruit, print “I like all fruits”.

Challenge: Nested Loops

  1. Using a nested for loop, print a 5x5 grid of asterisks (*). The output should look like:
    *****
    *****
    *****
    *****
    *****
    
Solution

Solution

Looping through Numbers

for (let i = 1; i <= 10; i++) {
    console.log(i);
}

let j = 10;
while (j >= 1) {
    console.log(j);
    j--;
}

Conditional Number Checker

let num: number = 7;
if (num % 2 === 0) {
    console.log("The number is even.");
} else {
    console.log("The number is odd.");
}

Looping through Strings

let colors: string[] = ["red", "blue", "green"];
for (let i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}

for (let color of colors) {
    console.log(color);
}

Conditional String Checker

let fruit: string = "apple";
switch (fruit) {
    case "apple":
        console.log("I like apples");
        break;
    case "banana":
        console.log("Bananas are yellow");
        break;
    default:
        console.log("I like all fruits");
}

Challenge: Nested Loops

for (let i = 0; i < 5; i++) {
    let row = "";
    for (let j = 0; j < 5; j++) {
        row += "*";
    }
    console.log(row);
}