Skip to main content

C# Loop Examples

In this chapter you will learn how to implement loop constructs in C# programming. There are some programming examples are given below that will help you to understand loop constructs in C#.

Qu 1: Write a program to display table of given number.

Example:


using System;

namespace Examples1
{
  class Program
   {
     static void Main(string[] args)
      {
        int num, i,result;
        Console.Write("Enter a number\t");
        num = Convert.ToInt32(Console.ReadLine());

        for (i = 1; i <= 10; i++)
         {
           result = num * i;
           Console.WriteLine("{0} x {1} = {2}", num, i,                result);
         }
        Console.ReadLine();
      }
   }
}



Output


Enter a number     8
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80



Qu2: Write a program to print following output using for loop.

1
22
333
4444
55555

Example:

using System;
namespace Example2
{
  class Program
   {
     static void Main(string[] args)
      {
        int i,j;
        i=0;
        j=0;

        for (i = 1; i <= 5; i++)
         {
           for (j = 1; j <= i; j++)
            {
              Console.Write(i);
            }
           Console.Write("\n");
         }
        Console.ReadLine();
      }
   }
}




Output

1
22
333
4444
55555





Comments

Popular posts from this blog

C# Array

Array is a collection of variable of same data type. If you have declare 1000 integer variable, then you can declare an integer type array of 1000 size. The value of array can be accessed using index position of array. The first index position of array is zero. In C#, there two types of array: Single Dimensional Array and Multi Dimensional Array. You can use both type of array easily and can access its element using loop constructs or index position.

Structure (C#)

Structure is the value type data type that can contain variables, methods, properties, events and so on. It simplifies the program and enhance performance of code in C# programming. The structure encapsulate small group of related variables inside a single user-defined data type. It improves speed and memory usage and also enhances performance and clarity of your code. How to use structure in C#? It is very simple to use structure in C#. The following programming example will show you to how to create and use structure in C# programming. Programming Example of Structure (C#) using System; namespace Structure {    class Program    {      // creating three different variable in single structure       struct book        {          public string bookname;          public int price;          public stri...