Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Conditions in a programming language are instructions such as the further program flow. Similar to rail traffic. A train travels on a rail until it hits a switch, then the train changes its direction of travel. The same applies to conditions in a program.


Conditions therefore change the course of a program. But according to which criteria is decided how the program process continues? The answer to this is logical operations based on the Boolean logic. Sounds more complicated than it is. We use logical operations in everyday life, here are some examples:

  • When I'm hungry or thirsty, I go to the kitchen and get something
  • If I have enough money and I have time, then I'll make a trip to India

In a programming language the spelling is different but the logic behind it remains the same.

  • equal to ==
  • not equal !=
  • greater than >
  • less than <
  • greater than or equal to >=
  • less than or equal to <=
  • logical And &&
  • logical Or ||


In the code this looks as follows:

int x=10;
if(x == 10)
{
   println("x is the same as 10");
}
else
{
   println("x is not the same as 10");
}


The code can almost be read out as intelligible language: If x is 10, write "x is equal to 10", if not then write "x is not equal to 10".

The syntax of a condition is always:

if([boolisch expression])
 {
 // block der ausgeführt wird wenn der boolische Ausdruck True ist
 }
 else
 {
 // block der ausgeführt wird wenn der boolische Ausdruck False ist
 }


Of course there are also some variants of writing style:

int x=10;
  
// Bedingung ohne Klammer-Block, die Bedingung
// geht in diesem Fall bis zum nächsten Semikolon
// das else ist ebenfalls optional
if(x == 10)
println("x ist gleich 10");
  
// Hier eine Bedinung mit mehreren Fällen
// zu Beachten ist die schreibweise von 'else if'
if(x == 10)
println("x ist gleich 10");
else if(x == 9)
println("x ist gleich 9");
else if(x == 8)
println("x ist gleich 8");
else
println("x ist nicht 10,9 oder 8");


For the multiple cases, there is a simpler version:

int x=10;
switch(x)
{
case 10:
println("x ist gleich 10");
break;
case 9:
println("x ist gleich 9");
break;
case 8:
println("x ist gleich 8");
break;
default:
println("x ist nicht 10,9 oder 8");
break;

Exercise 

Programm a drawing program. The color can be changed with the buttons '1' - '5'. The left mouse button is draws and the right mouse button is used to erase it.