Print a pattern in C#

Given a number n, print following pattern without using any loop.

Input:
BaseNumber = 16
DifferenceNumber = 5
Output: 16, 11, 6, 1, -4, 1, 6, 11, 16

Input:
BaseNumber = 10
DifferenceNumber = 5
Output: 10, 5, 0, 5, 10

Explanation: We’ll subtract DIfferenceNumber from Base Number till it become 0 or negative then we again add differenceNumber to it till be become our original BaseNumber.

static void Main(string[] args)
{
int baseNumber, differenceNumber;
Console.WriteLine(“Please enter a base number.”);
baseNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“Please enter a difference number.”);
differenceNumber = Convert.ToInt32(Console.ReadLine());
Printpattern(baseNumber, differenceNumber);
Console.ReadKey();
}

static void Printpattern(int baseNumber, int differenceNumber)
{
if (baseNumber <= 0)
{
Console.Write($”{baseNumber}, “);
return;
}
Console.Write($”{baseNumber}, “);
Printpattern(baseNumber – differenceNumber, differenceNumber);
Console.Write($”{baseNumber}, “);
}

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