A Beginner's Guide to D/Conditions and Loops/Simple Branching

From Wikibooks, open books for an open world
Jump to: navigation, search

The if Conditional[edit]

Example: More Complicated Input - a program that asks age and makes a "clever" response

import std.c.stdio;
import std.stdio;

void main()
  // Create a variable that can hold an integer
  int age;
  // writef does not flush on all platforms. If you remove fflush
  // below, the text might be written after you enter your number.
  writef("Hello, how old are you? ");

  // scanf reads in a number. %d tells scanf it is a number and the number
  //   is placed in the variable 'age'.
  // The & sign in &age tells the compiler that it is a reference to the
  //   variable that should be sent. 

  // Print different messages depending on how old the user is.
  if(age < 16) 
    // If age is below 16 you are not allowed to practice car-driving in Sweden
    writefln("You are not old enough to practice car driving!");
  else if (age < 18) /* 16 <= age < 18 */
    writefln("You may practice if you have a permission, but not drive alone!");
  else /* You are at least 18 so everything should be alright */
    writefln("You may drive as long as you have a licence!");