AP CSA Iterations PDF

Summary

This document explains different types of loops in Java programming. It details while loops, for loops, and how scope of variables affects their usage within code segments. There are also examples of algorithms for determining loops and tracing them.

Full Transcript

Iterations AP CSA We’ve learned 3 loops… While Loops - Executes code over and over as long as the condition is true Do…While Loops - Executes the code once, checks the condition, and continues as long as the condition is true For Loops - Executes code over and over as long as the conditi...

Iterations AP CSA We’ve learned 3 loops… While Loops - Executes code over and over as long as the condition is true Do…While Loops - Executes the code once, checks the condition, and continues as long as the condition is true For Loops - Executes code over and over as long as the condition is true For loop and while loops are interchangeable, use a For Loop when you know the number of iterations before a loop is run. While Loops Syntax: int x = 1; initialization while (x 0 && x < 5){ never be entered. System.out.println(x); x--; } Scope of Variables Java is an efficient programming language and it likes to save memory, so it does “garbage collection” to get rid of things that are no longer needed. When we declare a variable inside of a loop or if statement, its scope is that loop or if statement - it doesn’t exist outside of that loop or if statement An example of scope int x = 0; while (x > -1){ c was created inside the loop, so it can only be used inside. int c = 0; System.out.println (“you entered: “ + x); x = scan.nextInt(); c++; } System.out.println(“you entered “ + c + “ numbers.”); Cannot use “c” outside of loop. This will cause an error. Tracing while loops Consider the following… Code this: Write a while loop that will iterate loop lines of random numbers between 1 and 9 (inclusive). The line of random numbers will end once the random number is equal to value. Example: If loop is 4 and value is 8… 5638 2234518 23438 28 For Loops Use when you know the exact amount of times you want to loop Syntax: for(int i = 1; i

Use Quizgecko on...
Browser
Browser