Loops are one of the most important things you'll ever use in programming; they allow you to automate tasks, which is one of the core components of software.
For instance, you can search and sort lists; create or modify actors; and perform repetitive tasks with only a few lines of code.
- Code: Select all
int i;
setpen(255, 0, 0, 0, 2);
for(i=0; i<24; i++){
moveto(i*32, 0);
lineto(i*32, height);
moveto(0, i*32);
lineto(width, i*32);
}
The above code will draw a grid of lines across the canvas; instead of requiring 24 (moveto) and 24 (lineto) codes, the entire grid takes only 8 lines of code.
Toasterman wrote:
int i,j;
for(i=0;i<j;i++)
{
//action here
}
declare integer i. declare integer j. (you must declare temporary variables before you can use them.)
i starts at 0(i=0;). As long as i is smaller than j(i<j), perform loop. increase i by one each time(i++).
another is while;
- Code: Select all
int i, j;
while (i<2){
//do something;
j++;
if(j==10){
j=0;
i++;}
}
The second one will perform the action as long as the statement following 'while' is true; In this one, simple repetitions aren't enough to stop the loop, as they are in a for loop; the loop continues until the condition is no longer true. In this case, j must reach 10 twice before i is no longer <2.
Be careful with while loops! If the condition
never reaches false, the loop will continue forever, effectively freezing your program!
For loops are safer. Do loop is just another way to write a while loop.
From spawning spread shots to autotargeting to creating explosions and sparks, loops make writing code 100x easier.