Monday, December 26, 2011

2.1.2. "if" and compound statements

We discussed that the basic format of "if" is if (condition) statement; That "sentence" can be a single statement or a compound one. Compound statements are formed by grouping a number of simple statements using curly braces ("{" and "}"), as in this example:

/*---------------------------*/
/* C# Example #6: */
/* example06.cs */
/* */
/* Conditions with if (2) */
/* Compound statements */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
 
using System;
 
public class Example06
{
public static void Main()
{
int number;
 
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
if (number > 0)
{
Console.WriteLine("The number is positive.");
Console.WriteLine("Remember you can also use negative numbers.");
} /* End of "if" */
} /* End of "Main" */
} /* End of "Example06" */
 

In this case, if the number is positive, we write a text and then... we write another (we might have used only one "WriteLine" to display both texts, separated with a "line break"; we will learn more complex things to do within a compound statement later).

As shown in this example, each new "block" is usually written a little more on the right than the others, so it's easy to see where each section begins and ends. For example, the content of "Example06" is a little more to the right than the header "public class Example06", and the content of "Main" even more to the right, and also the compound statement after the "if statement. This extra spacing of the text is often called "indented writing". A typical size for indentation is 4 spaces, although in this text many times we will use only two spaces, not to reach the right margin of the paper too easily.

No comments:

Post a Comment