-
Notifications
You must be signed in to change notification settings - Fork 2
4) Data Structures
When your program needs to make a decision, use an if statement. The form of the if statement follows this generic pattern: if(whatever your condition is){stuff to do if the condition is true}
. Try it out; type
if(1 == 1){
System.out.println("If is working!");
}
and run the resulting program. You will see that If is working!
Else is the default condition if the conditional is false, and they cannot exist without a if statement directly above it. For example,
if(1 == 2){
System.out.println("Something is wrong...");
}
else{ // no conditional here
System.out.println("else is working too!");
}
Running this program will show you that else is working too! Note that else does not require a conditional statement; in fact, the compiler will be very unhappy when you try to put the conditional there. If and else will help programmers make programs that can have many different outcomes and programs that can think for themselves.
When you want something to happen over and over again a number of times, you can use a loop instead of typing it over and over. For example, say you want to print out all the numbers between 1 and 100. Instead of writing 100 System.out.println statements, you can write
for(int i = 1; i <= 100; i ++){
System.out.println(i);
}
These three lines give the same result as typing the 100 print statements. For loops follow the pattern: 'for(initialize whatever you are iterating; the ending statement; how much to iterate by){stuff you want to iterate}`. For the above example, i is the iterating variable and is initialized to a value of 0, we want to iterate to 100 including 100, and we want to iterate every integer (++ is a fancy way of saying i = i+1).
These work in a similar way to for loops, except you usually don't know how long this will run for. While loops follow this pattern: while(some condition is true){do all of this stuff}
. That conditional can be anything, as long as it changes into a false statement at some point. Otherwise, your program will run forever!