Previous Topic Next topic Print topic


Conditionals - in COBOL and C# and VB.NET

C# COBOL VB.NET
greeting = age < 20 ? "What's up?" : "Hello";

// Good practice is that all consequents are enclosed in {}
// or are on the same line as if.
if (age < 20) greeting = "What's up?";
else
{
   greeting = "Hello";
}

// Multiple statements must be enclosed in {}
if (x != 100 && y < 5)
{
  x *= 5;
  y *= 2;
}

//No need for _ or : since ; is used to terminate each statement.

if (x > 5)
{
   x *= y;
}
else if (x == 5)
{
   x += y;
}
else if (x < 10)
{
   x -= y;
}
else
{
   x /= y;
}

// Every case must end with break or goto case 
switch (color)                       // Must be integer or string
{
  case "pink":
  case "red":    r++;    break;
  case "blue":   b++;    break;
  case "green":  g++;    break;
  default:    other++;   break;      // break necessary on default
}
declare age as binary-long = 10
declare greeting as string
*>greeting = age < 20 ? has no directly equivalent syntax in COBOL

if age < 20
   move "What's up?" to greeting
else
   move "Hello" to greeting
end-if

declare x as binary-long = 200
declare y as binary-long = 3
if x not = 100 and y < 5
   multiply 5 by x
   multiply 2 by y
end-if



*> evaluate is preferred in COBOL rather than if/else if/else
evaluate x
when > 5
   multiply y by x
when 5
   add y to x
when < 10
   subtract y from x
when other
   divide y into x
end-evaluate





declare color as string = "blue"
declare r b g other-color as binary-long
evaluate color   *> can be any type
when "pink"
when "red"
   add 1 to r
when "blue"
   add 1 to b
when "green"
   add 1 to g
when other
   add 1 to other-color
end-evaluate
greeting = IIf(age < 20, "What's up?", "Hello")

' One line doesn't require "End If"
If age < 20 Then greeting = "What's up?"
If age < 20 Then greeting = "What's up?" Else greeting = "Hello"

' Use : to put two commands on same line
If x <> 100 And y < 5 Then x *= 5 : y *= 2


' Preferred
If x <> 100 And y < 5 Then
  x *= 5
  y *= 2
End If


' To break up any long single line use _
If whenYouHaveAReally < longLine And _
  itNeedsToBeBrokenInto2 > Lines Then _
  UseTheUnderscore(charToBreakItUp)

If x > 5 Then
  x *= y
ElseIf x = 5 Then
  x += y
ElseIf x < 10 Then
  x -= y
Else
  x /= y
End If





Select Case color   ' Must be a primitive data type
  Case "pink", "red"
    r += 1
  Case "blue"
    b += 1
  Case "green"
    g += 1
  Case Else
    other += 1
End Select

Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.

Previous Topic Next topic Print topic