Programming for Problem Solving: Iterative Statements, Nested Loops, and Jump Statements in C

Course Overview and Academic Framework

  • Institution: Chandigarh University Uttar Pradesh, School of Computer Science & Engineering
  • Program and Academic Term: Semester I
  • Course Name: Programming for Problem Solving
  • Course Codes: 25CSH-107 / 25ITH-107
  • Faculty: Dr. Sushil Kumar Mishra
  • Core Course Objectives:
    • Build a robust conceptual and practical foundation in problem-solving utilizing the C programming language.
    • Enhance technical capabilities by cultivating systematic logical thinking and algorithmic problem-solving techniques.
    • Empower students to analyze, design, and implement optimized solutions for practical, real-world computational challenges.
  • Course Outcome to Program Outcome (CO-PO) Articulation Matrix:
    • CO1: PO1 (33), PO2 (22), PO3 (11), PO4 (33), PO5 (22), PO6 (−-), PO7 (−-), PO8 (−-), PO9 (−-), P10 (−-), P11 (−-), P12 (−-)
    • CO2: PO1 (33), PO2 (33), PO3 (33), PO4 (22), PO5 (33), PO6 (−-), PO7 (−-), PO8 (−-), PO9 (11), P10 (−-), P11 (−-), P12 (−-)
    • CO3: PO1 (33), PO2 (33), PO3 (22), PO4 (22), PO5 (22), PO6 (−-), PO7 (−-), PO8 (−-), PO9 (−-), P10 (−-), P11 (−-), P12 (−-)
    • CO4: PO1 (33), PO2 (22), PO3 (22), PO4 (22), PO5 (11), PO6 (−-), PO7 (−-), PO8 (−-), PO9 (22), P10 (−-), P11 (−-), P12 (−-)
    • CO5: PO1 (33), PO2 (33), PO3 (22), PO4 (33), PO5 (22), PO6 (−-), PO7 (−-), PO8 (−-), PO9 (−-), P10 (−-), P11 (−-), P12 (−-)
  • Key Topics Covered:
    • Looping Statements (for, while, do-while)
    • Nested Loop Structures
    • Jump Statements (break, continue, goto, return)

Classification of Looping Statements

  • Definition of Iterative Statements:
    • Programming constructs designed to repeatedly execute a specific sequence of instructions based on the evaluation of an expression (typically an integer or Boolean condition).
  • Primary Structural Classifications:
    • Entry-Controlled Loop (Pre-Test Loop):
    • The controlling test condition is evaluated prior to entering the loop body and at the start of every subsequent iteration.
    • If the test expression evaluates to true, the loop body executes; if it evaluates to false, the loop body is bypassed entirely and control terminates the loop.
    • Examples include the while statement and the for statement.
    • Exit-Controlled Loop (Post-Test Loop):
    • The controlling test condition is evaluated after the completion of each loop iteration.
    • If the condition is true, the loop body repeats; if false, loop execution terminates.
    • The loop body executes at least once under all circumstances, even when the condition evaluates to false at the initial check.
    • Example includes the do...while statement.

Flowcharts comparing entry controlled and exit controlled loop logic

The while Loop

  • Execution Principles:
    • Re-executes a single statement or a block of statements continuously as long as a designated condition evaluates to true.
    • Operates as an entry-controlled loop where condition verification precedes the execution of any internal statement block.
    • If the condition evaluates to false at the outset, the inner statements do not execute, and program control jumps directly to the statement immediately following the while loop block.
    • The condition variable must be systematically updated inside the loop body to avoid infinite execution cycles.
  • Flowchart Architecture:

Flowchart diagram of a while loop

  • Formal Syntax:
  while (condition)
  {
      statement_block;
  }
  statement x;
  ```
* **Implementation Example (Displaying values from 00 to 1010):**

c // PROGRAM TO PRINT NUMBERS FROM 0 TO 10 USING WHILE LOOP #include

int main() { int i = 0; while (i <= 10) { printf(" %d", i); i = i + 1; // condition updated } return 0; }   ```

The do-while Loop

  • Execution Principles:
    • Functionally comparable to the while loop, with the structural distinction that the condition is evaluated at the end of the loop.
    • The loop body is executed at least one time, irrespective of whether the condition evaluates to true or false initially.
    • Entry into the loop block is automatic without prior evaluation; condition evaluation dictates only whether the loop continues for subsequent cycles.
    • Inherent Disadvantage: Because first-pass execution is mandatory, invalid inputs or false conditions will still trigger one complete execution of the statement block.
    • Practical Application: Extensively utilized to present selectable options in interactive, menu-driven programs.
  • Flowchart Architecture:

Flowchart diagram of a do-while loop

  • Formal Syntax:
  Statement x;
  do
  {
      statement_block;
  } while (condition);
  statement y;
&nbsp;&nbsp;```
* **Implementation Example (Displaying values from 00 to 1010):**

c // PROGRAM TO PRINT NUMBERS FROM 0-10 USING DO-WHILE LOOP #include

int main() { int i = 0; do { printf(" %d", i); i = i + 1; } while (i <= 10); return 0; }   ```

