I’m Learning C# – Part 8

Today we will learn how to reverse a string.

Method 1: read from console into a string, assign it into a character array, use the reverse property of arrays and then write it to console.

string straight = Console.ReadLine();
char[] charnew = straight.ToCharArray();
Array.Reverse(charnew);
Console.Write(charnew);
Console.ReadLine();

Method 2: Assigning the reversed data read from the console and assigning it to the char array.

char[] charnew = Console.ReadLine().Reverse().ToArray();
Console.Write(charnew);
Console.ReadLine();

Converting to upper case along with reversal

char[] charnew = Console.ReadLine().ToUpper().Reverse().ToArray();
Console.Write(charnew);
Console.ReadLine();

Next let us learn to generate a random number. So this is a simple code which takes in any name and prints a random number between 1 and 50 as the age of the person.

class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Enter the name”);
string name = Console.ReadLine();
Console.WriteLine(“the age of {0} is {1}”, name,age(name));
Console.ReadLine();
}
static int age(string name)
{
Random randomAge = new Random(); // Random is the class and we are creating an object randomAge here
int rand = randomAge.Next(1, 50); // Next is a method defined in the class Random
return rand;
}
}

Now if we want a do-while loop for the above logic, lets try something like this

class Program
{
static void Main(string[] args)
{
bool x = true;
do
{
Console.WriteLine(“Enter the name”);
string name = Console.ReadLine();
Console.WriteLine(“the age of {0} is {1}”, name, age(name));
Console.WriteLine(“do you want to continue? 1 for yes; 0 for no”);
string response = Console.ReadLine();
if (int.Parse(response) == 1)
{
x = true;
Console.WriteLine(“continuing the loop”);
}
else
{
x = false;
Console.WriteLine(“exiting the loop”);
}

} while (x);
Console.ReadLine();
}
static int age(string name)
{
Random randomAge = new Random();
int rand = randomAge.Next(1, 50);
return rand;
}
}

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