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
- Create a new TypeScript file
Looping through Numbers
- Using a
forloop, iterate from 1 to 10 and print each number usingconsole.log. - Using a
whileloop, iterate from 10 to 1 (in reverse) and print each number.
Conditional Number Checker
- Declare a variable named
numof typenumberand assign it a value of your choice. - Using an
if-elsestatement, check if the number is even or odd and print the result. (Hint: Use the modulo operator%)
Looping through Strings
- Declare an array named
colorsof typestring[]and initialize it with some colors (e.g., “red”, “blue”, “green”). - Using a
forloop, iterate through the array and print each color. - Using a
for-ofloop, repeat the above step.
Conditional String Checker
- Declare a variable named
fruitof typestringand assign it a value of your choice. - Using a
switchstatement, 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
- Using a nested
forloop, 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");
}