How to print a diamond pattern outline with C# - c#

Here's the code of a solid diamond and I want to remove the middle and leave the edges.
From this,
to this,
public void DiamondOne()
{
int i, j, count = 1, number;
Console.Write("Enter number of rows:");
number = int.Parse(Console.ReadLine());
count = number - 1;
for (j = 1; j <= number; j++)
{
for (i = 1; i <= count; i++)
Console.Write(" ");
count--;
for (i = 1; i <= 2 * j - 1; i++)
Console.Write("*");
Console.WriteLine();
}
count = 1;
for (j = 1; j <= number - 1; j++)
{
for (i = 1; i <= count; i++)
Console.Write(" ");
count++;
for (i = 1; i <= 2 * (number - j) - 1; i++)
Console.Write("*");
Console.WriteLine();
}
Console.ReadLine();
}

I would go with something like this:
public void Diamond()
{
Console.WriteLine("Enter number of rows:");
bool isNumber = int.TryParse(Console.ReadLine(), out int rowsNr);
if (!isNumber)
{
Console.WriteLine("Not a number!");
return;
}
// print the upper half
for (int rowIndex = 0; rowIndex < rowsNr - 1; rowIndex++)
{
for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)
{
if (colIndex == Math.Abs(rowsNr - rowIndex) || colIndex == Math.Abs(rowsNr + rowIndex))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
// print the lower half
for (int rowIndex = 1; rowIndex <= rowsNr; rowIndex++)
{
for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)
{
if (colIndex == rowIndex || colIndex == 2 * rowsNr - rowIndex)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
}
Basically you are looking for the x and y coordinates. Each of the 4 edges has its own equation (the upper-left one is x == y for instance) and you check for these while you iterate. I split the code in two parts, one for the upper half and one for the lower half. It's more readable and you don't put together too many if statements and lose the meaning of the code.

This is what I came up with:
// Get the number of rows
int rows;
do
{
Console.WriteLine("Enter number of rows:");
} while (!int.TryParse(Console.ReadLine(), out rows));
// Print diamond
DiamondOne(rows, Console.Out);
// Wait for key press
Console.WriteLine("Press any key to exit");
Console.ReadKey(true);
static void DiamondOne(int rows, TextWriter output)
{
for (int currentRow = 0; currentRow < rows; currentRow++)
{
OutputRow(rows, output, currentRow);
}
for (int currentRow = rows - 2; currentRow >= 0; currentRow--)
{
OutputRow(rows, output, currentRow);
}
}
static void OutputRow(int rows, TextWriter output, int currentRow)
{
int indentation = rows - currentRow - 1;
int diamondCentre = Math.Max((currentRow * 2) - 1, 0);
output.Write(new string(' ', indentation));
output.Write('*');
output.Write(new string(' ', diamondCentre));
if (currentRow != 0) output.Write('*');
output.WriteLine();
}

Related

Columns and rows in a 2D array?

{
int woodchuckSim = 0;
int numOfDays = 0;
bool validNumber = false;
bool validDays = false;
Random ran1 = new Random();
//display banner
//Ask user how many woodchucks to simulate
while(!validNumber)
{
Write("How many woodchucks would you like to simulate? (1 - 100) ");
int.TryParse(ReadLine(), out woodchuckSim);
if((woodchuckSim <= 0) || (woodchuckSim > 100))
{
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
}
else
{
validNumber = true;
}
}
//Ask user how many days to simulate
while(!validDays)
{
Write("\nHow many days would you like to simulate? (1 - 10) ");
int.TryParse(ReadLine(), out numOfDays);
if((numOfDays <= 0) || (numOfDays > 10))
{
WriteLine("Please enter a positive whole number between 1 and 10: ");
}
else
{
validDays = true;
}
}
//Using random class populate each cell between 1 and 50 that represents # of pieces of wood chucked by specific woodchuck on that specific day
int[,] sim = new int[woodchuckSim, numOfDays];
WriteLine($"{woodchuckSim} {numOfDays}");
for (int i = 0; i < sim.GetLength(0); i++)
{
for (int j = 0; j < sim.GetLength(1); j++)
{
sim[i, j] = ran1.Next(1, 50);
Write(sim[i, j] + "\t");
}
{
WriteLine(i.ToString());
}
}
WriteLine("Press any key to continue...");
ReadLine();
}
This is my code so far in my woodchuck simulation coding assignment but I need a columns and rows label on the side and top like the picture. I really don't have any idea how to do this, and I'm not sure if I'm missing a code or typed something wrong. Also at the end of the code it prints out the number of woodchucks simulated in a straight line like if the user typed in 15 it would print 0-14 in a straight line at the end which is not something I want, any help will be appreciated, thanks! (The second picture is what my code is printing)
There are a few steps to do this, but it's not too hard:
Write the column headers (include blank space at the beginning where the row headers go
Write the column underlines
For each row, write the row header first
Then for each column in the row, write the column data
After the column data is written, write a newline to start the next row
Here's a sample that produces a table similar to your output. Note that we use PadLeft to pad each column data with spaces so they're all the same width. I've also included Sum and Avg columns based on your comment below. Additionally, to clean up the main code, I added methods to write text in a different color and a method to get an integer from the user:
private static readonly Random Random = new Random();
private static void WriteColor(string text,
ConsoleColor foreColor = ConsoleColor.Gray,
ConsoleColor backColor = ConsoleColor.Black)
{
Console.ForegroundColor = foreColor;
Console.BackgroundColor = backColor;
Console.Write(text);
Console.ResetColor();
}
private static void WriteLineColor(string text,
ConsoleColor foreColor = ConsoleColor.Gray,
ConsoleColor backColor = ConsoleColor.Black)
{
WriteColor(text + Environment.NewLine, foreColor, backColor);
}
public static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
var isValid = true;
int result;
do
{
if (!isValid)
{
WriteLineColor("Invalid input, please try again.", ConsoleColor.Red);
}
else isValid = false;
Console.Write(prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
(validator != null && !validator.Invoke(result)));
return result;
}
public static void Main()
{
int columnWidth = 6;
ConsoleColor sumForeColor = ConsoleColor.DarkRed;
ConsoleColor sumBackColor = ConsoleColor.Gray;
ConsoleColor avgForeColor = ConsoleColor.White;
ConsoleColor avgBackColor = ConsoleColor.DarkGreen;
int numWoodchucks = GetIntFromUser(
"How many woodchucks would you like to simulate? (1 - 100) ... ",
x => x >= 1 && x <= 100);
int numDays = GetIntFromUser(
"How many days would you like to simulate? (1 - 10) .......... ",
x => x >= 1 && x <= 10);
int[,] data = new int[numWoodchucks, numDays];
// Write column headers, starting with a blank row header
Console.WriteLine();
Console.Write(new string(' ', columnWidth));
for (int col = 1; col <= data.GetLength(1); col++)
{
Console.Write($"{col}".PadLeft(columnWidth));
}
Console.Write(" ");
WriteColor("Sum".PadLeft(columnWidth - 1), sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor("Avg".PadLeft(columnWidth - 1), avgForeColor, avgBackColor);
// Write column header underlines
Console.Write(new string(' ', columnWidth));
for (int col = 0; col < data.GetLength(1); col++)
{
Console.Write(" _____");
}
Console.Write(" ");
WriteColor("_____", sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor("_____", avgForeColor, avgBackColor);
int total = 0;
for (int row = 0; row < data.GetLength(0); row++)
{
// Write row header
Console.Write($"{row + 1} |".PadLeft(columnWidth));
int rowSum = 0;
// Store and write row data
for (int col = 0; col < data.GetLength(1); col++)
{
data[row, col] = Random.Next(1, 50);
Console.Write($"{data[row, col]}".PadLeft(columnWidth));
rowSum += data[row, col];
}
// Write sum and average
Console.Write(" ");
WriteColor($"{rowSum}".PadLeft(columnWidth - 1),
sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor($"{Math.Round((double) rowSum / data.GetLength(1), 1):F1}"
.PadLeft(columnWidth - 1), avgForeColor, avgBackColor);
total += rowSum;
}
// Write the sum of all the items
Console.Write(new string(' ', columnWidth + columnWidth * data.GetLength(1) + 1));
WriteColor("_____", sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor("_____", avgForeColor, avgBackColor);
// Write the average of all the items
Console.Write(new string(' ', columnWidth + columnWidth * data.GetLength(1) + 1));
WriteColor($"{total}".PadLeft(columnWidth - 1), sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor(
$"{Math.Round((double) total / (data.GetLength(0) * data.GetLength(1)), 1):F1}"
.PadLeft(columnWidth - 1), avgForeColor, avgBackColor);
Console.Write("\nPress any key to continue...");
Console.ReadKey();
}
Output
Not tested, but something like this:
Write("\t");
for (int i = 0; i < sim.GetLength(0); i++)
{
Write(i.ToString() + "\t");
}
WriteLine("\t");
for (int i = 0; i < sim.GetLength(0); i++)
{
Write("_____\t");
}
WriteLine();
for (int i = 0; i < sim.GetLength(0); i++)
{
{
WriteLine(i.ToString().PadLeft(3) + " |\t");
}
for (int j = 0; j < sim.GetLength(1); j++)
{
sim[i, j] = ran1.Next(1, 50);
Write(sim[i, j] + "\t");
}
}
Like I said, not tested, just typed right into the editor here, but that should get you close. Also, look at the string.PadLeft(int) function to get your numbers to be right-justified like the example.

pyramid pattern in while loop c#

I have to create a program to print pyramid pattern (1 2 33 44 555 666...) and sum the numbers.
Here is my solution:
static void Main(string[] args)
{
int i, j;
i = 1;
int sum = 0;
while (i < 9)
{
for (j = 1; j <= i; j+=2)
{
Console.Write(i);
}
Console.Write("\n");
sum += i;
i++;
}
Console.WriteLine("Summary: " + sum);
Console.ReadLine();
}
And my output:
What am I doing wrong here (wrong summary)?
Here is an optimized and working version of your code:
int sum = 0;
for (int i = 1; i < 9; i++)
{
int current = 0;
for (int j = 1; j <= i; j += 2)
{
Console.Write(i);
current = 10 * current + i;
}
Console.WriteLine();
sum += current;
}
Console.WriteLine("Summary: " + sum);
The main issue is that you were only capturing the value of i (integer being printed) and using that to calculate the summary. As seen here, the current value is captured (for the entire line) within the nested loop and then added to the summary to give you the result you expect.
HTH
Only made small adjustments to your code.
static void Main(string[] args)
{
int i, j;
i = 1;
int sum = 0;
while (i <= 9)
{
for (j = 0; j <= i - 1; j++)
{
Console.Write(i);
sum += i * (int)Math.Pow(10, j);
}
Console.WriteLine();
i++;
}
Console.WriteLine("Sum: " + sum);
Console.ReadLine();
}
If you like to extend your code to let the user pick a number you can do this:
Instead of this line:
while (i <= 9)
You can do this:
Console.WriteLine("Please enter a number between 1 and 9:");
int maxValue = 1;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out maxValue) || maxValue < 1 || maxValue > 9)
{
Console.WriteLine("Wrong input! Try again:");
continue;
}
break;
}
while (i <= maxValue)
Please find not optimized but quick solution
int i, j;
i = 1;
int sum = 0;
while (i < 9)
{
int current = 0;
for (j = 1; j <= i; j += 2)
{
current = 10 * current + i;
Console.Write(i);
}
Console.Write("\n");
sum += current;
i++;
}
Console.WriteLine("Summary: " + sum);
Console.ReadLine();

How to print a triangle of Binary numbers in c#

I need to add binary number logic into this snippet. I just cannot wrap my head around how to implement binary numbers, I could just add 0s and 1s but that does not seem to be right
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
}
you can use modulo (%)
c = star % 2; // will print first the '1'
c = (star + 1) % 2; // will print first the '0'
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
int c = 0;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
c = star % 2; //this will return 1 if the value of star is odd then 0 if even
Console.Write(c);
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
VIEW DEMO

C# Multiplication Table

So I'm attempting to print a multiplication table in C# however I can't quite figure out how to get what I need.
So far my program outputs the following:
1 2 3
2 4 6
3 6 9
However, I need it to output this:
0 1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
I've tried a lot of different ways to get the second output however I can't quite figure it out. I'm not necessarily asking for an answer but if someone could point me in the right direction it would be much appreciated.
This is the code I have as of now:
static void Main(string[] args)
{
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write(i * j + "\t");
}
Console.Write("\n");
}
Console.ReadLine();
}
for (int i = 0; i <= 3; i++)
{
Console.Write(i + "\t");
for (int j = 1; j <= 3; j++)
{
if (i>0) Console.Write(i * j + "\t");
else Console.Write(j + "\t");
}
Console.Write("\n");
}
int tbl= int.Parse(Console.ReadLine());
int j = int.Parse(Console.ReadLine());
for (int i=1; i<=10; i++)
{
for (int j=1;j<=10; j++)
{
Console.WriteLine("{0}*{1}={2}", i, j, (i * j));`enter code here`
}
}
Console.ReadLine();
You should skip both 0's.
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
Console.Write((i == 0? j : (j == 0? i : i*j)) + "\t");
}
Console.Write("\n");
}
You could try one of this three solutions.
Solution 1 (without if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
Console.Write("{0}\t", i);
for (int j = 1; j <= 3; j++)
{
Console.Write("{0}\t", i * j);
}
Console.WriteLine();
}
Console.ReadLine();
}
Solution 2 (With if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (i == 0)
{
Console.Write("{0}\t", i);
}
else
{
Console.Write("{0}\t", i * j);
}
}
Console.WriteLine();
}
Console.ReadLine();
}
Solution 3 (With short-hand if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write("{0}\t", (i == 0) ? i : i * j);
}
Console.WriteLine();
}
Console.ReadLine();
}
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
if (i == 0)
{
Console.Write(j);
}
else
{
if(j == 0)
{
Console.Write(i);
}
else
{
Console.Write(i * j);
}
}
}
Console.Write("\n");
}
Console.WriteLine("Enter A Number");
int j = Convert.ToInt32(Console.ReadLine());
for (int i = 0 ; i <= 10; i++) {
Console.WriteLine("{1} X {0} = {2}",i,j,i*j);
Console.ReadLine();
}
public class Program
{
//int num;
public static void Main(string[] args)
{
int num,num1;
Console.WriteLine("enter a any number num");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter any second number num1");
num1 = Convert.ToInt32(Console.ReadLine());
for(int i = num;i <= num1; i++)
{
for (int j = 1; j <= 10; j++)
{
Console.Write(i *j+ "\t");
}
}
Console.Write("\n");
}
}
using System;
/*
* Write a console-based application that displays a multiplication table of the product of
* every integer from 1 through 10 multiplied by every integer from 1 through 10. Save the
* file as DisplayMultiplicationTable.cs.
*/
namespace MultiplicationTable
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\t\t\t\t\t\t\t\t\tMultiplication Table");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------");
const int END = 11;
for(int x = 1; x < END; x++)
{
for(int y = 1; y < END; y++)
{
int value = x * y;
Console.Write("{0} * {1} = {2}\t", y, x, value);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Output
Output of Code
I am attempting to complete the above code in a GUI. So far I have come up with the following code; but the output is not like the above output.
My Code for the GUI is as follows:
using System;
using System.Windows.Forms;
namespace DisplayMultiplicationTableGUI
{
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}
private void ShowTableButton_Click(object sender, EventArgs e)
{
int a;
int b;
const int STOP = 11;
for(a = 1; a < STOP; a++)
{
for(b = 1; b < STOP; b++)
{
int value = a * b;
multiplicationTableLabel.Text += String.Format("{0} * {1} = {2} ", b, a, value);
}
multiplicationTableLabel.Text += "\n";
}
}
}
}

create asterisk tree with C#

Hello everyone
I try to solve asterisk tree problem
and found my code is not work correctly and can be improved.
This is output that expected
input : 5
*
* * *
* * * * *
* * *
*
input : 4
* * * *
* *
* * * *
and this is my code
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
{
for (int i = 1; i <= couter; i++)
{
for (int j = 3; j > i; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" *");
}
Console.WriteLine();
}
for (int i = couter - 1; i >= 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (j <= couter - i)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
}
else
{
for (int i = couter; i > 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (couter - i >= j)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
for (int i = couter - 1; i <= couter; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
}
Please could you help me to solve this problem.
Lately, I think I'm poor at algorithms and a little complex problem. Is anybody know useful link or how I can improve this skill, please let me know.
Thanks,
Check this page for input 5 (diamond) : http://www.dreamincode.net/forums/topic/126715-diamond-asterisk/
I've translated it to C# - now it displays diamonds with size that you set in variable 'rows':
int rows = 5;
StringBuilder sb = new StringBuilder();
// top part
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= rows - i; j++)
sb.Append(' ');
for (int k = 1; k <= 2 * i - 1; k++)
sb.Append('*');
sb.AppendLine();
}
//bottom part
for (int n = rows - 1; n > 0; n--)
{
for (int l = 1; l <= rows - n; l++)
sb.Append(' ');
for (int m = 1; m <= 2 * n - 1; m++)
sb.Append('*');
sb.AppendLine();
}
Console.Write(sb.ToString());
I was initially reluctant to post it because it definitely smells like homework...
Anyway, here's a piece of working code:
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
PrintDiamond(couter);
else
PrintHourGlass(couter);
}
Console.ReadLine();
}
private static void PrintDiamond(int couter)
{
bool moreAsterisks = true;
for (int row = 0; row < couter; row++)
{
int nAsterisks = moreAsterisks ? (2 * row) + 1 : 2 * (couter - row - 1) + 1;
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 1) / 2)
moreAsterisks = false;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
private static void PrintHourGlass(int couter)
{
bool moreAsterisks = false;
for (int row = 0; row < couter - 1; row++)
{
int nAsterisks = moreAsterisks ? couter - 2 * (couter - row - 2) : couter - (2 * row);
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 2) / 2)
moreAsterisks = true;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
P.S.:
it works with any number, not just 4-5...
Here's a minified LINQ solution for your problem:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
}
}
}
It's pretty simple; inside the loop, first line calculates length of the i-th diamond row if input is even, second one corrects the calculation for odd input. The remaining two lines print i-th row using some LINQ tricks. If you don't like showing off with LINQ, you can replace thoose lines with regular for loops (which is probably going to be faster). Then the code would look like:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
//Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
//Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
for (int c = 0; c < n - l; c++) Console.Write(" ");
for (int c = 0; c < l; c++) Console.Write("* ");
Console.WriteLine();
}
}
}

Categories

Resources