Page 1 of 1

Control Structures (loops, ifs and switch)

#1 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Posted 05 March 2011 - 11:52 AM

*
POPULAR

Learning C# Series


Control Structures (loops, ifs, and switch)

Welcome to my tutorial on Control Structures (or constructs for short). In this tutorial, we shall go through each control structure in turn, and then we shall finish by demonstrating them in use with a basic example.

Why is this important to learn about?

Control structures are one of the most fundamental concepts in any programming language you will come across. If you want to know C#, and if you want to learn to program with any language, you must have a firm grip on the control structures of the language.

Generally speaking, if you learn them in one language, you will pick them up in different languages very quickly.


Definitions of terms used.

Iteration – This is the act of repeating something (that ‘something’ being code statements in the programming context).

Conditional – A conditional action is said to be one that is only performed if a certain condition is true.


Note: All examples were created using Visual Studio 2010, targetting the .NET Framework 4.0. We'll do our best to point out anything that might not work in older versions.

Control Structures (loops, ifs, and switch)

Before we begin, you should have a reasonable understanding of:

  • Data Types
  • Operators


A basic knowledge of methods would be useful, but is not required.

Right let's get started!

C# has two general types of control structures:

  • Iteration (often called 'loops')
  • Decision (sometimes called 'conditionals', or 'selection statements')


Note that all examples are written in a ConsoleApplication’s Main() method.

Iteration Constructs

Iteration constructs (otherwise known as loops) allow us to repeat code in a cyclic fashion. There are 4 types of iteration constructs in C#, each of which are covered next.

For Loops

For loops allow us to specify the number of times to repeat a block of code. It is best demonstrated with an example:

for (int i = 1; i <= 5; i++)
{
   Console.WriteLine(i);
}




This basic example prints out all the numbers from 1 to 5. How does it do this? I shall go through what happens when the loop executes, step by step:

1. An integer variable called ‘i’ is declared and set equal to 1 in this line; int i = 1. This is called the initialisation variable.

2. The condition i <= 5 is checked. If ‘i’ is less than or equal to 5, then the body of the loop is executed. Otherwise, the loop terminates. 1 is less than 5, so the condition evaluates to true, and the body (the code statements in the curly braces) of the loop executes.

3. Once the body has been executed once (and the value of ‘i’ has been printed out, which, of course, is currently 1). Next, this statement is executed; i++. This means ‘increment the value of ‘i’ by 1.’ Consequently meaning that ‘i’ now equals 2.

4. Now, the condition i <= 5 is evaluated again. ‘i’ is now equal to 2, of which is less than 5, so the loop body executes again, printing out 2.

5. i++ is then executed, meaning ‘i’ is now 3. i <= 5 evaluates to true as 3 is less than 5, so the “3” gets printed out to the console.

6. i++ is executed again, meaning ‘i’ equals 4, which is still less than 5, so the loop body executes again, leading to 4 being printed.

7. i++ is executed once again, meaning ‘i’ equals 5. i <= 5 is testing if ‘i’ is less than OR equal to 5. ‘i’ is now equal to 5, so it still evaluates to true, meaning the loop body is executed again, thus printing out 5.

8. i++ is executed again, meaning ‘i’ now equals 6. Now, i <= 5 evaluates to false. Therefore, the loop terminates as the terminating condition has evaluated to false. The loop doesn’t get executed any more, and the program can continue to execute statements that come after the loop.

Thus, we see numbers from 1 to 5 printed out to the console in this example.

Note that you can use any condition as the terminating condition, as long as it evaluates to true of false :)/>.


A few points to note:

  • The i++ statement can be changed to any other valid statement that modifies the variable ‘i’. A few examples include; i--(decrement the variable by 1), i += 2 (add 2 to the variable) etc.

  • In our example, the scope of the variable ‘i’ is limited to the body of the for loop. So, if we did this:


for (int i = 1; i <= 5; i++)
{
   Console.WriteLine(i);
}

Console.WriteLine(i); //’i’ is not available here




, we would get an error saying ‘i’ does not exist in the current context. This is because ‘i’ is not available outside of the for loop.

To get around this, we can declare the initialisation variable (‘i’), before the for loop, like this:

int i;

for (i = 1; i <= 5; i++)
{
   Console.WriteLine(i);
}

Console.WriteLine(i);




We declare ‘i’ before the loop. This is perfectly valid as ‘i’ is now not limited to within the for loop. This code will print out numbers 1 – 6. The loop prints out numbers 1 – 5, then the line after the for loop will print out the value of ‘i’, which, by that point, will be 6, due to the how the for loop increments ‘i’ with this statement; i++.

  • Finally, you can have multiple initialisation variables in a single for loop. This example doesn’t produce any meaningful output, but it demonstrates the idea:


for (int i = 1, j = 6; i <= 5; i++, j--)
{
     Console.WriteLine(i);
     Console.WriteLine(j);
}




Notice how we use the comma ‘,’ to declare two int variables; ‘i’ and ‘j’. We can still only use one condition in the for loop. We then have two statements (again, separated by a comma). One that increments ‘i’, and once that decrements ‘j’.

You can use this principle to build some quite complex for loops!

Here is an example for you to look at. It prints out the 6 times table, all the way up to 6 times 12. Can you see how it works?

for (int i = 6, j = 0; j <= 12; j++)
{
    Console.WriteLine(i*j);
}



Spoiler


Foreach Loops

Foreach loops (sometimes called “foreach, in” loops) are used to loop through items in an array or a collection. The collection/array must implement an interface called IEnumerable (or IEnumerable<T> if the collection is generic). This interface will be covered in the collections tutorial later in this series. For now, it is enough to say it is a way to ensure that an enumerator can be obtained for the collection, of which is needed to allow iteration through the collection.

Here is an example of its use:

//declare an array to hold some numbers
int[] array = new int[] { 1, 5, 3, 8, 3, 5, 8, 6, 10 };

//foreach loop
foreach (int i in array)
{
   //this gets executed once ‘for each’ number in the array
   Console.WriteLine(i);
}



We first declare an array of numbers. Arrays do implement IEnumerable, and so we can use a Foreach loop to loop through each number in the array, one at a time, executing the body of the loop (the code in between the curly braces) 'for each' element.

The variable ‘i’ in the above is the variable that holds the current element/number, and is of type int because the elements in our array are of type int. On the first loop through, ‘i’ is 1, the second, it is 5 and so on until we reach the end of our array.

In this example, we print each number in the array to the console using the Console.WriteLine() method.

The important thing to recognise with foreach loops is that you cannot add to, or remove from, the collection from within the loop body.

Any attempt to add to, or remove from, the collection will lead to an InvalidOperationException that reads something like this:

Quote

Collection was modified; enumeration operation may not execute.


If you need to add to, or remove from, the collection, use a for loop.


While Loop

The while loop is used to repeat a block of code, while a certain condition remains true.

It is similar in concept to a for loop, and they can be practically used interchangeably. However, using a certain type over another can make your life easier in certain situations. For example, when you know exactly how many iterations you need, a for loop will be the easiest loop to use. Having said that, you could equally use a while loop, with a little bit of extra code, to loop a certain number of times.

It's about making a choice based on your situation :)/>.

Here is an example:

            
Console.WriteLine("Enter 'Q' to quit the while loop. Enter anything else to loop again");
 
while (Console.ReadLine().ToUpper().Equals("Q") == false)
{              
   Console.WriteLine("Still in while loop");
}

Console.WriteLine("While loop ended");




Here, we first print out a message telling the user what to do. Then, we get to the while loop. Inside its parentheses ‘()’ goes the Boolean condition to test. It will continue looping until the condition inside the parentheses evaluates to false.

What is happening with that condition?

We read it from left to right. Firstly, Console.ReadLine() reads what the user has entered, and then ToUpper() converts it to upper case. We then use Equals() to compare what the user has entered to “Q”. If they are equal, Equals() will return true, otherwise, it will return false.

Now, we want to continue looping until the user enters “Q”, therefore, we want to loop while the input isn’t equal to “Q”. Therefore, we compare the value returned by Equals() to false. If Equals() returns false, continue looping as the user didn’t enter “Q”. If it returns true, then we don’t want to continue looping, as the user has signalled that they have finished by entering 'Q'.

On every loop, we display a message saying that we are still in the while loop.

Once the loop exits because the user entered “Q”, we print a message alerting the user to this fact. Just so you can see that the loop has terminated.


Do While

Now, imagine that we have written our while loop as above, and it is working fine. However, you then realise that if the user starts up the program, and then enters “Q” straight away, the loop won’t execute at all! Therefore, your message; “Still in while loop” won’t get displayed at all. You want the message to be displayed at least once.

How do we do that then? Well, for the message to be displayed at least once, the loop body needs to execute at least once. We need some way of ensuring that at least one loop cycle is executed.

Enter the do while loop!

To ensure the message is displayed at least once in the above while loop example, we could change it to this:

do{

     Console.WriteLine("Still in while loop");

} while (Console.ReadLine().ToUpper().Equals("Q") == false); //remember the semi-colon here :)/>/>

Console.WriteLine("While loop ended");


Notice how we use the ‘do’ keyword to show the block that we want repeating (the loop body), and notice how the while() condition comes after the body of the loop. The affect of this is that the message “Still in while loop” is always shown at least once, even if the first thing the user enters is "Q".

When the user starts up the program, the message “Still in while loop” will be displayed as the body of the while loop will execute once, and only then will it check the condition in the parentheses to check if the user has entered "Q".

This makes the do while loop ideal for situation when you need to guarantee that the body of the loop is executed at least once.


Decision Constructs

Decision constructs are used to control the flow of our programs. They allow us to run certain blocks of code once, only if a certain condition is true.

There are two key types of decision constructs in C#:

  • if/else/else if
  • switch



If Statements

As suggested, the if statements come in various different forms, each of which is described below:

if statement – This is used to execute some code ONCE, only when a specified condition is true.

if...else statement – This is an extension to the standard if statement. It allows to specify the code that should run, if the condition in the first if statement evaluates to false.

if...else if....else statement – This is used to select from multiple different blocks of code. It is often very similar to the switch statement which we shall cover soon.

If statements allow you to choose which code gets executed.

Here are some examples to demonstrate each version:

We first get the user to enter an integer:

Console.WriteLine("Enter a number"); 
 
//this line just tries to convert the string entered into a number
int i = int.Parse(Console.ReadLine());



Now, we could display a message if the number entered is less than 10:

if (i < 10)
{
   Console.WriteLine("Number is less than 10!");
}




Simple enough, right? If (and only if) ‘i’ is less than 10, display the message.

However, if ‘i’ is not less than 10, the user gets no message. This isn’t very friendly.

To get around this, we need to display a message if the number entered is NOT less than 10. To do this, we can use an ‘else’ block:


  if (i < 10)
  {
      Console.WriteLine("Number is less than 10!");
  }
  else
  {
      Console.WriteLine("Number is NOT less than 10!");
  }



This ensures that a message will always be displayed if the user enters a valid integer. If it is less than 10, the first message is displayed; else the other message is displayed.

Note that you can combine multiple conditions in a single if statement by using the && and || operators. They are read as 'and' and 'or' respectively. For example, you could do this to execute code only when the number entered is below 20, but greater than 10:

if(i < 20 && i > 10)
{
   //code to excecute here
}


It is important to realise that we cannot write this:

if(i < 20 && 10)
{
   //code to execute here
}


We must exlicitly state the variable we are comparing against for every condition. You can use as many '&&' and '||' operators as you like in a single if statement. You can also combine the two.

if( (i < 20 && i > 10) || (i < 30 && i > 20) )
{
  //code to execute here
}



This can be read as; "if 'i' is less than 20 and greater than 10, OR, if 'i' is less than 30 and greater than 20", execute this code.

These two operators work a 'short circuit' system. If the first expression in an 'or' condition evaluates to true, there is no point in executing the second expression as we know the 'or' condition as a whole is going to evaluate to true, as only one expression needs to be true in an 'or' condition to make the whole condition true.

Likewise, if the first expression in an 'and' condition evaluates to false, as both expressions have to be true for an && expression to be true, we already know that the condition is going to evaluate to false without even looking at the second expression.

You should have already covered the different operators in an earlier tutorial :)/>.


Now, moving onto the last variation of if statement...

Here’s an example of the most complex standalone if statement you will see:

  if (i == 10)
  {
     Console.WriteLine("Number is 10!");
  }
  else if (i == 20)
  {
     Console.WriteLine("Number is 20!");
  }
  else if (i == 30)
  {
     Console.WriteLine("Number is 30!");
  }
  else
  {
     Console.WriteLine("Number is NOT 10,20 or 30");
  }



This first checks if the number is 10, if it is, it displays the first message, else, if the number is 20, it displays the second message etc. If the number isn’t 10, 20 or 30, we shall drop all the way down to the else statement, where another message will be displayed, telling the user that the number wasn’t 10, 20 or 30.

NOTE: The expression (the condition that is being tested) in the parentheses of if statements needs to be a Boolean. In other languages like C++ and PHP, you can just put numbers on their own in if statements and they are converted automatically to Boolean values (0 is false, everything else is true). You cannot do that in C#. The condition has to be able to be directly evaluated as a Boolean (true or false).

Also, you can compare strings, objects etc in if statements. You are by no means limited to numbers!



Switch Statement

Now, the last example I showed (the if/else if/else) can be written in a clearer manner using something called a switch statement.

A switch statement allows use to execute code based on a predefined set choices.

Here is the previous example written as a switch statement:


            switch (i)
            {
                case 10:
                    Console.WriteLine("Number is 10!");
                    break;
                case 20:
                    Console.WriteLine("Number is 20!");
                    break;
                case 30:
                    Console.WriteLine("Number is 30!");
                    break;
                default:
                    Console.WriteLine("Number is NOT 10,20 or 30");
                    break;

            }



The value we want to compare with our predefined values is placed in the parentheses of the switch, and must be a String or an Integral type. Then, we list our different choices (or ‘cases’), which, unlike with the if statement, must each be a constant expression. This does exactly the same thing as the if/else if statement above. If 'i' is 10, execute the 'case 10:' block, if it is 20, execute the 'case 20:' block etc.

Notice the use of ‘default’. This specifies the default case to be executed if none of the other cases match the input. It is equivalent to an ‘else’ statement. The default case is optional, but the use of the ‘break’ keyword is not.

The break keyword is a terminating statement. Without it, something called ‘fall-through’ would occur.

Say the user enters 10, meaning the first case will be satisfied and the message Number is 10!" will be displayed. Without the ‘break’ statement, all the other messages would also be displayed also. We would ‘fall through’ and execute the remaining cases too.

To avoid this, the C# compiler demands that you use the ‘break’ keyword on every case; even the ‘default’ case.

If you miss a break statement for case 10 in the above example, you will see an error message like this:

Quote

Control cannot fall through from one case label ('case 10:') to another


Note: you can also use the ‘return’ keyword instead of the ‘break’ keyword to prevent fall through. The reason you would use the ‘return’ keyword is if you wanted to return a value from a method using a switch statement to decide what value to return.


Continue and Break Keywords

We have already met the ‘break’ keyword in the context of the switch statement. However, these keywords are more often used in the iterations constructs (loop) we covered earlier. They are usually used in conjunction with the if statement constructs, to manipulate loops when certain conditions are met.


