Introduction: Interesting Programing Guidance for Designer--Program Process Control- Loop Statement

Picture of Interesting Programing Guidance for Designer--Program Process Control- Loop Statement

Program Process Control- Loop Statement

From this chapter, you will get in touch with an important and powerful knowledge point-Loop Statement.

Before reading this chapter, if you want to draw 10,000 circles in the program, you can only do with a terrible method. That is to write 10,000 lines of ellipse code . Those lazy code designers who want to improve efficiency by all means, definately would not allow this happened. So, loop statement is created. With this statement, you can intuitively feel the power of computer automation.

Step 1: For Loop

There are lots of loop statements, among which the most widely used is For Loop. We all know that function draw is continuously operate in circulation. Start from the first sentence at the beginning, it will implement from top to bottom till the last sentence. After it finished an operation, it will start again from the first sentence. For statement is a little bit similar to function draw. Code within for statement can be executed repeatedly.

Here is its grammar structure:

For( expression 1; expression 2; expression 3){

Loop body

}

Obviously, sentences within loop body is what we expected to be implemented repeatedly. Expression 1 is used to initialize and assign the first value to loop variable. Expression 2 is for loop condition. Expression 3 will update loop variable value.

What is loop variable? It is actually equivalent to a local variable. Let's take a look of a complete writing.

for(int i = 0;i < 10;i++){

Loop body

}

In order to realize loop function, for statement mainly relies on a local variable, which will be used at the loop termination. The local variable in the above example is i. Expression 1 has completed the initialization of local variable. Later, every time the loop operates for once, this variable must be updated. Among the above example, i++ in expression 3 is used to realize update function. Through it, the variable will increase 1 every time it updated. In the end, the code within loop body can not loop indefinitely, otherwose the latter statements can not be executed. Thus, we need a terminal condition. Express 2 is just for it. Here, the program will judge whether i is less than 10. If it is, then go on operate. If it isn't, then jump out of the loop.

Therefore, the operation sequence of for statement is just like this.

Expression 1 (Local variable initialization)

Expression 2 (Satisfied, then continue to operate)

Loop body (First circulation)

Expression 3 (Update)

Expression 2 (Satisfied, then continue to operate)

Loop body (Second circultaion)

Expression 3 (Update)

Expression 2 ( Satisfied, then continue to operate)

Loop body ( Third circulation) ...

...

Expression 3 (Update)

Expression 2 (Not satisfied, then jump out of the loop)

You can simulate this sequence of execution in your head for several times. But it is impossible to really understand the code without typing it with your hand for once. When we want to find out a strange concept, we can print the value in the console through the println statement.

Code Example (5-1): void setup(){

for(int i = 0; i < 10; i++){

println ("run");

}

}

You can count the number of run output in the console. Here, it is exactly 10. This tells you how many times the code in the loop body has been executed. However, we still can not detect what changes have actually happened in the loop. So we can try to change character "run into variable "i", and see what will happen.

Code Example (5-2): void setup(){

for(int i = 0; i < 10; i++){

println (i);

}

}

Now, we can see the value i in loop body is continuously increasing. Later, we can use this value to understand the current process of the loop.

In code example (5-2), the value of i is changed from 0 to 9. Compared to the actual loop times, it seems to always have 1 less. If you are not get used to it, the expression within bracket of for statement can be written to the following:

for(int i = 1; i <= 10; i++)

Thus, i is righteously correspond to loop times. The meaning of "<=" is less than and equal to. So when i equals to 10, it will still meet the condition. Therefore, it will operate once more compared with being written into i < 10. Although it is start from 1, the loop times is still 10. Of course, if nothing special needed, I would like to suggest you adopt the writing method in the example at the beginning. Later we will introduce vector or array to you, both of which obtain its element by its subscript. And the defaulted subscripts all starts from 0. To define the initial value to be 0 is the comparatively common practice.

In the above example, if we write i is beyond 0, the pogram will crash. Because the variable is constanlty increasing, it will never satisfy this condition. This is just like it can never be stopped so that the program will run into endless loop.

