Control Structures
Iteration, conditions, nested conditions
Control Structures:
Control Structures are the building blocks in programming that dictate the flow of execution in a program. They allow you to control how the program behaves based on certain conditions or repetitive actions.
Examples of them are: ↓ ↓ ↓
Iteration:
This refers to repeating a set of instructions multiple times. It allows you to perform an action repeatedly, such as going through items in a list, or performing a task until a certain condition is met. It helps automate repetitive tasks and makes code more efficient.
Example: (from code)
this.tID = setInterval(() => {
const col = (frame + obj.col) * this.pixels;
this.marioElement.style.backgroundPosition = `-${col}px -${row}px`;
this.marioElement.style.left = `${this.positionX}px`;
this.positionX += speed;
frame = (frame + 1) % obj.frames;
const viewportWidth = window.innerWidth;
if (this.positionX > viewportWidth - this.pixels) {
document.documentElement.scrollLeft = this.positionX - viewportWidth + this.pixels;
}
}, this.interval);
Conditions:
Conditions allow you to make decisions in your program. They evaluate whether something is true or false and execute different code based on the result. If a condition is true, one block of code runs; if it’s false, another block of code may run. It enables the program to react to different situations.
Example: (from code)
window.addEventListener("keydown", (event) => {
if (event.key === "ArrowRight") {
event.preventDefault();
if (event.repeat) {
mario.startCheering();
} else {
if (mario.currentSpeed === 0) {
mario.startWalking();
} else if (mario.currentSpeed === 3) {
mario.startRunning();
}
}
} else if (event.key === "ArrowLeft") {
event.preventDefault();
if (event.repeat) {
mario.stopAnimate();
} else {
mario.startPuffing();
}
}
});
Nested Conditions:
Nested conditions occur when one condition is placed inside another. This allows for more specific decision-making. If a condition within a condition is true, it will trigger further checks or actions, helping to handle more complex scenarios where multiple factors need to be evaluated.
Example: (from code)
window.addEventListener("keydown", (event) => {
if (event.key === "ArrowRight") {
event.preventDefault();
if (event.repeat) {
mario.startCheering();
} else {
if (mario.currentSpeed === 0) {
mario.startWalking();
} else if (mario.currentSpeed === 3) {
mario.startRunning();
}
}