Ben
Ben

Reputation: 307

Are "loops" a type of "Conditional Statement" in Java?

I have a project that reads: "There will be no conditional statements (if, switch, or,…)." I'm not sure if this includes for and while loops, since both technically run on conditions. Could I get away with saying that they're "conditional loops" instead?

Upvotes: 4

Views: 738

Answers (2)

Bohemian
Bohemian

Reputation: 425063

for and while loops use (terminating) conditions, not conditional statements, so on that basis loops are OK.

Apart from loops, another option would be the ternary operator ? - it's not a statement, it's an operator, and you may be able to code some conditional flow using these, ie this code:

int x;
if (<some condition>)
    x = 1;
else
    x = 2;

may be coded using the ternary operator as:

int x = <some condition> ? 1 : 2;

Upvotes: 2

wattostudios
wattostudios

Reputation: 8774

It would probably be acceptable to use loops (for, while,...), but you would need to check with the project author. I tend to treat loops and conditional statements separately, as they usually have different purposes...

  • Conditional statements like if and switch will make a choice out of a list of options. They only run once.
  • Loops like for and while are typically designed to run a piece of code multiple times.

Of course this is only a generalisation, and everyone probably has a different opinion, but I certainly treat them differently because they have different primary purposes.

For extra credit, Wikipedia seems to agree. The If Statement is a conditional operator, and the For Loop is an iteration statement.

Upvotes: 4

Related Questions