Local variables in the for statement can not only declare plastic types, but also declare variables in floating-point types. For example, it can be written as (float i = 0; i <10; i + = 0.02).

Step 2: Use for Loop to Solve Mathematical Problems

Do you still remember a story of mathematician Gauss in his childhood? At that time, Guass was 10 years old. His teacher wanted to assign a task in the class and the question was

1+2+3+4……+97+98+99+100=?

If you calculate with your hands, it will take you much time. But Guass seems to have figure out the method of summation of the arithmetic sequence already. So just after the question is given, he spoke out the answer with ease, which had greatly suprised his teacher.

Now, we may not still remember what is the summation of the arithmetic sequence but we can get the answer in a primitive and violent way. And that is for loop. Since it is just a small piece of cake for computers to count, we have to describe the question into a language that can be recognised by computer, then we can easily get our answer.

Code Example (5-3):

void setup(){

int answer = 0;

for(int i = 1; i <= 100; i++){

answer += i;

}

println(answer);

}

I believe the result you get is same to the answer Guass reported: it is 5050!

Tips: The name of local variables in for loop can be changed at will on condition that it abides by the variable naming regulations. You can write it to be (int k = 1;k <= 100;k++). If no speical conditions happened, it default i as the name of the variable.

Step 3: For Loop Drawing

After a series of seemly boring bedding, finally we can come into a more interesting section. That is to use for loop to draw pictures. We can set aside those tedious mathematical calculation now. We designers are more sensitive to graphics.

Use For Loop To Draw A Circle Array

When we want to use for loop to represent a group of repeated elements, we have to make sure the numeral relatioship of these elements beforehand, then we can use for loop to conveniently realize it instead of doing massive repeat work. Suppose if we want to draw a row of circle equally spreaded in horizontal direction. Its virtical coordinate is unchanged while its horizontal coordinate is changed. And from the left to the right, the horizontal coordinate is constantly increasing and the increasing distance is the same. At this time, we can use i in for loop to get the horizontal coordinate of each circle.

Code Example(5-4): void setup(){

size(700,700);

background(83,51,194);

noStroke();

}

void draw(){

for(int i = 0; i < 7; i++){

ellipse(50.0 + i * 100.0, height/2.0, 80.0, 80.0);

}

}

50 stands for the start position of the first circle in the left. 100 in i * 100 represents the increasing distance.

Step 4: Use for Loop to Draw a Random Round Point

The above graphic position is predictable. This will minimize lots of interest. We can use function random we refered in the previous chapter and try to write it in drawing function.

Code Example (5-5):

void setup(){

size(700,700);

background(0);

noStroke();

}

