C# Loop Programming Examples

In this chapter you will learn:
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.
Answer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Loop_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
 
Answer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Loop_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
__

Summary

In this chapter you learned how to implement loop constructs in C# programming. In next chapter, you will get some programming exercises. You must do all the exercises in order to improve your programming skills in loop constructs.

 

Share your thought