The ‘continue’ keyword is used to instantly move to the next iteration of a loop body.

We could use it to print out all the multiples of 5 between 1 and 20 for example:

for (int i = 1; i <= 20; i++)
{
     if (i % 5 != 0)
     {
        continue;
     }

     Console.WriteLine(i);
}




I am sure that you can see, this for loop starts with ‘i’ equal to 1, it executes the body of the loop (in between the curly braces), and increments the variable ‘i’, until the variable ‘i’ equals 21, at which point, it stops looping.

Now, on every loop, the condition in the if statement is tested. What it does is it divides the current value of ‘i’ by 5, and if it is exactly divisible (i.e. it’s a multiple of 5), it returns 0.

Therefore, if i % 5 does not equal 0, it means the current value of ‘i’ isn’t a multiple of 5. i % 5 != 0 will evaluate to true (remember that != is the NOT EQUAL TO operator) and the continue statement will be executed. This skips to the next iteration, totally skipping the Console.WriteLine(i) statement, as we don’t want to print ‘i’ if it isn’t a multiple of 5.

Here is what is happening for the first couple of loops:

‘i’ begins as being equal to 1, and so i % 5 != 0 is true as 1 isn’t a multiple of 5. Therefore, the continue statement is executed. As soon as the continue statement is executed, i++ is executed, and the next loop begins, starting at the if statement again. Thus meaning that Console.WriteLine(i) is completely skipped.

When ‘i’ equals 5, for example, i % 5 != 0 evaluates to false, as 5 is a multiple of 5 (obviously!), meaning the continue statement is NOT executed. Therefore, the number is printed out with Console.WriteLine(i).

Basically, when you see a continue statement, read it as “start the next iteration (loop) immediately, and skip any other code in the loop’s body that may come after the continue statement.”


The ‘break’ keyword, when used in the context of loops, can be read as “break out of this loop immediately, and do not loop any more.”

If we wrote this, for example:

for (int i = 1; i <= 20; i++)
{
     if (i == 10)
     {
         break;
     }

     Console.WriteLine(i);
}




Console.WriteLine(“The loop has finished executing”);

, we would see numbers 1 -9 printed to the console, followed by the message; “The loop has finished executing”.

This is because when ‘i’ equals 10, the if statement condition i == 10 evaluates to true, meaning the break statement is executed, and execution immediately breaks out of the loop and drops to the code after the loop, without finishing the current loop.

Further, as with the switch statement, a ‘return’ statement will cause the loop to terminate also, but you can return a value from a method at the same time using ‘return’.

(NOTE: Technically, there is another statement through which a loop can terminate, and that is via the use of the ‘throw’ keyword. You’ll get to that in the Exception Handling tutorial :)/>).


An example that combines different constructs

In this example, I am going to write a program to calculate the average of list of numbers that the user enters. It is a very ‘around the houses’ approach, but it illustrates many of the constructs explained in this tutorial in use.

