Module 2: Conditionals and loops Flashcards

1
Q

How do you take input from a user?

A

The scanner class.

Ex:

import java.util.Scanner

Scanner sc = new Scanner(System.in);
String name = sc.nextLine();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the if and else statements do?

A

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”);}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the ternary operator?

A

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”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a switch statement?

A

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”);}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the logical operators?

A

&& 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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a while loop?

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a for loop?

A

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);}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a nested for loop?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly