Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

What are the pros and cons of using a for loop versus an if then statement?

+14 votes
I feel like sometimes these two things have an overlapping domain in Java, and sometimes you can achieve the same output using either method.  Is one of them a "better" go to or is this more of a specific question, and it depends on the situation?
asked Sep 27, 2016 in CSC 211 (F16) by Audrey Hogenkamp (100 points)

4 Answers

+6 votes

FOR loops and IF statements may look similar, but they are really very different in practice.

FOR loops are for doing repetitive execution -- you have a piece of code that you would like to run multiple times.

IF statements are about conditional execution: you have a piece of code that you might or might not want to run, depending on some condition.

Perhaps some other students can chime in with answers that have examples of when to use each...

answered Sep 27, 2016 by Forrest Stonedahl (3,438 points)
0 votes
As you will learn in  CSC-285, although in some instances where a for loop and an if statement both work, for loops can reduce redundancy in your code and can make it more efficient, easier to read, and simpler.  If there are only a couple conditions in which you are checking, then don't bother with a for loop, just use a couple if/else statements.  However, if you are checking through LOTS of conditions...then a for loop would be preferred because then you won't have lines and lines of if/else statements.
answered Sep 27, 2016 by Troy Barger (100 points)
0 votes
I believe loops are more for repeating a statement multiple times, and if/else statements work more as an editing /conditional agent TO what you want to execute. For instance, if you wanted to run a statement 5 times

you would have to use a loop ( i =0; i <5; i++) {

 but if you wanted to edit the code to execute something else when"  i "is a certain number you would use an if/else statement. For example, printing a different string, but only when" i " is even.
answered Sep 28, 2016 by Paige Oucheriah (240 points)
0 votes
FOR loop is used to repeat the same statement, while IF STATEMENT is used to process statements with conditions provided. I think it's totally different, so it's not easy to weight the pros and cons of the 2 methods.
answered Oct 3, 2016 by Trung Le (Jayden) (206 points)