C Sharp/Loops

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators
C# - Flow Control

C# - Variables II
C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

[edit] C# Simple Loops


We will discuss loops in this section and looping techniques



looping is very necessary because it relieves the programmer from time consuming tasks. Developers are able to execute statements repeatedly millions of times if they need to. Tedious calculations can also benefit from loops as well. Lets see how loops can make our job easier.


Lets print the numbers from 1 to 10

Example 1:

using System;
 
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(1);
        Console.WriteLine(2);
        Console.WriteLine(3);
        Console.WriteLine(4);
        Console.WriteLine(5);
        Console.WriteLine(6);
        Console.WriteLine(7);
        Console.WriteLine(8);
        Console.WriteLine(9);
        Console.WriteLine(10);
 
        Console.Read();
    }
}

Output

1
2
3
4
5
6
7
8
9

10

A grueling way to print from 1 to 10. Lets examine a more efficient way to do basic counting using goto.


Example 2

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int x = 0;
 
    LoopLabel:
        x += 1;     //Equivalent to x = x + 1
        Console.WriteLine(x);
 
        if (x < 10) //if x is less than 10 then goto LoopLabel
            goto LoopLabel;
 
        Console.Read();
    }
}

Output:

1
2
3
4
5
6
7
8
9

10


This is a much more efficient way to count from 1 to 10 or even a thousand or 1 million