Here is the code with some detailed comments:

            //declare a do-while loop as we want the user to always be able to
            //calculate the average AT LEAST once. A do-while loop ensures the loop
            //is executed at least once
            do
            {
                //declare a list collection that will hold the numbers the user enters
                List<int> numbers = new List<int>();

                //ask user how many numbers they plan to enter
                Console.WriteLine("How many numbers are you going to enter");

                //capture the number in a variable (after converting it to an integer of course ;)/>/>)
                int noOfValues = int.Parse(Console.ReadLine());

                //ask user to enter their numbers
                Console.WriteLine("Enter your numbers:");

                //a loop used to fill our list collection with the numbers
                //the user enters on number per iteration, and it gets added to the
                //list. We know how many numbers to expect, so we know how many
                //iterations we need, making a for loop an ideal choice
                for (int i = 0; i < noOfValues; i++)
                {
                    //capture the number, and add it to the list
                    numbers.Add(int.Parse(Console.ReadLine()));
                }

                //variable to hold the sum of all the integers in the list
                int sum = 0;

                //the list collection implements IEnumerable<T>, and so
                //we can use a Foreach loop to go through each number in
                //the list, one by one. Rememeber, we cannot add to, or remove from,
                //the collection in a Foreach loop. In this example, we need to
                //go through every number in the list, and add each one to a running
                //total, making Foreach the ideal choice of loop
                foreach (int num in numbers)
                {
                    //add current number to the running total 'sum' variable
                    sum += num;
                }

                //calculate average by dividing 'sum' by the number of elements in the list accessed via the 'Count' property
                //print the value out
                Console.WriteLine("Average: {0}", sum/numbers.Count);

                //ask user if they want to enter another list of numbers
                Console.WriteLine("Do you want to go again - {0} or {1}", "Y", "N");

                //capture whether or not hte user wants to continue in a Boolean variable
                //by determining whether input was "Y" or not
                bool again = Console.ReadLine().ToUpper().Equals("Y");

                //check if 'again' is true
                //notice we don't need to put "again == true"
                //the expression is automatically evaluated to true or false
                if (again)
                {
                    //if the user wants to go again,
                    //skip everything beyond this line, and start a new iteration
                    //when this is executed, the user will see "How many numbers are you going to enter"
                    //printed in the console as a new loop has begun
                    continue;
                }
                else
                {
                    //else, break out of the loop as the user
                    //doesn't want to enter another list.
                    //The user will see "Thank you for using this program"
                    //displayed when this line executes as the is terminated immediately
                    //and execution resumes with the first statement after the loop
                    break;
                }
                

            } while (true); //notice the use of true here. While loops execute until the condition
                            //in the parentheses is false. However, this will never happen here, so 
                            //our loop will loop for ever. It is an infinite loop. This kind of loop
                            //will usually cause your program to become unresponsive. However, as we have provided a
                            //'way out' of the loop by using the 'break' keyword, our program will execute fine and
                            //remain responsive. We didn't strictly need to use an infinity loop here, as we could 
                            //just test this line Console.ReadLine().ToUpper().Equals("Y") in the while's parentheses.
                            //I used an infinity loop so that I could demonstrate the break keyword in action.

                            //The for loop equivalent of an infinite loop is:
                            /* for(;;)/>/>
                               {

                               }
                             */


            //print out thank you message once user has done
            Console.WriteLine("Thank you for using this program");




That example demonstrates another point. You can nest all the control structures within each other. You can have a for loop, of which contains another for loop, of which contains a while loop, for example. When nesting control structures, you have to be careful with variable scope by remembering that variables declared in the contruct definition or construct body are NOT available outside the construct.

The 'sum' variable isn't available outside the while loop in the above example, for example.


In Conclusion

So there you have it! They are the fundamental constructs in the C# language.

Here is a link to the MSDN documentation on statements in general. The three statement types we are concerned with in this tutorial are the ‘selection statements’, the ‘Iteration Statements’ and the ‘Jump Statements’.

MSDN Reference

Further, there are actually two small, sub features that I didn’t mention in the tutorial.

The first thing is that there is actually another type of conditional, decision making construct that uses a ternary operator (an operator that has 3 operands). It is merely a shorthand for an if/else construct, and can be handy in certain circumstances, but it is by no means mandatory that you learn it. Standard if statements can easily suffice, it's just saves a few lines of code ocassionally.

Read about it here:

Ternary Operator

The second thing is the ‘goto’ statement and label identifiers. I deliberately didn’t mention these as it is strongly advised that you do not use them in real code. There is no situation where you need these statements to complete a programming task.

For your reference however, here is the documentation:

Goto Statement


Thank you for viewing this tutorial, and have fun :)/>!


See all the C# Learning Series tutorials here!

This post has been edited by CodingSup3rnatur@l-360: 23 November 2012 - 12:50 AM


Is This A Good Question/Topic? 9
  • +