The for Loop

  • Execution Principles:
    • The control variable initialization step occurs only once at the beginning of loop execution.
    • During each iteration cycle, the loop condition is tested; if true, the enclosed statement block executes, followed by the variable update step.
    • If the condition evaluates to false, the statements inside the body are skipped, and control jumps directly to the statement immediately following the loop.
    • Loop updates may include incrementing (i++i++), decrementing (i−−i--), or applying compound assignment operations (e.g., i+=2i += 2).
  • Flowchart Architecture:

Flowchart diagram of a for loop

  • Formal Syntax:
  for (initialization; condition; increment/decrement/update)
  {
      statement block;
  }
  Statement Y;
&nbsp;&nbsp;```
* **Implementation Example (Printing first nn numbers):**

c #include

int main() { int i, n; printf(" Enter the value of n :"); scanf("%d", &n); for (i = 0; i <= n; i++) { printf(" %d", i); } return 0; }   ```

Nested Loops

  • Structural Principles:
    • A nested loop refers to any loop established entirely within the body of another loop.
    • C supports combining any loop category within another (e.g., a for loop placed inside a while loop, or a while loop nested within another while loop).
    • While programmers commonly implement up to 33 nested levels for manageable code complexity, C enforces no limit on nesting levels.
  • Flowchart Architecture (Nested while loop):

Flowchart diagram for a nested while loop

  • Generalized Syntax:
  outer_loop
  {
      inner_loop
      {
          // Inner loop statement/s
      }
      // Outer loop statement/s
  }
