nested if statements

+5 Sylvester Chikoti · April 23, 2017
hi
if i put if statement inside for loop, would'nt i nest if statement?
something like:
for(int i=0; i<10;i++){
if(i==1){
//bla bla bla
else if(i==9)
//bla bla bla
}
}

Post a Reply

Replies

Oldest  Newest  Rating
+2 Nicholas Eason · April 26, 2017
I don't understand the question? If you put an if statement inside of a for loop, then you have an if statement?
for(int i=0; i<10;i++){
if(i==1){
//bla bla bla
else if(i==9)
//bla bla bla
}
}


Things within '{}' are just blocks. Almost anything can be within them.
0 Franz Schmidt · May 27, 2017
No you would not nest if statements.
Nicholas is right everything in {} are just blocks.

So if you expand the for loop it would look like this:
if(0 == 1){
//bla bla bla
}
else if(0 == 9){
//bla bla bla
}
if(1 == 1){
//bla bla bla
}
else if(1 == 9){
//bla bla bla
}
if(2 == 1){
//bla bla bla
}
else if(2 == 9){
//bla bla bla
}
...
...
if(9 == 1){
//bla bla bla
}
else if(9 == 9){
//bla bla bla
}


What you might want is called recursion and therefor you would need a function which calls itself:
void recursiveFunction(int arg){
if(arg == 1){
recursiveFunction(arg);
}
}

Recursion although can lead to endless loops like mine aboth if the arg would be 1. So you would need write your program carefully.
+1 Nicholas Eason · June 2, 2017
As a side note, you probably shouldn't be using a for loop if you're going to be checking the value of the loop-control variable to do a different thing for every single iteration.

For loops are nice when you need to iterate through something [x] amount of times, but if you are going to do something different for every single iteration, then just write the [x] calls instead of doing it inside a loop.
  • 1

Java / Android Development

120,976 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator