Kinjal Maru Shah Kinjal Maru Shah - 16 days ago 8
C# Question

Table in C# with conditional cell values

I need help to generate the following table in .txt file using C#

enter image description here

For each cell in the table, a random number will be generated between 0 and 100 (inclusive). If the number is between 5 and 95, the cell will have a " * ", else it will be a blank cell.

Thank you in anticipation.

Answer
char[] table = new char[9];
for(int i =0;i<table.Length;i++)
{
  int nbr =new Random().Next(0,100);//you can add the seed inside random constructor
  if( nbr<5 || nbr >95)
   table[i] = '*';
  else
   table[i] = ' ';
}

For the text file use this method

add using System.IO; so you use the StreamWriter

void WriteToTxt(string[] table,string fileName)
{
 StreamWriter writer = new StreamWriter(fileName);
 int column=1;
 writer.WriteLine(" _________");
 for(int i =0;i<table.Length;i++)
 {
   writer.WriteLine("|"+table[i]+" |");
   column++;
   if(column == 3)
   {
    column =1;
    writer.WriteLine("|__|__|__|");
   }
 }
 writer.Close();
}

play with the spaces to make the size you want hope it helps if so please mark this as the answer :) have a nice day !