How to rescue this task? - c#

I wonder how to do or write a code that it will print out no one got 20 points and it has to write a number of line. Everything works except if (is20 == false). How to fix it?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double[,] points = new double[50, 5];
Random r = new Random();
for (int k = 0; k < 50; k++)
{
for (int j = 0; j < 5; j++)
{
points[k, j] = r.NextDouble() * 5 + 15.5;
if (points[k, j] > 20) points[k, j] = 20;
Console.Write("{0:f1}", points[k, j]);
Console.Write(" ");
}
Console.WriteLine();
}
bestEstimated(points);
Console.ReadLine();
}
public static void bestEstimated(double[,] points)
{
bool is20 = false;
for (int line = 0; line < 50; line++)
{
for (int column = 0; column < 5; column++)
{
if (points[line, column] == 20)
{
Console.WriteLine("20 points got: " + line + " competitor");
is20 = true;
break;
}
}
}
if (is20 == false)
{
Console.WriteLine("No one got 20 points: ");
}
}
}
}

You can set is20=false in inner loop in else part and check it inside outer loop after inner loop.
public static void bestEstimated(double[,] points)
{
bool is20 = false;
for (int line = 0; line < 10; line++)
{
for (int column = 0; column < 5; column++)
{
if (points[line, column] == 20)
{
Console.WriteLine("20 points got: " + line + " competitor");
is20 = true;
break;
}
else
{
is20=false;
}
}
if (!is20)
{
Console.WriteLine("20 points not got: " + line + " competitor");
}
}
if(is20 == false)
{
Console.WriteLine("No one got 20 points: ");
}
}

Just a wild guess from your comments below your question:
public static void bestEstimated(double[,] points)
{
var not20Points = new List<int>();
for (int line = 0; line < 50; line++)
{
bool is20 = false;
for (int column = 0; column < 5; column++)
{
if (points[line, column] == 20)
{
Console.WriteLine("20 points got: " + line + " competitor");
is20 = true;
break;
}
}
if (is20 == false)
{
Console.WriteLine("competitor" + line + " didnt get 20 points"); //also can print it here if ya want...
not20Points.Add(line);
}
}
if (not20Points.Count == 50)
{
Console.WriteLine("No one got 20 points");
}
else
{
Console.WriteLine("Those lines did get 20 points: " + string.Join(",", Enumerable.Range(0, 50).Except(not20Points)));
Console.WriteLine("Those lines didnt get 20 points: " + string.Join(",", not20Points));
}
}
(Updated my version, to only print stuff if atleast one column has 20 points)

Related

Trouble creating algorithm that modifies elements of a 2d array

I am having trouble editing the values of a 2d char array.
char[,] chrRaster = new char[4, 5];
After adding values to the array and printing it to the console, I get:
// Input example:
*****
**.**
*****
****.
I am trying to make an algorithm that replaces every '*' that is beside, under or above a '.' by a '.' and then printing this to the console.
// Output after algorithm example:
**.**
*...*
**.*.
***..
I have tried converting the 2d char array to a 2d string array and then using IndexOf('*') to replace every '*' that is beside, under or above a '.', and I also tried calculating this using a number of if and for loops without any luck.
static void Main(string[] args)
{
// Variablen
int intTestgeval = 0; // Number of times you want program to repeat
int intN = 0; // Number of rows
int intM = 0; // Number of coloms
char chrGrond; // Used to store '*' or '.'
char[,] chrRaster; // 2d char array used to store all values
// Code
try
{
intTestgeval = Int32.Parse(Console.ReadLine()); // Number of times program will repeat
if(intTestgeval > 150) // Program can not repeat more then 150 times
{
throw new Exception();
}
}
catch (Exception)
{
Environment.Exit(0);
}
intN = Controle(intN); // Number of rows ophalen
intM = Controle(intM); // Number of Coloms ophalen
chrRaster = new char[intN, intM]; // Initializing array with user input
for (int intR = 0; intR < intTestgeval; intR++) // Print 2d array to console
{
for(int intY = 0; intY < intN; intY++)
{
for(int intZ = 0; intZ < intM; intZ++)
{
chrGrond = Convert.ToChar(Console.ReadKey().KeyChar);
chrRaster[intY, intZ] = chrGrond;
}
Console.WriteLine();
}
instorten[intR] = Instorten(chrRaster, intN, intM); // Ignore this part, that's another part of my assignment not related to my question.
}
}
static int Controle( int intX )
{
try
{
intX = Int32.Parse(Console.ReadLine());
if (intX > 150 || intX < 1) // Length of row and colom can not exceed 20 and can not go lower then 1
{
throw new Exception();
}
return intX;
}
catch // Program will off if value does not meet requirements
{
Environment.Exit(0);
return intX;
}
}
// It is this part of the program I need help with. This is what I tried but can't get any further
static int Instorten(char[,] chrRaster, int intN, int intM)
{
for (int intY = 0; intY < intN; intY++)
{
for (int intZ = 0; intZ < intM; intZ++)
{
if(chrRaster[intY, intZ] == '.' && chrRaster[intY, intZ + 1] == '*' || chrRaster[intY, intZ] == '*' && chrRaster[intY, intZ + 1] == '.')
{
}
}
Console.WriteLine();
}
int intm = 0;
return intm;
}
}
One way to do this would be to make a copy of the array and then iterate over it, examining each item. If the item is a '.', then update the neighbors of this item in the original array.
To determine the neighbors, we simply add one to the row to get the neighbor below, subtract one from the row to get the neighbor above, and similarly we can get the right and left neighbors by adding/subtracting from the column value. Of course we need to ensure that we're inside the bounds of the array before doing anything.
We could write a method with this logic that might look like:
private static void ExposeDotNeighbors(char[,] input)
{
if (input == null) return;
// Make a copy of the input array that we can iterate over
// so that we don't analyze items that we've already changed
var copy = (char[,]) input.Clone();
for (var row = 0; row <= copy.GetUpperBound(0); row++)
{
for (var col = 0; col <= copy.GetUpperBound(1); col++)
{
if (copy[row, col] == '.')
{
// Update neighbors in original array
// Above = [row - 1, col], Below = [row + 1, col],
// Left = [row, col - 1], Right = [row, col + 1]
// Before updating, make sure we're inside the array bounds
if (row > 0) input[row - 1, col] = '.';
if (row < input.GetUpperBound(0)) input[row + 1, col] = '.';
if (col > 0) input[row, col - 1] = '.';
if (col < input.GetUpperBound(1)) input[row, col + 1] = '.';
}
}
}
}
We can also write some helper methods that will give us the initial array and to print an array to the console (also one that will write a header to the console):
private static char[,] GetInitialArray()
{
var initialArray = new char[4, 5];
for (var row = 0; row <= initialArray.GetUpperBound(0); row++)
{
for (var col = 0; col <= initialArray.GetUpperBound(1); col++)
{
if ((row == 1 && col == 2) || (row == 3 && col == 4))
{
initialArray[row, col] = '.';
}
else
{
initialArray[row, col] = '*';
}
}
}
return initialArray;
}
private static void PrintArrayToConsole(char[,] input)
{
if (input == null) return;
for (var row = 0; row <= input.GetUpperBound(0); row++)
{
for (var col = 0; col <= input.GetUpperBound(1); col++)
{
Console.Write(input[row, col]);
}
Console.WriteLine();
}
}
private static void WriteHeader(string headerText)
{
if (string.IsNullOrEmpty(headerText))
{
Console.Write(new string('═', Console.WindowWidth));
return;
}
Console.WriteLine('╔' + new string('═', headerText.Length + 2) + '╗');
Console.WriteLine($"║ {headerText} ║");
Console.WriteLine('╚' + new string('═', headerText.Length + 2) + '╝');
}
With these helper methods, we can then write code like:
private static void Main()
{
var chrRaster = GetInitialArray();
WriteHeader("Before");
PrintArrayToConsole(chrRaster);
ExposeDotNeighbors(chrRaster);
WriteHeader("After");
PrintArrayToConsole(chrRaster);
GetKeyFromUser("\nDone! Press any key to exit...");
}
And out output would look like:
I noticed that you also appear to be getting the values from the user, and using try/catch blocks to validate the input. A better approach might be to write a helper method that takes in a string that represents the "prompt" to the user, and a validation method that can be used to validate the input. With this, we can keep asking the user for input until they enter something valid.
Below are methods that get an integer and a character from the user, and allow the caller to pass in a function that can be used for validation. These methods will not return until the user enters valid input:
private static char GetCharFromUser(string prompt, Func<char, bool> validator = null)
{
char result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadKey().KeyChar;
} while (!(validator?.Invoke(result) ?? true));
Console.WriteLine();
return result;
}
private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can then re-write our GetInitialArray method to use these methods to get the dimensions and values from the user:
private static char[,] GetInitialArray()
{
const int maxCols = 20;
const int maxRows = 20;
var numCols = GetIntFromUser(
$"How many columns do you want (1 - {maxCols}): ",
i => i > 0 && i <= maxCols);
var numRows = GetIntFromUser(
$"How many rows do you want (1 - {maxRows}): ",
i => i > 0 && i <= maxRows);
var initialArray = new char[numRows, numCols];
for (var row = 0; row <= initialArray.GetUpperBound(0); row++)
{
for (var col = 0; col <= initialArray.GetUpperBound(1); col++)
{
initialArray[row, col] = GetCharFromUser(
$"Enter value for [{row}, {col}] ('.' or '*'): ",
c => c == '.' || c == '*');
}
}
return initialArray;
}
And now our output might look like this:
If you try it, notice that you cannot enter an illegal value. The program just waits for you to read the instructions and enter a valid number or character. :)
Here is the algorithm that does what you want. I have tried to explain my code in the comments. The output will match what you're looking for.
static void Main(string[] args)
{
char STAR = '*';
char DOT = '.';
var input = new char[,]
{
{ STAR,STAR,STAR,STAR,STAR},
{ STAR,STAR,DOT,STAR,STAR},
{ STAR,STAR,STAR,STAR,STAR},
{ STAR,STAR,STAR,STAR,DOT}
};
var output = new char[4, 5];
// Copy each from input to output, checking if it touches a '.'
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 5; y ++)
{
if (input[x, y] == STAR)
{
var isDot = false;
// Check left
if (x > 0)
isDot = input[x - 1, y] == DOT;
// Check right
if (x < 3)
isDot = isDot || (input[x + 1, y] == DOT);
// Check above
if (y > 0)
isDot = isDot || (input[x, y - 1] == DOT);
// Check below
if (y < 4)
isDot = isDot || (input[x, y + 1]) == DOT;
output[x, y] = isDot ? DOT : STAR;
}
else
{
output[x, y] = input[x, y];
}
}
}
// Print output
for (int x = 0; x < 4; x ++)
{
for (int y = 0; y < 5; y ++)
{
Console.Write(output[x, y]);
}
Console.WriteLine();
}
Console.Read();
}
You can go like this :
using System;
public class chars
{
public static void Main(string[] args)
{
char[,] charArray = new char[,] {{'*','*','*','*','*'},
{'*','*','.','*','*'},
{'*','*','*','*','*'},
{'*','*','*','*','.'}};
int[,] holdIndex = new int[4, 5];
for(int i = 0; i<4; i++) // get allindexes containing '.'
{
for(int j = 0; j<5; j++)
{
if(charArray[i,j] == '.')
holdIndex[i,j] = 1;
else
holdIndex[i,j] = 0;
}
}
for(int i = 0; i<4; i++)
{
for(int j = 0; j<5; j++)
{
if(holdIndex[i,j] == 1)
{
if(i!=0)
charArray[i-1,j] = '.'; //up
if(j!=0)
charArray[i,j-1] = '.'; // left
if(j!=4)
charArray[i,j+1] = '.'; //right
if(i!=3)
charArray[i+1,j] = '.'; //down
}
}
}
for(int i = 0; i<4; i++)
{
for(int j = 0; j<5; j++)
{
Console.Write(charArray[i,j]);
}
Console.WriteLine();
}
Console.Read();
}
}

finding prime numbers c#

the program should ask for a number and print all the primes numbers between 1 to the number the user entered... why isn't it working?
bool isPrime = true;
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
if (isPrime)
{
Console.WriteLine(i + " is a prime number");
primes++;
}
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");
You have put the boolean out of the loops. So, once it is false, it will never be true in other loops and this cause the issue.
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
bool isPrime = true;
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
if (isPrime)
{
Console.WriteLine(i + " is a prime number");
primes++;
}
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");
First define this class:
public static class PrimeHelper
{
public static bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
then call it in your application:
var finalNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < finalNumber; i++)
{
bool prime = PrimeHelper.IsPrime(i);
if (prime)
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
}

Outside Bounds of Array When Reading From File

I'm new to C# - I've got a 'Treasure Hunt' game here - it hides a 't' in a box, then the user inputs coordinates - if they get 't' it says they've won, if not then a 'm' is displayed.
I'm trying to setup save games linked to the name a user enters. It writes the save game to a txt file and stores it - that much works. But when I try to load the game I keep getting an error 'Index was outside the bounds of the array'.
static string username = "";
static string saveGame = "";
public const int BoardSize = 10;
static void Main(string[] args)
{
char[,] Board = new char[10, 10];
Console.WriteLine("Would you like to:");
Console.WriteLine("1. Start New Game");
Console.WriteLine("2. Load Game");
Console.WriteLine("9 Quit.");
int mainMenuChoice = 0;
mainMenuChoice = int.Parse(Console.ReadLine());
if (mainMenuChoice == 1)
{
Console.WriteLine("What is your name?");
username = Console.ReadLine();
}
else if (mainMenuChoice == 2)
{
Console.WriteLine("What was your username?");
username = Console.ReadLine();
saveGame = username + ".txt";
LoadGame(saveGame, ref Board);
}
else if (mainMenuChoice == 9)
{
Console.WriteLine("Closing in 3 seconds.");
Thread.Sleep(3000);
Environment.Exit(0);
}
Random randomOneX = new Random();
randomOneX = new Random(randomOneX.Next(0, 10));
int randomX = randomOneX.Next(0, BoardSize);
randomOneX = new Random(randomOneX.Next(0, 10));
int randomY = randomOneX.Next(0, BoardSize);
//Console.Write(randomX);
//Console.Write(randomY);
for (int i = 0; i < Board.GetUpperBound(0); i++)
{
for (int j = 0; j < Board.GetUpperBound(1); j++)
{
Board[i, j] = ' ';
}
}
Board[randomX, randomY] = 'x';
PrintBoard(Board);
int Row = 0;
int Column = 0;
bool wonGame = false;
Console.WriteLine();
Console.WriteLine("I've hidden a 't' in a map - you're job is to find the coordinates that have the 't' in.");
Console.WriteLine();
do
{
Console.Write("Please enter a Row: ");
bool validRow = false;
do
{
try
{
Row = int.Parse(Console.ReadLine());
validRow = true;
if (Row >= 10 || Row < 0)
{
Console.WriteLine("Please pick a number between 0-9: ");
validRow = false;
}
}
catch (Exception)
{
Console.WriteLine("Ooops, you've entered something that simply cannot be, please retry.");
}
} while (validRow == false);
Console.Write("Now enter a column: ");
bool validColumn = false;
do
{
try
{
Column = int.Parse(Console.ReadLine());
validColumn = true;
if (Column >= 10 || Column < 0)
{
Console.WriteLine("Please pick a number between 0-9: ");
validColumn = false;
}
}
catch (Exception)
{
Console.WriteLine("Ooops, you've entered something that simply cannot be, please retry.");
}
} while (validColumn == false);
if (Board[Row, Column] != 'x')
{
Board[Row, Column] = 'm';
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Clear();
Console.WriteLine("You've missed the target! Feel free to retry.");
Console.ForegroundColor = ConsoleColor.Gray;
wonGame = false;
PrintBoard(Board);
SaveGame(username, ref Board);
}
else
{
Board[Row, Column] = 't';
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You've won!");
Console.ForegroundColor = ConsoleColor.Gray;
wonGame = true;
}
} while (wonGame == false);
PrintBoard(Board);
Console.ReadLine();
}
private static void PrintBoard(char[,] Board)
{
Console.WriteLine();
Console.WriteLine("The map looks like this: ");
Console.WriteLine();
Console.Write(" ");
for (int Column = 0; Column < BoardSize; Column++)
{
Console.Write(" " + Column + " ");
}
Console.WriteLine();
for (int Row = 0; Row < BoardSize; Row++)
{
Console.Write(Row + " ");
for (int Column = 0; Column < BoardSize; Column++)
{
if (Board[Row, Column] == '-')
{
Console.Write(" ");
}
else if (Board[Row, Column] == 'x')
{
Console.Write(" ");
}
else
{
Console.Write(Board[Row, Column]);
}
if (Column != BoardSize)
{
Console.Write(" | ");
}
}
Console.WriteLine();
}
}
private static void SaveGame(string username, ref char [,] inBoard)
{
StreamWriter sGame = null;
string saveFilePath = username + ".txt";
try
{
sGame = new StreamWriter(saveFilePath);
}
catch (Exception)
{
Console.WriteLine("Ooops there seems to be an error with saving your game. Check the log for details.");
}
for (int i = 0; i < inBoard.GetUpperBound(0); i++)
{
for (int j = 0; j < inBoard.GetUpperBound(1); j++)
{
sGame.Write(inBoard[i, j]);
}
sGame.WriteLine("");
}
sGame.Close();
}
private static void LoadGame(string GameFile, ref char[,] Board)
{
StreamReader saveGameReader = null;
string Line = "";
try
{
saveGameReader = new StreamReader(GameFile);
}
catch (Exception e)
{
StreamWriter errorMessage = new StreamWriter("ErrorLog.txt", true);
errorMessage.WriteLine(DateTime.Now + "Error: " + e.ToString());
errorMessage.Close();
Debug.WriteLine(e.ToString());
Console.WriteLine("There was an error loading game, check log for info. (Press Enter to exit.)");
Console.ReadLine();
Environment.Exit(0);
}
char[,] loadedBoard = Board;
for (int Row = 0; Row < BoardSize; Row++)
{
Line = saveGameReader.ReadLine();
for (int Column = 0; Column < BoardSize; Column++)
{
loadedBoard[Row, Column] = Line[Column];
}
}
Board = loadedBoard;
saveGameReader.Close();
}
}
}
The link to a notepad screenshot is : https://imgur.com/a/hobuv
The GetUpperBound returns, as MSDN says
Gets the index of the last element of the specified dimension in the
array.
So you are getting 9 everywhere you use that method. To fix your code you need to change your loops in the saving and initialization of the Board array with <= as exit condition from the loops
for (int i = 0; i <= Board.GetUpperBound(0); i++)
{
for (int j = 0; j <= Board.GetUpperBound(1); j++)
{
Board[i, j] = ' ';
}
}
Your save has 9 rows but your board size was defined as 10
If your values in the file are like below
m m m m m m m m X m m m
m m m m m X m m X m m m
m m m X m m m m X m m m
Then you can try with this approach
int i = 0;
// Read the file and work it line by line.
string[] lines = File.ReadAllLines(gameFile);
foreach(string line in lines)
{
string[] columns = line.Split(' ');
for(int j = 0; j < columns.Length; j++)
{
loadedBoarder[i, j] = columns[j];
}
i++;
}
#captainjamie : Thanks for correcting my code.

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";
}
}
}
}