void draw(){

background(0);

for(int i = 0;i < 10;i++){

float randomWidth = random(60.0);

ellipse(random(width), random(height), randomWidth, randomWidth);

}

}

  1. 1Here, the reason why the position of circle is continuously flashing is because of every time function random operate for once, the result is random. Because function draw is defaulted to run 60 frames per second, so every 10 circles drawn in a second will change its position for 60 times. This swift flash makes the picture seem to have more than just 10 circles. Change a simple value in the program will bring you a totally different effect. We can change the loop times by revising the terminal condition . The terminal condition in the picture below is i < 100.
  2. 2
  1. Here's the effect when the terminal condition is i < 1000: 3
  2. RandomSeed
  3. If I don not want the position of circle is randomly generated as well as its flash,what can I do? One method is to build and store independent variables for each circle and initialize these variables in setup. Assign these variables a random value. Thus, when using drawing function within draw, what we invoked is the value stored in variables . It will not change at any time. To draw 10 circles we can just use this method. But what if we want to draw 1000 circles, or 10,000 circles? It will be quite troublesome if we use this traditional method to build these variables and name it. We do not have to learn a new variable build method. Here is a flexible method that can help us achieve this goal. That is to use randomSeed. Now, let's take a look of its effect after being used. Code Example (5-6):[cceN_cpp theme="dawn"] void setup(){ size(700,700); background(0);noStroke();}
  4. void draw(){

    background(0);

    randomSeed(1);

    for(int i = 0;i < 10;i++){

    float randomWidth = random(20.0, 60.0);

    ellipse(random(width), random(height), randomWidth, randomWidth);

    }

    } [/cceN_cpp]

    Compared to the code before, it do not have any changes except making the radius range of circle change from 10 to beyond 30 with a sentence of ofSeedRandom only. After being added this sentence, the graphic seems become static.

    Invoke Format:

    randomSeed(a);

    Among this format, the setting of a is seed. You have to fill an integer (write afloating point value in P5, it will not go wrong but treat it as an integer) into it. The function of randomSeed is to set the seed for random value. Then it iwll generate different random array according to different seed. After it, we invoke function random so that the result of return is definite. Here, the definite is not for the result is a definite value but for the generated array. That is to say the result of return is definite relative to the invoking times.

    Code Example (5-7):[cceN_cpp theme="dawn"] void setup(){

    randomSeed(0);

    for(int i = 0;i < 5;i++){

    println(random(10));

    }

    } [/cceN_cpp]

    Now we go on using println to do an experiment. After using randomSeed, every time you close the program and restart the program, it will return to a string of same result. The value will correspond to the sequence one by one. If you delete it, then every time it will return to different value. Why it has this setting? It is because of the random value itself in the program is pseudo random. The result seems random but actually it is generated by a fixed and repeatable calculate method. It is equivalent to designate a primitive value for randomSeed, then the following result will be calculated according to this seed. However, if we do not designate the seed, the program will default to use the present time of the system to generate seed. Therefore the result of every operation is different. The example below can help you better understand randomSeed.

    Example Code (5-8):[cceN_cpp theme="dawn"] void setup(){

    size(700,700);

    background(0);

    noStroke();

    }

    void draw(){

    randomSeed(1);

    for(int i = 0;i < 10;i++){

    float randomWidth01 = random(10, 60);

    ellipse(random(width), random(height), randomWidth01, randomWidth01);

    println(randomWidth01);

    }

    randomSeed(1);

    for(int i = 0;i < 10;i++){

    float randomWidth02 = random(10, 60);

    ellipse(random(width), random(height), randomWidth02, randomWidth02);

    println(randomWidth02);

    }

    } [/cceN_cpp]

    Try to revise the second randomSeed(1) to randomSeed(0) and compare the final results.

    Tips: In P5, we only have to invoke function noLoop at the end of draw so that we can get the same effect. Its function is to terminate the program. It is quite different to the above working principles in nature.

Step 5: Use for Loop to Draw Line

After we have mastered the usage of randomSeed , we can try to change drawing function. For example, change circle drawing into line drawing. Only if we design some changing regulations to the end of the line, we can use a lot of lines entwined to make a unique pattern.

Code Example(5-9):

[cceN_cpp theme="dawn"] void setup(){

size(700,700);

background(0);

}

void draw(){

randomSeed(0);

for(int i = 0; i < 2000; i++){

float x1 = width/2.0;

float x2 = random(50.0, 650.0);

stroke(255, 20);

line(x1, 50, x2, 650);

}

} [/cceN_cpp]

Create Simple Brush

Back to for loop again. The above examples are not interactive. If we want to make the result become more interesting, we can not forget to combine mouseX and mouseY into our code.

Code Example (5-10):

[cceN_cpp theme="dawn"] void setup(){

size(700,700);

background(255);

noStroke();

}

void draw(){

for(int i = 0;i < 1000;i++){

fill(0,30);

float x = mouseX + random(-50,50);

float y = mouseY + random(-50,50);

ellipse(x , y, 2, 2);

}

} [/cceN_cpp]

4

A "scattering points" brush is created. Because of every intensive mini round point is based at the position of the mouse, it can move limited directions from the four directions of left, right, up and down. So the final shape spread of the brush is similar to a square.

Code Example (5-11):

[cceN_cpp theme="dawn"] void setup(){

size(700,700);

background(255);

noStroke();

}

void draw(){

for(int i = 0;i < 1000;i++){

float ratio = mouseX/(float)width;

float x = mouseX + random(-50,50);

float y = mouseY + random(-50,50);

fill(0, ratio * 255,255 * (1 - ratio), 30);

ellipse(x , y, 2, 2);

}

}

[/cceN_cpp]

If we use the value of mouseX to affect the filling color, then we will get a much more magic color gradient.

Step 6: For Loop Nested

For loop can be nested. You can write a for loop again into the for loop. When you need to draw a two dimensional dot matrix, you can choose this method.

Code Example(5-12):

[cceN_cpp theme="dawn"] void setup(){

size(700, 700, P2D);

background(202, 240, 107);

}

void draw(){

fill(0);

for(int i = 0;i < 5;i++){

for(int j = 0;j < 5;j++){

float x = 150 + i * 100;

float y = 150 + j * 100;

ellipse(x, y , 60, 60);

println(i + ":" + j);

}

}

}

[/cceN_cpp]

To use the nested loop for the first time, you have to figure out its logic relations. The code implementation in the program is always from the up to the bottom. Therefore, the first implemented is definitely the outmost loop. Every time the outer loop operate for once, the internal loop will continuously operate until it can not satisfy the condition any more. After that, it will start the second outer loop operation. After the second operation started, the internal loop will go on implement until it can not satisfy the condition. Such a repetition it does until all conditions can not be satisfied and it jump out of the loop.

In the above code, the loop body in the outer loop has operated 5 times in total, while the loop body in the internal loop has operated 25 times. Within 25 times, according to the difference of i, j value, we can assure the horizontal and vertical coordinate of the circle separately. I have embeded a section of print , you can observe the data output and think about its change. With two nested loops only, we can experience all of the combinations of i,j data.

Tips

For loop in the second layer usually condense with Tab at the beginning. This can make the code structure more clear. You have to name local variables in the two layers of for loop with different names. Among it, "i", "j", "k" is the most commonly used.

Flexible Use "i" , "j"

The two variable name of "i","j" represent local variables of the two layers of for loop. The example below will deepen your understanding for "i""j". According to the different value of "i" ,"j" , we can input parameters to group the elements.

Code Example (5-13):[cceN_cpp theme="dawn"] void setup() {

size(700, 700);

background(0);

noStroke();

}

void draw() {

background(0);

fill(250, 233, 77);

for (int i = 0; i < 7; i++) {

for (int j = 0; j < 7; j++) {

pushMatrix();

translate(50 + i * 100, 50 + j * 100);

// Setting 1

//float angle = sin(millis() / 1000.0) * PI/2;

// Setting 2

//float ratio = i/7.0;

//float angle = sin(millis() / 1000.0 + ratio * (PI/2)) * PI/2;

// Setting 3

float ratio = (i * 7 + j)/49.0;

float angle = sin(millis() / 1000.0 + ratio * (PI/2)) * PI/2;

rotate(angle);

rectMode(CENTER);

// Draw picture 1

rect(0, 0, 80, 80);

// Draw picture 2

// rect(0, 0, 100, 20);

// Draw picture 3

//rect(0,0,ratio * 50);

popMatrix();

}

}

} [/cceN_cpp]

Code Explanation

rectMode(CENTER) can change the drawing method of square. The oringinal former two parameters of rect are used to define the coordinate of left top corner of the sqaure. After we start this command, these two parameters will be used to set the coordinate for the square center point. Because here we operate the paterrn rotation through rotate, so we need to use this method to draw the center point to the original point of the coordinate.

millis() acquires the time from the program start to the present.The unit is ms.This value will influence the changing speed of sin output value. If we write millis directly, the changing scale is too big. Thus, we have to divide it by 1000.0.