Replies To: Control Structures (loops, ifs and switch)

#2 cs_gal  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 22-October 10

Posted 23 March 2011 - 02:14 AM

A very nice and helpful tutorial for beginners. Hats off to the writer !
I read the first lesson about the "Hello World" program, I want to know, how can I write that the same program in C#, so that it gives a graphic interface to the user and when the user click a button, he can see "hello world" printed in a nice formatted way in a box. I am sorry, if i am being senseless, I am new and have no idea about the language, but trying to learn it.
Was This Post Helpful? 1
  • +
  • -

#3 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Posted 23 March 2011 - 01:49 PM

Thanks a lot for the feedback!

You want to start a new Windows Forms Application project (where you choose 'Console Application' in Visual Studio, choose 'Windows Forms Application' instead).

Next, you would drag a textbox and a button from the toolbox (if you can't see the toolbox, go into the 'View' menu and click 'Toolbox') onto the form.

Then, double click on the button you have dragged out, and you should be taken to some code that looks like this:

//this is the code that is run when the button is clicked
private void button1_Click(object sender, EventArgs e)
{

}



Then, add this line to that method (in between the { }):

//assign .Text property of the textbox to the string you want to display
this.textBox1.Text = "Hello, World";



Then, just run the application :)
Was This Post Helpful? 0
  • +
  • -

#4 Macjohn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 407
  • Joined: 10-April 09

Posted 23 March 2011 - 04:46 PM

View Postcs_gal, on 23 March 2011 - 09:14 AM, said:

A very nice and helpful tutorial for beginners. Hats off to the writer !
I read the first lesson about the "Hello World" program, I want to know, how can I write that the same program in C#, so that it gives a graphic interface to the user and when the user click a button, he can see "hello world" printed in a nice formatted way in a box. I am sorry, if i am being senseless, I am new and have no idea about the language, but trying to learn it.

we have no problem giving you a hand, if you have donne your homework first :P
Just post for some help and some tell us what you allready tried or what you don't understand.
Was This Post Helpful? 0
  • +
  • -

#5 G-RaY  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 02-March 11

Posted 24 March 2011 - 09:03 AM

Thanks for the tutorial. I have a rather noobish question though. When you say control structures or (constructs) at the beginning. They are not the same as constructors? Right? Because constructors are what you use to build your class (i.e. methods()). And the control structures are just the parameters for how many times your class does something, and how to do it at teach stage of its loop, etc.? Sorry about this, but I just want to ensure that I am thinking about this the right way.
Was This Post Helpful? 0
  • +
  • -

#6 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4479
  • View blog
  • Posts: 7,800
  • Joined: 08-June 10

Posted 24 March 2011 - 12:33 PM

A control structure is just a name for a tool that allows you to control the flow of your program. Loops repeat, if/else if/else allows decisions, and switch allows for multiple choice.

You're correct about what a constructor is. Hopefully we'll have our tutorial on Classes up soon, and we can explain in depth what this means, but a constructor is a special method with no return type (not even void) that is called when you create a new instance of that class using the new keyword.
Was This Post Helpful? 1
  • +
  • -

#7 G-RaY  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 02-March 11

Posted 24 March 2011 - 05:44 PM

That's what I thought. I just still have a hard time explaining the stuff. Which is why this site is awesome, cuz I can actually see if I'm getting it or not.

I graduate from a 2 year programming degree in a couple months, but there was no emphasis on OOP just VB and C# syntax. So that is what I am really trying to get down right now. I finally found 2 good books after 4 or 5 that didn't do much. So hopefully they help.

Thanks for your explanation. And Thanks to everyone else that is making these tutorials.
Was This Post Helpful? 0
  • +
  • -

#8 Naelex  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 01-March 10

Posted 18 April 2011 - 06:17 AM

Thanks for another great tutorial, very clear and helped me recap on the C# i learned over a year ago, when i never fully understood how to use all the control structures available in c#.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1