Intro to if Statements
Using Pushbuttons in Tinkercad Circuits
Today’s Task
What is a data type?
What is a data type?
A data type in programming stores a certain kind of value or information
What are examples of data types?
Let’s switch gears into:
if/else statements
What is an if statement?
What is an if statement?
An if statement will only run the code inside it when a certain condition is true
if statement
Let’s look at a few if statements. Assume int val = 5;
Will these statements be true or false?
2. if (val != 4)
3. if (val < 3)
4. if (val > 5)
5. if (val >= 5)
if statement
Let’s look at a few if statements. Assume int val = 5;
Will these statements be true or false?
true
2. if (val != 4)
3. if (val < 3)
4. if (val > 5)
5. if (val >= 5)
if statement
Let’s look at a few if statements. Assume int val = 5;
Will these statements be true or false?
true
2. if (val != 4)
true
3. if (val < 3)
false
4. if (val > 5)
false
5. if (val >= 5)
true
What is an else statement?
What is an else statement?
An else statement will run the code inside it when the previous if statement isn’t true
You can’t have an else statement without an if
else statement
Let’s look at a few if/else statements.
What is the condition for the else?
---
else
---
2. if (val > 5)
---
else
---
else statement
Let’s look at a few if/else statements.
What is the condition for the else?
---
else // val != 5
---
2. if (val > 5)
---
else // val <= 5
---
Let’s build our circuit!
Start from one pushbutton circuit
Declare variables BEFORE setup()
So far, we have only written code within the brackets of setup() and loop()�
Now, we are declaring our variables at the beginning of the program before both functions so they can be used throughout the whole program.
Declare pinMode()
If la is true, turn on led1
* The LED depends on boolean value la
If la is not true, turn off led1
If the button is pressed, set la to false
*boolean value la depends on whether or not the button is pressed
If the button is not pressed, set la to true
*boolean value la depends on whether or not the button is pressed
Run your code!