ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Program Control Loops …
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    8 min read
    Topic 13 of 39
    Topic Study Note Illustration
    13

    Program Control: for, switch, do...while, break, continue, Logical Operators

    Program control structures allow you to control the flow of a program by executing certain blocks of code based on conditions or repeatedly executing them. In C...

    Program Control in C: for, switch, do...while, break, continue, Logical Operators

    Program control structures allow you to control the flow of a program by executing certain blocks of code based on conditions or repeatedly executing them. In C programming, the main program control structures include the for loop, switch statement, do...while loop, and keywords like break, continue, and logical operators. Each of these structures provides different ways to manage the execution flow, whether for repeated actions or decision-making.

    Let's go through each of these program control structures and concepts in detail.


    1. The for Loop

    The for loop is used for repeating a block of code a specific number of times. It’s ideal when the number of iterations is known in advance.

    Syntax:

    for (initialization; condition; increment/decrement) {
        // Code to be executed
    }
    

    Explanation:

    • Initialization: Typically used to initialize a loop control variable (e.g., i = 0).
    • Condition: The loop continues as long as this condition is true.
    • Increment/Decrement: The control variable is updated after each iteration (e.g., i++).

    Example:

    #include <stdio.h>
    
    int main() {
        // Print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) {
            printf("%d\n", i);
        }
        return 0;
    }
    

    Explanation:

    • The loop starts with i = 1 and runs while i <= 5.
    • After each iteration, i is incremented by 1.
    • The loop prints the values from 1 to 5.

    Output:

    1
    2
    3
    4
    5
    

    2. The switch Statement

    The switch statement is used to handle multiple conditions. It is often used when you need to select one of many code blocks to execute, based on the value of a single variable.

    Syntax:

    switch (expression) {
        case constant1:
            // Code to be executed if expression == constant1
            break;
        case constant2:
            // Code to be executed if expression == constant2
            break;
        default:
            // Code to be executed if expression doesn't match any case
    }
    

    Explanation:

    • Expression: The value or variable being tested.
    • Case labels: Each case corresponds to a possible value of the expression. If a match is found, the corresponding block is executed.
    • break statement: Exits the switch statement after the matching case is executed.
    • default: Optionally executed if none of the case values match.

    Example:

    #include <stdio.h>
    
    int main() {
        int day = 3;
    
        switch (day) {
            case 1:
                printf("Monday\n");
                break;
            case 2:
                printf("Tuesday\n");
                break;
            case 3:
                printf("Wednesday\n");
                break;
            case 4:
                printf("Thursday\n");
                break;
            case 5:
                printf("Friday\n");
                break;
            default:
                printf("Invalid day\n");
        }
    
        return 0;
    }
    

    Explanation:

    • The switch statement checks the value of day.
    • Since day = 3, the program prints "Wednesday".
    • The break statement ensures the program exits the switch block after executing the matching case.

    Output:

    Wednesday
    

    3. The do...while Loop

    The do...while loop is similar to the while loop, but with a key difference: the condition is checked after the loop body is executed. This means the loop will always execute at least once, even if the condition is false initially.

    Syntax:

    do {
        // Code to be executed
    } while (condition);
    

    Explanation:

    • The loop executes the code block once, and then checks if the condition is true.
    • If the condition is true, the loop repeats. If false, the loop terminates.

    Example:

    #include <stdio.h>
    
    int main() {
        int i = 1;
    
        do {
            printf("%d\n", i);
            i++;
        } while (i <= 5);
    
        return 0;
    }
    

    Explanation:

    • The loop prints numbers from 1 to 5.
    • The condition is checked after printing, ensuring the loop executes at least once.

    Output:

    1
    2
    3
    4
    5
    

    4. The break Statement

    The break statement is used to terminate the execution of a loop or switch statement immediately, even if the loop or switch condition hasn’t been satisfied.

    Usage:

    • Exiting loops: When you want to exit a loop prematurely based on some condition.
    • Exiting switch statements: To stop checking other case values.

    Example:

    #include <stdio.h>
    
    int main() {
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                break;  // Exit the loop when i is 6
            }
            printf("%d\n", i);
        }
    
        return 0;
    }
    

    Explanation:

    • The loop will print numbers from 1 to 5, and when i equals 6, the break statement terminates the loop early.

    Output:

    1
    2
    3
    4
    5
    

    5. The continue Statement

    The continue statement is used to skip the current iteration of a loop and proceed to the next iteration, without executing the remaining statements in the loop body for the current iteration.

    Usage:

    • Skipping an iteration: When you want to skip certain parts of the loop for specific conditions.

    Example:

    #include <stdio.h>
    
    int main() {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                continue;  // Skip the rest of the code for i == 5
            }
            printf("%d\n", i);
        }
    
        return 0;
    }
    

    Explanation:

    • When i == 5, the continue statement is triggered, which causes the loop to skip the printf for that iteration.
    • Numbers from 1 to 10 are printed, except for 5.

    Output:

    1
    2
    3
    4
    6
    7
    8
    9
    10
    

    6. Logical Operators in C

    Logical operators are used to combine multiple conditions. They evaluate expressions that return boolean values (true or false) and return true or false based on the combination of conditions.

    Logical Operators:

    1. && (Logical AND):

      • Returns true if both conditions are true.
    2. || (Logical OR):

      • Returns true if at least one of the conditions is true.
    3. ! (Logical NOT):

      • Reverses the truth value of the condition. Returns true if the condition is false, and false if the condition is true.

    Example:

    #include <stdio.h>
    
    int main() {
        int a = 5, b = 10, c = 20;
    
        if (a < b && b < c) {
            printf("a is less than b, and b is less than c\n");
        }
    
        if (a > b || b < c) {
            printf("Either a is greater than b, or b is less than c\n");
        }
    
        if (!(a > b)) {
            printf("a is not greater than b\n");
        }
    
        return 0;
    }
    

    Explanation:

    • The first if checks if both a < b and b < c are true (which they are).
    • The second if checks if either a > b or b < c is true (which b < c is).
    • The third if uses the ! operator to check if a is not greater than b.

    Output:

    a is less than b, and b is less than c
    Either a is greater than b, or b is less than c
    a is not greater than b
    

    Summary of Program Control

    • for loop: Ideal for when the number of iterations is known.
    • switch statement: Used for handling multiple possible values of a single variable.
    • do...while loop: Ensures the loop executes at least once before checking the condition.
    • break statement: Immediately exits the loop or switch block.
    • continue statement: Skips the current iteration of the loop and continues with the next iteration.
    • Logical operators: Combine multiple conditions, allowing for more complex decision-making.

    These program control structures provide flexibility and efficiency in managing the flow of your program. Whether you're repeating tasks or making decisions, these tools are essential for writing clean and effective C programs.

    ← Previous topic 12
    Structured Program Development: The if, if...else, while Nested Control Statements
    Next topic 14 →
    Functions: Modularizing Program in C, Math Library Functions

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals