Conditional statements: if
Very often, you need to make choices in your program: Some actions need to happen only when particular situations occur. For that, you can use conditions that allow you to control the flow of your program.
real life: if you are hungry, get something to eat //it is not really healthy to eat all the time...
growing circle: if the circle exceeds the screen, it should start over.
A conditional statement has always 2 parts:
- An action (what to do). This can be any set of statements
- A condition (when to do the action). The condition is always a test, a decision.
* Conditions are expressions (combinations of values and operators) that evaluate to true (yes) or false (no) (true and false are reserved words) * If the condition is true (and only then), the code inside the {} will be executed. Afterwards, the program continues with the next statement after the {} *If the condition is false, the code inside the {} is SKIPPED and the program jumps to the first statement after the {} |
How do you write conditions? Relational operators
Less than | < |
Greater than | > |
Equal | == |
Not equal | != |
Less or equal | <= |
Greater or equal | >= |
Expression | In plain English... | Answer |
---|---|---|
2>3 | is 2 greater than 3? | no, false |
5>3 | is 5 greater than 3 ? | yes, true |
2==3 | is 2 equal to 3? | no, false |
pow(2,3)>0 | is the result of pow(2,3) greater than 0? | yes, true |
x>=0 | is x greater or equal to 0? | it depends! |
*IMPORTANT! Do not confuse '=' (assignment) with '=='(equality)
x=1; //give variable x the value 1
x==1 // is x equal to 1?
Examples
if (my_var>5) { //is my_var greater that 5? if yes
rect(100,100,20,20); // draw a rectangle
}
//what will this draw for my_var=1, my_var=10, my_var=5?
--------------------------------------------------
if (my_var>5) {
rect(100,100,20,20);
}
ellipse(50,50,20,20);
//what will this draw for my_var=1, my_var=10, my_var=5?
So, how can I make my growing circle smarter?
In words: if the circle exceeds the screen, it should start over.
if (exceeds the screen) { //but what does "exceed the screen" actually mean?
start over //and how does it start over?
}
--------------------------------------------------
//a smarter growing circle
int diameter=0;
void setup() {
size(200,200);
}
void draw() {
diameter=diameter +1;
if (diameter>width) {
diameter=0;
}
ellipse(width/2,height/2,diameter,diameter);
}