ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Program Control: for, switch, do...while, break, continue, Logical Operators
    Programming FundamentalsTopic 13 of 39

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

    8 minread
    1,330words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,330
      Code examples0
      DifficultyIntermediate