&nbsp;&nbsp;```
* **Execution Workflow:**
  * 1. The inner loop condition is reached and evaluated only when the outer loop condition produces a Boolean value of `True`. If false, control exits both loops entirely.
  * 2. Inside the inner loop, if the inner condition evaluates to `True`, the inner statement block and update expressions execute.
  * 3. When the inner condition evaluates to `False`, the inner loop relinquishes control back to the outer loop, where the outer variable updates and the cycle repeats until the outer condition evaluates to `False`.
* **Code Demonstration 1: Nested do-while Loop:**

c #include

int main() { int i = 1; do // outer loop { int j = 1; do // inner loop { printf("*"); j++; } while (j <= 8); printf(" "); i++; } while (i <= 4); return 0; }   ```

  • Walkthrough: The outer counter variable ii initializes to 11. Because do-while executes unconditionally on entry, the inner loop executes through all iterations (j=1j = 1 up to 88), printing 88 asterisks on one line. Control then proceeds to printf(" ") and increments ii. The outer condition checks if i≤4i ≤ 4; the entire sequence repeats until 44 distinct lines of 88 asterisks have been produced.
  • Code Demonstration 2: Nested for Loop:
  #include <stdio.h>

  int main()
  {
      int i, j;
      for (i = 1; i <= 5; i++)
      {
          printf("
For i = %d ", i);
          for (j = 0; j < i; j++)
          {
              printf("*");
          }
      }
      return 0;
  }
&nbsp;&nbsp;```
* **Program Output:**
    ```text
    For i = 1 *
    For i = 2 **
    For i = 3 ***
    For i = 4 ****
    For i = 5 *****
&nbsp;&nbsp;&nbsp;&nbsp;```

# Overview of Jump Statements

* **Purpose:** Alter the execution sequence of conditional and iterative statements dynamically.
* **Capabilities:** Enable premature loop termination, immediate progression to the subsequent iteration, or arbitrary transfer of control to designated identifiers.
* **The Four Jump Statements in C:**
  * `break`
  * `continue`
  * `goto`
  * `return`

# The break Statement

* **Execution Mechanism:**
  * Immediately terminates the execution of the enclosing loop or switch construct.
  * Control transfers directly to the statements situated immediately downstream of the terminated block.
  * In nested loops, `break` only exits the specific innermost loop that directly contains it, leaving outer loops running.
* **Flowchart Architecture:**

![Flowchart illustrating break statement control flow](https://assets.knowt.com/pdf-flow-prod/4d655161-fcdd-41b7-8097-70edd720e884-figures/22.jpg)

* **Implementation Example (Terminating execution at a specified iteration):**

c #include

int main() { int i; for (i = 1; i <= 15; i++) { printf("%d ", i); if (i == 10) { break; } } return 0; }   ```

  • Program Output:text 1 2 3 4 5 6 7 8 9 10 &nbsp;&nbsp;&nbsp;&nbsp;

The continue Statement

  • Execution Mechanism:
    • Skips the remaining statement execution in the current iteration of the loop body upon meeting an active condition.
    • Re-routes program control directly to the start of the loop for the next iteration cycle, initiating the update and condition evaluation.
    • In nested loop scenarios, continue affects only the inner loop level containing it, leaving outer loop iterations unaffected.
  • Flowchart Architecture:

Flowchart illustrating continue statement control flow

  • Implementation Example:
  #include <stdio.h>

  int main()
  {
      int i, j;
      for (i = 1; i < 3; i++)
      {
          for (j = 1; j < 5; j++)
          {
              if (j == 2)
              {
                  continue;
              }
              printf("%d
", j);
          }
      }
      return 0;
  }
&nbsp;&nbsp;```
* **Execution Details:** Whenever `j=2j = 2`, `continue` executes, bypassing the `printf` instruction for that iteration. The outer loop cycles twice (i=1i = 1 and i=2i = 2) with no interruption.
* **Program Output:**
    ```text
    1
    3
    4
    1
    3
    4
&nbsp;&nbsp;&nbsp;&nbsp;```

# The goto Statement

* **Execution Mechanism:**
  * Executes an unconditional branching jump, transferring program control directly to a labeled statement within the same function.
  * A label is defined using a valid C identifier followed by a colon (`:`), situated immediately preceding the target statement.
* **Flowchart Architecture:**

![Flowchart illustrating goto statement jump logic](https://assets.knowt.com/pdf-flow-prod/4d655161-fcdd-41b7-8097-70edd720e884-figures/31.jpg)

* **Implementation Example:**

c #include

int main() { int i, j; for (i = 1; i < 5; i++) { if (i == 2) { goto there; } printf("%d ", i); }

there: printf("Two"); return 0; }   ```

  • Execution Details: When ii reaches 22, the expression i == 2 evaluates to true, triggering goto there;. Execution leaves the loop immediately and jumps to the labeled target there:, printing Two.
  • Program Output:text 1 Two &nbsp;&nbsp;&nbsp;&nbsp;

The return Statement

  • Execution Mechanism:
    • Terminates execution within the active function and returns program control back to the calling function.
    • Can optionally deliver a return value to the caller, corresponding to the declared return type of the function.
    • If a function has a return type of void, the return statement can be excluded entirely, or written simply as return;.
  • Flowchart Architecture:

Diagram showing calling and called function interaction through return

  • Implementation Example (ASCII Integer to Character Conversion): ```c

    include

    char func(int ascii) { return ((char)ascii); }

    int main() { int ascii; char ch; printf("Enter any ascii value in decimal: "); scanf("%d", &ascii); ch = func(ascii); printf("The character is: %c", ch); return 0; }   ```

  • Execution Details: The program contains two functions with defined return types (char for func() and int for main()). func() evaluates and returns the character representation of the inputted decimal value. main() utilizes return 0 to return an integer exit code indicating normal termination.

  • Program Output (Sample Input: 8080):text Enter any ascii value in decimal: 80 The character is: P &nbsp;&nbsp;&nbsp;&nbsp;

Comparative Review of Iterative and Jump Structures

  • Summary Comparison of Loop Types:
    • for loop: Executes a code block repeatedly until the governing condition becomes false; unifies initialization, conditional evaluation, and variable updates within a single line.
    • while loop: Controlled by a single pre-test condition, continuously executing its body as long as that condition evaluates to true.
    • do-while loop: Evaluates condition logic at the end; guarantees that the statement block is executed at least once and continues as long as the post-test condition remains true.
  • Summary of Nested Loops:
    • C provides full support for defining loops inside other loops across all loop types.
    • Programmers commonly employ up to 33 nested levels; however, no technical limit exists within the C language standard.
  • Summary Comparison of Jump Statements:
    • break: Terminates the loop or switch statement in which it resides immediately.
    • continue: Skips the remaining statements within the current iteration and advances execution directly to the subsequent cycle.
    • goto: Unconditionally transfers program control to a specified labeled identifier within the function.
    • return: Terminates execution of the current function and transfers control back to the caller, optionally returning a value.

Academic References and Supplemental Resources

  • Prescribed Textbooks:
    • Balaguruswami, E. (2024). Computer Concepts and Programming in C. McGraw Hill.
    • Kanetkar, Yashwant P. (2024). Let Us C. BPB Publications.
    • Venugopal, K. R. (2017). Mastering C. McGraw Hill Education India.
  • Online Reference Texts:
    • The C Programming Language: http://www2.cs.uregina.ca/~hilder/cs833/Other%20Reference%20Materials/The%20C%20Programming%20Language.pdf
    • The Basics of C Programming: http://www.freebookcentre.net/programming-books-download/The-Basics-of-C-Programming.html
  • Instructional Video Lectures:
    • Loops in C: https://www.studytonight.com/c/loops-in-c.php
    • Spocathon Lecture on Loop Implementation: https://spocathon.page/video/lecture-20-implementation-loops-statement-contd
    • Nesting Loops in C Programming: https://study.com/academy/lesson/nesting-loops-statements-in-c-programming.html
  • Web Tutorials and Resources:
    • Programiz C For Loop Guide: https://www.programiz.com/c-programming/c-for-loop
    • BeginnersBook C Loop Examples: https://beginnersbook.com/2014/01/c-loops-examples/