In this section of code, we use comment symbol "//" to hide several settings. Youcan shift effects by start or close. For example, if we start sentences behind "Setting 3", we have to use comment symbol to close code blocks behine "Setting 1" and "Setting 2". As for examples of this similar program structure with different local variables, we can write in this format. Thus we don't have to store several engineering documents separately. We can use this skill often during practice and creation and preserve some satisfying parameter settings.

Among it, the influence of i,j value to the program is mainly represented by shifting "Setting 1 (Setting 2)(Setting 3)". You can compare the output results below.

Draw picture 1: Setting 1

6

Draw picture 1: Setting 2

7

Draw picture 1: Setting 3

8

Draw picture 2: Setting 1

9

Draw picture 2: Setting 2

10

Draw picture 2: Setting 3

11

In setting 1, we haven't used i and j to influence the rotate angle of each element. Thus we can see movement of every element is the same. While in setting 2, we have used i value and both i and j in setting 3. Finally they have influenced parameter input of function sin through ratio. This has changed the periodic change of angle. Because of the actual effect of setting 2 and setting 3 is not so obvious in the animated graphics, we can observe it from the following screenshot.

Draw Picture 2 (Left: Setting 2; Right: Setting 3)

Draw Picture 3 (Left: Setting 2; Right: Setting 3)

In the first picture, ratio is used to affect the square rotate angle. While the second picture, it is ised to control the radius of the circle directly. We can see that it has used i value sentence:

float ratio = i/7.0;

Its verticle element change is consistant. Because the horizontal coordinate forcontrolling the picture is only depend on the value of i, so patterms with the same horizontal coordinate will be the same. And the value of ratio, rotate angle and the radius of circle is the same too.

At the same time, we use i, j sentence:

float ratio = (i * 7 + j)/49.0;

It can discribe "gradient". Here, with the method of multiply a factor, it has combined the influence of rows and columns. So each element is different.

Step 7: While Loop

There is a brother for for loop. That is while loop. What for loop can do, while loop can do it too. But the using frequency of while loop in creativeCoding is not high as for loop.

Code Example (5-14):[cceN_cpp theme="dawn"] void setup(){

int a = 0;

while(a < 10){

println(a);

a++;

}

} [/cceN_cpp]

The grammar structure of while is easier to be understand than for . We can create variables before while statement. Then fill in an expression within square bracket. When it is satisfied, then operate the sentences within loop body. Finally we put an expression in the loop body to update the variables, then while loop is finished. As for the assured loop times, we often use for loop. As for indifinite variable value, we recommend you to use while loop .

Think:

Try to use all kinds of basic elements to replace drawing elements in for loop to create various different brushes.

Combine with trigonometric function refered in the last chapter, try to revise "scattering points" brush into round shape brush.

Try to make a two dimensional dot matrix with a for loop only.

Next Chapter PreviewAs with this course, you will find every new knowledge you learn, the possibility of playing will ommediately increased a lot . Program is a pandora box. Everything you can imagined, it can do it for you. So there is no reason for us not learning this language which can communicate with computers. In our next chapter, we will introduce another process control statement if to you. It can control process flow and generate more complicated and changeable results. With if statement, you can create your own text adventure games with ease!This article comes from designer Wenzy.Relative Readings:Interesting Programming Guidance for Designer——Processing Initial TouchInteresting Programming Guidance for Designer——Create Your First Processing ProgramInteresting Programming Guidance for Designer–Get Your Picture Running(Part One)Interesting Programming Guidance for Designer–Get Your Picture Running(Part Two)

Step 8: Source

This article is from: https://www.elecfreaks.com/11037.html

If you have any questions, you can contact: louise@elecfreaks.com.

Comments

About This Instructable

33views

2favorites

License:

Bio: ElecFreaks is an open design house founded in March 2011. Our goal is to create rapid prototypes and give small-batch manufacture solution for makers and ... More »
More by ElecFreaks:Elecfreaks Motor:bit User GuideCreate an Electric Spirit LevelHC-08 Bluetooth UART Communication Module V2.4 User Guide
Add instructable to: