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:
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:
Output
1
22
333
4444
55555
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();
}
}
}
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();
}
}
}
{
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
Post a Comment