🔄

Understanding Control Statements in Programming

Apr 7, 2025

Lecture 3: Control Statements

Overview

  • Control statements dictate the flow of execution in a program.
  • They are essential for decision-making and iteration in programming.

Types of Control Statements

  1. Conditional Statements

    • Used to perform different actions based on different conditions.
    • Common types include:
      • if statements
      • if-else statements
      • switch statements
  2. Looping Statements

    • Allow code to be executed repeatedly based on a condition.
    • Common types include:
      • for loops
      • while loops
      • do-while loops

Conditional Statements

if Statement

  • Syntax: if (condition) { // code to execute if condition is true }
  • Example: if (x > 10) { console.log('x is greater than 10'); }

if-else Statement

  • Syntax: if (condition) { // code if condition is true } else { // code if condition is false }
  • Example: if (x > 10) { console.log('x is greater than 10'); } else { console.log('x is 10 or less'); }

switch Statement

  • Used to execute one block of code among many choices.
  • Syntax: switch (expression) { case value1: // code block break; case value2: // code block break; default: // code block }

Looping Statements

for Loop

  • Used for iterating over a sequence (like an array).
  • Syntax: for (initialization; condition; increment) { // code to execute }
  • Example: for (let i = 0; i < 5; i++) { console.log(i); }

while Loop

  • Repeats a block of code as long as a condition is true.
  • Syntax: while (condition) { // code to execute }
  • Example: let i = 0; while (i < 5) { console.log(i); i++; }

do-while Loop

  • Executes a block of code once, and then repeats while a condition is true.
  • Syntax: do { // code to execute } while (condition);
  • Example: let i = 0; do { console.log(i); i++; } while (i < 5);

Summary

  • Control statements are crucial for controlling the flow of execution in programs.
  • Understanding how to implement conditional and looping statements is vital for programming.