In this post, I will be addressing all you concerns about what loops are and how they work. Whichever programming language you are currently learning, whether it is Java, Python, JavaScript, C#, c++, e.t.c, they all follow the same nomenclature of action. I intend to help you trash out the concept of Loops on your Journey to becoming a programmer. In this post, I will make use of JavaScript as a reference point to whichever Language you are learning.
What are Loops?
According to Zuckerberg's Chat Bot(Meta AI): A loop is a control structure in programming that allows a sequence of instructions to be executed repeatedly, either for a fixed number of iterations or until a specific condition is satisfied.
I like this definition as it makes explicit indication -"Until a specific condition is satisfied". To redefine it, Loops are blocks of code that will not stop iterating over and over (Initializing repeatedly) unless an already declared condition becomes false (i.e, condition is no longer true).
When constructing a loop, a condition of action is always declared together with it and the loop will not be terminated unless the declared condition is no longer true.
There a basically, 2 major types of Loops in all programming language:
- For Loop
- While Loop
However, In JavaScript there are 5 forms of Loops:
- For Loop
- For Of Loop
- For In Loop
- While Loop
- Do While Loop
I will focus on the 2 major ones in this post, For and While Loop.
FOR LOOP
When you have codes that you want to Run repeatedly while either console. Logging, incrementing, decrementing, you want to fill in some elements into an array, carry out some arithmetic operations over some predeclared numbers etc, For Loop might just be your best choice.
One distinction that is easily noticeable between For and While Loop is that the afore allows variables to be declared within the For loop when the Loop is being declared.
// Define an array of numbers
let numbers = [1, 2, 3, 4, 5];
// Use a For loop to iterate over the array
for (let i = 0; i < numbers.length; i++) {
// Print each number
console.log(numbers[i]);
}
We define an array numbers containing five integers.
The For loop iterates over the numbers array.
The variable i is the loop counter, initialized to 0.
The loop condition checks if i is less than the length of the numbers array.
Inside the loop, we print the current value of numbers[i] using console.log()
secondly, For Loops work majorly with Arithmetic conditions such as:
// Define an array of objects
let students = [
{ name: 'John Doe', age: 20, grade: 85 },
{ name: 'Jane Doe', age: 22, grade: 90 },
{ name: 'Bob Smith', age: 21, grade: 78 },
{ name: 'Alice Johnson', age: 20, grade: 92 },
];
// Use a For loop to iterate over the array
for (let i = 0; i < students.length; i++) {
// Check if the student's grade is above 85 and age is above 21
if (students[i].grade > 85 && students[i].age > 21) {
// Print the student's name and grade
console.log(`${students[i].name} has a grade of ${students[i].grade}`);
} else if (students[i].grade > 85 && students[i].age <= 21) {
// Print a message if the student's grade is above 85 but age is 21 or below
console.log(`${students[i].name} is a high-achieving student, but not yet 22 years old.`);
} else {
// Print a message if the student's grade is 85 or below
console.log(`${students[i].name} needs to improve their grade.`);
}
}
however, on the contrary-wise, while Loops can work with both Arithmetic and Boolean conditions. Beside All this, it works just like a while loop
WHILE LOOP
While loop is less preferred by most programmers due to its unique conditional cases. Unlike For loop, While Loops are commonly used with a Boolean conditional test to create a repeated iterations.
// Initialize a counter variable
let i = 0;
// Set a condition for the loop
while (i < 5) {
console.log(`Counter: ${i}`)// Print the current value of the counter
i++;
}
Using a Boolean test case as conditions allows programmers a lot of unique usage of the Loop. for example while validating a log in details
let isLoggedIn = false;
// Simulate user login attempt
while (!isLoggedIn) {
let username = prompt("Enter your username:");
let password = prompt("Enter your password:");
// Verify login credentials
if (username === "admin" && password === "password") {
isLoggedIn = true; //sets the condition true
console.log("Login successful!");
} else {
console.log("Invalid username or password. Please try again.");
}
}
// User is now logged in
console.log("Welcome to the dashboard!");
a boolean variable
isLoggedIn
is initialized to false.
The While loop checks the condition!isLoggedIn
, which is equivalent to(isLoggedIn === false)
.
If the condition is true, the loop body executes
If the credentials are valid, setsisLoggedIn
to true.
Steps 2-3 repeat until the condition!isLoggedIn
is false.
Once the condition is false, the loop exits, and the user is logged in.
One common mistake programmers make with WHILE Loops is that they define the condition within the loop, which eventually crashes the terminal.
If you have followed me through up to this point, congratulations you have just divulged the most important points you need to know before effectively using a Loop.
Top comments (0)