Jump to content

An Introduction to Dragon/Lessons/Control Structures

From Wikibooks, open books for an open world

Control Structures

[edit | edit source]

In this chapter we are going to learn about the control structures provided by the Dragon programming language.

Branching

[edit | edit source]
  • If Statement

Syntax:

	if(Expression)
	{
		Block of statements
	}
	else if(Expression)
	{
		Block of statements
	}
	else {
		Block of statements
	}

Example:

	select "types"
	select "graphic"
	nOption = int(prompt("1) Say Hello \n2) About")
	
	if nOption == 1	
	{
		name = prompt("Enter your name: ")
		showln "Hello " + name 
	}
	else if nOption == 2 
	{      
		showln "Sample : using if statement" 
	}
	else
	{ 
		showln "bad option..."
	}

Looping

[edit | edit source]
  • While Loop

Syntax:

	while(Expression)
	{
		Block of statements
	}


  • For Loop

Syntax:

	for (identifier=initialize value, terminating expression, step expression)
	{
		Block of statements
	}

Example:

	// print numbers from 1 to 10
	for (x = 1, x <= 10, x++)
	{
		showln x  
	}


  • Foreach Loop

Syntax:

	for (identifier : List/String)
	{
		Block of statements
	}

Example:

	aList = [1,2,3,4]  //create list contains numbers from 1 to 10
	for x : aList
	{
		showln x       // print numbers from 1 to 10
	}

Do While Loop

[edit | edit source]

Syntax:

	do {
		body
	} while (condition)

Example:

	x = 1 
	do {
		showln x 
		x++ 
	}
	while (x <= 10)