CSEN102 Introduction to Computer Science: Lecture 4

This lecture for CSEN102: Introduction to Computer Science, given by Milad Ghantous, PhD, covers fundamental programming constructs including conditional statements and loops.


4.1 Control Structures: Overview

Control structures are fundamental to programming as they dictate the flow of execution in a program. They allow programs to make decisions, repeat actions, and respond to various conditions.

Types of Control Structures:


4.2 Selection Statements (Conditionals)

Conditional statements allow a program to perform different actions based on whether a specified condition evaluates to true or false. They are essential for decision-making within programs.

1. If Statement:

Executes a block of code only if a condition is true.

if (condition) {
    // code to execute if condition is true
}

2. If-Else Statement:

Executes one block of code if the condition is true and another block if the condition is false.

if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

3. If-Else If-Else Statement (Nested Conditionals):

Allows for multiple conditions to be checked in sequence.

if (condition1) {
    // code for condition1
} else if (condition2) {
    // code for condition2
} else {
    // code if none of the above conditions are met
}

4. Switch Statement (or equivalent):

Provides a way to select one of many code blocks to be executed. Often used when comparing a single variable against multiple discrete values.

switch (variable) {
    case value1:
        // code if variable matches value1
        break;
    case value2:
        // code if variable matches value2
        break;
    default:
        // code if variable does not match any case
}

Logical Operators:

Used to combine or modify conditions:


4.3 Repetition Statements (Loops)

Loops allow a block of code to be executed repeatedly until a certain condition is met or a specified number of times.

1. While Loop:

Repeats a block of code as long as a condition is true. The condition is checked before each iteration.

while (condition) {
    // code to repeat
}

2. Do-While Loop:

Similar to a while loop, but the code block is executed at least once before the condition is checked. The condition is checked after each iteration.

do {
    // code to repeat
} while (condition);

3. For Loop:

Repeats a block of code a specific number of times. It is typically used when the number of iterations is known beforehand.

for (initialization; condition; increment/decrement) {
    // code to repeat
}

Loop Control Statements:

Thank you