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