🔄

Understanding Break and Continue in C

Sep 11, 2024

C Programming: Break and Continue Statements

Introduction

  • Lecture by Padma from Pragyamis.
  • Focus on break and continue statements in C programming to alter the normal flow of loops.

Break Statement

  • Definition: Immediately terminates the loop when encountered.
  • Example:
    • For Loop Example:
      • Loop from i = 1 to i = 5 prints values.
      • Adding break after print results in only 1 being printed.
      • The loop exits after the first iteration.
    • Using with Condition:
      • Modified code to break when i == 3.
      • Output is 1 and 2 because loop terminates on 3.

Continue Statement

  • Definition: Skips the current iteration of the loop and starts the next iteration.
  • Example:
    • Replaced break with continue in previous loop.
    • Output is 1, 2, 4, 5 (skips 3).

Combined Usage of Break and Continue

  • Scenario: User inputs only positive numbers; break on <= 0 and skip odd numbers.
  • Implementation:
    • Check if input is odd using number % 2 != 0.
    • Print only even numbers.
  • Example:
    • Input 4 prints 4, input 7 skips, input -3 terminates the loop.

Programming Task

  • Write a program:
    • Print negative odd numbers.
    • Print message for positive values.
    • Skip negative evens with a message.
  • Output Example:
    • Reflects the conditions for input processing.

Conclusion

  • Key learning points revisited.
  • Engage with viewers: comment on the skip keyword used in loops.
  • End of the session with a note on happy programming.