I’m Learning C# – Part 9

The best way to learn or I must say use a blend of loops is by creating patterns. Here I made a diamond of “*”. Try for yourself

class Programcapture
{
static void Main(string[] args)
{

StringBuilder newstring = new StringBuilder();
for (int i = 0; i <= 10; i++)
{
int k = i;
while(k<10)
{
newstring = newstring.Append(” “);
k++;
}

for (int j = 0; j <= 2*i; j++)
{
newstring = newstring.Append(“*”);
}
newstring = newstring.Append(“\n”);

}
for (int i = 9; i >= 0; i–)
{
int k = i;
while (k < 10)
{
newstring = newstring.Append(” “);
k++;
}

for (int j = 0; j <= 2 * i; j++)
{
newstring = newstring.Append(“*”);
}
newstring = newstring.Append(“\n”);

}
Console.WriteLine(newstring);
Console.ReadLine();
}
}

Changing the numbers here and there and playing with the loops will get you many more patterns 🙂

Things which are new here is StringBuilder. It’s a class included in System.Text and it is sealed class which means you cannot inherit it. Now we have created an object of the type StringBuilder called ‘newstring’ to do our appending. Now this method will be effective when we have lot of appending to be done to reduce the strain on memory.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s