C# How to exclude an int from an array?

So I've got an array of integer. I want to use a loop and exclude integers that makes the equation true. So that would be like
for (int n = 0; n < first9char.Length; n++ ) {
if (first9char[n] == clickValue) {
first9char[n] = first9char[n + 1];
But then it only changes the value that is equal to not changing whole array. So is there any way to do this?
I want to use it in this loop.
if (UserSquareMethod.clickedBoxes[0] == -1) {
MessageBox.Show("You have not selected any box");
} else {
int i = 0;
do {
if (textButtonArray[clickedBox[i]].Text == "" || clickValue == "") {
textButtonArray[clickedBox[i]].Text = clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 14, FontStyle.Bold);
}
else
{
textButtonArray[clickedBox[i]].Text += "," + clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 5, FontStyle.Regular);
string[] first9char = textButtonArray[clickedBox[i]].Text.Split(new string[] { "," }, StringSplitOptions.None);
for (int j = 1; j < first9char.Length; j++)
{
for (int k = j - 1; k >= 0; k--)
{
if (first9char[j] == first9char[k])
{
if (clearNumberClicked == true)
{
first9char = Array.FindAll(first9char, x => x != clickValue);
label2.Text = first9char[0];
//int n = 0;
//for (int p = 0; p < first9char.Length; p++)
//{
// if (first9char[p] != clickValue)
// {
// first9char[n] = first9char[p];
// n++;
// label2.Text += "," + first9char[n];
// }
// }
//for (int n = 0; n < first9char.Length; n++ ) {
//if (first9char[n] == clickValue) {
// first9char[n] = first9char[n + 1];
// for ( int p = 0; p < n; p++) {
//}
//}
//}
MessageBox.Show("Clear the number" + first9char[(first9char.Length - 1)] + "and " + clickValue + " " + first9char.Length);
}
else {
first9char[j] = "";
textButtonArray[clickedBox[i]].Text = first9char[0];
MessageBox.Show("You cannot enter the same number again!"+ first9char[j]+j);
for (int m = 1; m < (first9char.Length - 1); m++) {
textButtonArray[clickedBox[i]].Text += ","+ first9char[m];
}
}
}
}
}
if (textButtonArray[clickedBox[i]].Text.Length > 9)
{
textButtonArray[clickedBox[i]].Text = first9char[0] + "," + first9char[1] + "," + first9char[2] + "," + first9char[3] + "," + first9char[4];
MessageBox.Show("You cannot enter more than 5 numbers, please clear the box if you want to enter different number." + textButtonArray[clickedBox[i]].Text.Length);
}
}
i++;
}
while (clickedBox[i] != -1);
}
}
I would use LINQ for this:
first9char = first9char.Where(x => x != clickValue).ToArray();
It just means "pick the items that don't match". If you can't use LINQ for some reason, then just keep another counter, and make sure to only loop to n from there on in:
int n = 0;
for(int i = 0; i < first9char.Length; i++) {
if(first9char[i] != clickValue) {
first9char[n] = first9char[i];
n++;
}
}
Clean and efficient.

Categories

Resources