Wednesday, August 17, 2011

Arrays in c#


There are two types of arrays :

1)One Dimensional Array
2)Multi or Double Dimensional arrays

Programs for 1d array

1)Simple array program

class abc
{
static void Main()
{
string[] names=new string[5];
for(int i=0;i<5;i++)
{
System.Console.WriteLine("Enter name of People");
names[i]=System.Console.ReadLine();
}
for(int i=0;i<5;i++)
{
System.Console.WriteLine(names[i]);
}
}}


2)Reverse an array

class abc
{
static void Main()
{
int[] a={45,66,43,12,85};
for(int i=0;i {
System.Console.WriteLine(a[i]);
}
System.Array.Reverse(a);
System.Console.WriteLine("reverse is");

for(int i=0;i {
System.Console.WriteLine(a[i]);
}
}
}

Two dimensional arrays

1)Program for Populationa and sector

using System;
class abc
{
static void Main()
{
int[ , ] population = new int [5,2];
for(int i=0;i<5;i++)
{
Console.Write("Enter secttor no. ");
population[i,0]=Convert.ToInt32(Console.ReadLine());

Console.Write("Enter Population ");
population[i,1]=Convert.ToInt32(Console.ReadLine());
}
for(int i=0;i<5;i++)
{
Console.WriteLine("{0} population is {1}",population[i,0],population[i,1]);
}
}
}

2)Transpose of a matrix

class abc
{
static void Main()
{
int[ , ] matrix = new int[4,4];


int[ , ] matrix2 = new int[4,4];

for(int j=0;j<=3;j++)
{
for(int i=0;i<=3;i++)
{
System.Console.Write("Enter Element {0},{1} : ",j,i);
matrix[j,i]=System.Convert.ToInt32(System.Console.ReadLine());
}
}

for(int j=0;j<=3;j++)
{

for(int i=0;i<=3;i++)
{
System.Console.Write(matrix[j,i]);
}
System.Console.WriteLine("");
}

System.Console.WriteLine("its transpose is");

for(int j=0;j<=3;j++)
{
for(int i=0;i<=3;i++)
{
matrix2[i,j]=matrix[j,i];
}
}
for(int j=0;j<=3;j++)
{
for(int i=0;i<=3;i++)
{
matrix[i,j]=matrix2[i,j];
}
}

for(int j=0;j<=3;j++)
{

for(int i=0;i<=3;i++)
{
System.Console.Write(matrix[j,i]);
}
System.Console.WriteLine("");
}
}
}

No comments:

Post a Comment