Module 2: Conditionals and loops Flashcards
How do you take input from a user?
The scanner class.
Ex:
import java.util.Scanner
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
What does the if and else statements do?
If executes code if its condition is true, if false the else code executes.
Ex:
int x = 5;
if(x>3) {System.out.println(“Welcome”);} else {System.out.println(“Too young”);}
What is the ternary operator?
A statement that checks a condition and outputs code depending if the condition is true or false.
Syntax:
variable = (condition) ? expressionTrue : expressionFalse;
Ex:
int time = 20;
String result = (time < 18) ? “Good day” : “Good evening”;
What is a switch statement?
A conditional used to see if a variable is equal to a list of values.
Ex:
int day = 3;
switch(day) {case 1: System.out.println(“Monday”); break; case 2: System.out.println(“Tuesday”); break; case 3: System.out.println(“Wednesday”); break; default: System.out.println(“Different day”);}
What are the logical operators?
&& AND (Returns true if both statements are true)
|| OR (Returns true if one of the statements is true)
! NOT (Reverses the result, returns false if the result is true and vice versa)
What is a while loop?
A conditional that repeatedly executes if its condition is true.
Ex:
int x = 5;
while(x>0) {System.out.println(x); x-=1:}
Do while loops always execute once, regardless if the condition is true.
Ex:
int x = 10;
do {System.out.println(x); x++;} while(x <15);
What is a for loop?
A conditional that executes a certain amount of times.
Syntax:
for (statement 1; statement 2; statement 3)
{//code block to be executed}
Ex:
for(int x=10; x<=40; x+=10) {
if(x == 30) {
break;} System.out.println(x);}
What is a nested for loop?
A for loop inside another for loop. The inner loop executes 1 time (until its condition is false) for each iteration of the outer loop.
Ex:
for(int i=1; i<=2; i++) {System.out.println(“Outer: “ + i); for(int j=1; j<=3; j++) {System.out.println(“Inner: “ + j);}}
Outer loop executes 2 times, inner loop executes 6 times.