Conditional Statements

Conditional statements are used where your program must evaluate whether a logical statement is true or false. These include, but are not limited to:

IF-THEN-ELSE

General form:
IF(CONDITION evaluates to TRUE) THEN
    DO SOMETHING
ELSE
    DO SOMETHING ELSE
C/C++ / C#.NET / Java
    if(x == 1)
	{
		// do something
	}
	else
	{
		// do something else
	}
VisualBasic.NET
    If foo = "bar" Then
	    ' do something
	Else
	    ' do something else
	End If

WHILE, DO-WHILE, and DO-UNTIL loops

General form:
WHILE(CONDITION evaluates to TRUE)
    DO SOMETHING
LOOP

DO
    SOMETHING
WHILE(CONDITION evaluates to TRUE)

DO
    SOMETHING
UNTIL(CONDITION evaluates to TRUE)
C/C++ / C#.NET / Java
while(choice != 'x')
{
    // do something
}

do
{
    // do something
} while(choice != 'x')

do
{
    // do something
} while(choice == 'x')
VisualBasic.NET
While repeat = True
    ' do something
End While

Do While repeat = True
    ' do something
Loop

Do Until repeat = False
    ' do something 
Loop

FOR and FOREACH loops

General form:
FOR(ITERATOR; CONDITION; INCREMENTOR)
    DO SOMETHING
	
FOREACH(ELEMENT in COLLECTION)
    DO SOMETHING
C/C++
for(int i = 0; i < 10; i++)
{
    // do something
}
C#.NET
int x = 10;
for(int i = 0; i <= x; i++)
{
    // do something
}

foreach (Control ctrl in this.Controls)
{
    // do something
}
Java
int x = 10;
for(int i = 0; i <= x; i++) {
    // do something
}

for (Control ctrl : this.Controls) { 
    // do something
}
VisualBasic.NET
For Each ctrl As Control In Me.MainForm.Controls
    ' do something
Next ctrl

SWITCH or SELECT CASE statements

General form:
SWITCH (COMPARITOR)
    CASE (VALUE1):
	    DO SOMETHING
		BREAK
    CASE (VALUE2):
	    DO SOMETHING
		BREAK
	CASE (DEFAULT VALUE):
	    DO SOMETHING
		BREAK
END SWITCH
C/C++ / C#.NET / Java
switch(rdb.Name)
{
    case "button1":
	    // do something
		break;
		
	case "button2":
	    // do something
		break;
		
	default:
	    // do something
		break;
}
VisualBasic.NET
Select Case option
    Case 0
	    ' do something
	Case 1
	    ' do something
	Case Else
	    ' do something
End Select

Older Newer