ZC

Programing Lab

  • Types of Loops

    • While Loop
    • Checks condition at the beginning.
    • Minimum execution count: zero (if condition is false initially).
    • Repeats until the condition is false.
    • Do While Loop
    • Checks condition at the end.
    • Minimum execution count: one (always executes at least once).
  • Infinite Loops

    • Can occur in both types of loops if conditions are not appropriately managed.
    • For While Loop:
      • Example: If a counter variable is not incremented, the loop will continue indefinitely.
    • For For Loop:
      • Example: Incorrectly defined condition (e.g., always true) leads to an infinite loop.
  • Visibility of Variables

    • Variables must be defined within the scope they are to be used.
    • Local variables defined inside loops (e.g., in a for loop) cannot be used outside that loop.
  • Understanding Execution of Loops

    • Example of a while statement:
    • If x = 5 and the condition is x < 8, the loop will add 2 to x, resulting in 7 and then 9 being printed, and it stops when x >= 8.
    • Infinite loop example: If x = 5 and the operation is x - 2, loops indefinitely as x keeps decreasing.
  • Complexity in Programming

    • Time Complexity: Time required to run a program (how many operations it performs).
    • Space Complexity: Amount of memory required to run a program.
    • Aim: Optimize code to minimize both time and space complexities.
  • Time Complexity Calculation

    • Each instruction/loop iteration is simulated to take a certain time (e.g., 1 second).
    • Example of a for loop with n iterations will take n seconds.
    • If n grows to millions, time taken increases dramatically (e.g., 10 million takes 10 million seconds).
  • Nested Loops

    • A loop within a loop.
    • Example: Printing a rectangle pattern of stars requires both row and column loops.
    • Time complexity of nested loops: If outer loop runs m times and inner n times, total operations are m*n, leading to O(m*n) complexity.
  • Formula for Square Shapes in Nested Loops

    • For squares where rows equal columns, the time complexity becomes O(n^2) (as both dimensions grow) leading to rapidly increasing required time with larger input sizes.
    • Example: If n = 1,000,000, then the time required for execution could reach extremely high values like 1,000,000^2 seconds.
  • Recommendations for Learning

    • Familiarize yourself with writing nested loops to create shapes (e.g., rectangles, squares) and practice their time complexity calculations.
    • Continue to engage with exercises that challenge your understanding of loop visibility, infinite loops, and complexities to reinforce learning.