I am new at programming and I'm trying to understand why the methods call inside a switch statement is not working. Basically I have a main menu and a submenu. Whem I press the Animal submenu , the switch statement is meant to call the methods for a CRUD (insert new, visualize by Id, update, etc) but none of these options are working. Is the method call/structure correct?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace menu_clinica_veterinaria
{
class Program
{
public static int id = 1;
enum animalHeader { id, name, client_name, type_animal };
enum clientHeader { id, name, client_surname, adrress };
static void Main(string[] args)
{
string[,] animal = new string[20, 4];
string[,] client = new string[20, 6];
do { MenuOptions(animal); } while (true);
}
static void MenuOptions(string[,] animal)
{
int userChoice;
do
{
Console.Clear();
Console.WriteLine("\nChoose one of the following options:\n");
Console.WriteLine("[ 1 ] Animals");
Console.WriteLine("[ 2 ] Clients");
Console.WriteLine("[ 0 ] Quit application\n");
} while (!int.TryParse(Console.ReadLine(), out userChoice) || userChoice < 0 || userChoice > 2);
Console.Clear();
switch (userChoice)
{
case 1:
menuAnimal(animal);
break;
case 2:
//menuClient(client);
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("Try again!!");
break;
}
}
static void menuAnimal(string[,] animal)
{
int optAnimal;
while (true)
{
do
{
Console.Clear();
Console.WriteLine("\nInsert one of the following options:\n");
Console.WriteLine("[ 1 ] Insert animal");
Console.WriteLine("[ 2 ] See animal");
Console.WriteLine("[ 3 ] Alter animal");
Console.WriteLine("[ 4 ] Erase animal");
Console.WriteLine("[ 5 ] List animals");
Console.WriteLine("[ 0 ] Return to main menu\n");
} while (!int.TryParse(Console.ReadLine(), out optAnimal) || optAnimal < 0 || optAnimal > 5);
Console.Clear();
bool goBack = false;
switch (optAnimal)
{
case 1:
insertData(animal);
break;
case 2:
visualizeByid(animal);
break;
case 3:
updateById(animal);
break;
case 4:
deleteByid(animal);
break;
case 5:
listData(animal);
break;
case 0:
goBack = true;
break;
}
if (goBack) return;
}
}
static void mainMenu()
{
Console.Clear();
Console.ReadKey();
}
static void menuReturn(string[,] animal)
{
Console.Clear();
do { menuAnimal(animal); } while (true);
}
static int generateId()
{
return id++;
}
static int getInsertIndex(string[,] matrix)
{
for (int j = 0; j < matrix.GetLength(0) - 1; j++)
{
if (string.IsNullOrEmpty(matrix[j, 0])) return j;
}
return -1;
}
static void insertData(string[,] matrix)
{
int id = generateId();
int n = getInsertIndex(matrix);
matrix[n, 0] = Convert.ToString(id);
for (int j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[n, j] = Console.ReadLine();
} while (String.IsNullOrEmpty(matrix[n, j]));
}
}
static int searchId(string[,] matrix)
{
int choosenId, index = -1;
do
{
Console.Write("Insert ID to continue: ");
} while (!int.TryParse(Console.ReadLine(), out choosenId));
for (int i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
}
}
return index;
}
static void visualizeByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"{matrix[i, j]}\t");
}
Console.WriteLine();
}
}
else { Console.WriteLine("Wrong Id"); }
}
static void updateById(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[i, j] = Console.ReadLine();
}
Console.WriteLine();
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void deleteByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = null;
}
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void listData(string[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"\t{matrix[i, j]}\t");
}
Console.WriteLine("\n\t");
}
}
}
}
It's a nifty little program for what it is.
However, you can't see an animal because:
searchId
for (var i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
// Though it's not the problem you could break here
// you could also just return from here
break;
}
}
Also, you'll need to Console.ReadKey() somewhere as your menu refreshes and overwrites the see animal routine.
menuAnimal
visualizeByid(animal);
// if you don't do something like this as the menu refreshes the animal away
Console.ReadKey();
The only other thing I'd suggest is to use lists and well-typed classes, instead of multidimensional arrays of strings; they are easier to work with, and you can use Linq.
Update
In regards to comments, given this:
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
You could do something like this:
static void updateById<T>(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {GetHeader<T>(j)}: ");
...
Usage:
updateById<animalHeader>(animal);
Basically this is some generics to reuse the updateById method and using your HeaderType.
Your program working Fine. You are using Console.Clear(). It will clear the screen which is displayed previously on the screen. Remove Console.Clear() in the program or Add Console.ReadKey() immediately after Switch block. I think it will work fine.
Related
I wrote a code for a 3x3 bingo game. It check for line, bingo or nothing for a given input where I get a 3x3 bingo card and next 15 numbers extracted.
Basically I use a 2D user inputed array for the 3x3 bingo card, then I have a function which asks me to input 15 numbers. If all the numbers from the 3x3 bingo card are present in those 15 extracted numbers then I have "bingo". If I have numbers from a line but not all numbers then the program will output "line". And if i will not have bingo neither line the program will output "nothing".
I don't like the CheckForLine() function using 3 nested loops. I can't use Linq, due to Sonar analyzer limitation.
using System;
class Program
{
static void Main()
{
const int numberOfRows = 3;
const int numberOfColumnns = 3;
const int numbersExtracted = 15;
int[,] bingoCard = ReadBingoCard(numberOfRows, numberOfColumnns);
int[] numbers = ReadNumbersExtracted(numbersExtracted);
PrintResult(bingoCard, numbers);
}
static int[,] ReadBingoCard(int rowsNumber, int columnNumber)
{
int[,] card = new int[rowsNumber, columnNumber];
for (int i = 0; i < rowsNumber; i++)
{
string[] array = Console.ReadLine().Split(' ');
for (int j = 0; j < columnNumber; j++)
{
card[i, j] = Convert.ToInt32(array[j]);
}
}
return card;
}
static int[] ReadNumbersExtracted(int numbersExtracted)
{
int[] numbers = new int[numbersExtracted];
for (int i = 0; i < numbersExtracted; i++)
{
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
return numbers;
}
static bool CheckForBingo(int[,] bingoCard, int[] numbers)
{
int numMatchesFound = 0;
foreach (var number in bingoCard)
{
for (int numIndex = 0; numIndex < numbers.Length; numIndex++)
{
if (number == numbers[numIndex])
{
numMatchesFound++;
break;
}
}
}
return numMatchesFound == bingoCard.Length;
}
static bool CheckForLine(int[,] bingoCard, int[] numbers)
{
for (int row = 0; row < bingoCard.GetLength(0); row++)
{
int colMatchesInRow = 0;
for (int col = 0; col < bingoCard.GetLength(1); col++)
{
for (int numIndex = 0; numIndex < numbers.Length; numIndex++)
{
if (bingoCard[row, col] != numbers[numIndex])
{
continue;
}
colMatchesInRow++;
break;
}
}
if (colMatchesInRow == bingoCard.GetLength(1))
{
return true;
}
}
return false;
}
static void PrintResult(int[,] bingoCard, int[] numbersExtracted)
{
if (CheckForBingo(bingoCard, numbersExtracted))
{
Console.WriteLine("bingo");
}
else if (CheckForLine(bingoCard, numbersExtracted))
{
Console.WriteLine("line");
}
else
{
Console.WriteLine("nothing");
}
}
}
I am trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). The subroutine 'ComputerMove();' does not execute for some reason, why is that? I am yet to finish but it is the ComputerMove subroutine that I am confused with. Apologies in advance if I am missing something obvious.
(Edit: There is no error message, just a blank console)
using System;
using System.Threading;
namespace THE_NIM
{
class Program
{
static char[,] Board = new char[7, 12];
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static bool GameStatus = false;
static string firstMove;
static void Introduction()
{
Console.WriteLine("\t\t\t\t\t" + underline + "Welcome to NIM!\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(underline + "The rules are as follows:\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Thread.Sleep(1500);
}
static void PrintBoard()
{
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i <= 6; i++)
{
Console.Write(" ");
for (int j = 0; j <= 11; j++)
{
Console.Write(Board[i, j]);
}
Console.WriteLine();
Console.WriteLine();
}
}
static void WhoGoesFirst()
{
string[] PossibleChoices = { "Computer", "You" };
Random WhoGoesFirst = new Random();
int WGFIndex = WhoGoesFirst.Next(0, 2);
firstMove = PossibleChoices[WGFIndex];
Console.WriteLine("Randomly selecting who goes first...");
Thread.Sleep(1000);
Console.WriteLine("{0} will go first!\n", firstMove);
Thread.Sleep(1000);
}
static void PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
switch (PlayerStackSelection)
{
case(1):
PlayerStackSelection = 0;
break;
case (2):
PlayerStackSelection = 2;
break;
case (3):
PlayerStackSelection = 4;
break;
case (4):
PlayerStackSelection = 6;
break;
case (5):
PlayerStackSelection = 8;
break;
case (6):
PlayerStackSelection = 10;
break;
}
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == ' ')
{
spaces += 1;
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + PlayerRemovedSelection); i++)
{
Board[i, PlayerStackSelection] = ' ';
}
}
PrintBoard();
CheckIfBoardEmpty();
}
static void ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 7);
int PreChangeStack = CompStackSelection;
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 7);
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
while (spaces == 7)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
CompStackSelection = CompStack.Next(1, 7);
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if ((nearestBlock + CompRemovedSelection) !< 8)
{
while ((nearestBlock + CompRemovedSelection) !< 8)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + CompRemovedSelection); i++)
{
Board[i, CompStackSelection] = ' ';
}
}
Console.WriteLine("Computer is making its move... ");
Thread.Sleep(1000);
Console.WriteLine("Computer has decided to remove {0} blocks from stack number {1}.\n", CompRemovedSelection, PreChangeStack);
Thread.Sleep(1000);
PrintBoard();
CheckIfBoardEmpty();
}
static void CheckIfBoardEmpty()
{
bool keepGoing = false;
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (Board[i,j] == '█')
{
GameStatus = false;
keepGoing = true;
break;
}
}
}
if (keepGoing != true)
{
Console.Write("BOARD EMPTY");
GameStatus = true;
}
}
static void Main(string[] args)
{
Introduction();
WhoGoesFirst();
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (j % 2 == 0)
{
Board[i, j] = '█';
}
else
{
Board[i, j] = ' ';
}
}
}
if (firstMove == "You")
{
while (GameStatus == false)
{
PlayerMove();
ComputerMove();
}
}
else
{
while (GameStatus == false)
{
ComputerMove();
PlayerMove();
}
}
}
}
}
I wonder what I do wrong about that task:
I had to create a table[][,] where I enter from the keyboard number of groups, the number of students in each group and how many subjects they have.
For each student, I had to enter a grade for each subject.
I don't actually where is my mistake.
Because the program I wrote can't show properly full table (f.e. if in a group no. 1 I have 3 students and for a group no. 2 I have 1 student it shows for each group 1 student)
Also I used "float" to calculate the Average of all grades for each group but it shows the integer number.
Can you help me?
I attached the code down below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpecialTask
{
class Program
{
static int[][,] tab1;
static int iSub = 0;
static int iGro = 0;
static int iStu = 0;
static int note = 0;
static int iSum = 0;
static float fAvg = 0.0f;
static int Subjects(string sSubjects)
{
do
{
Console.WriteLine("Please enter a number of subjects (2-4):");
}
while ((!int.TryParse(Console.ReadLine(), out iSub)) || (iSub < 2) || (iSub > 4));
return iSub;
}
static int Groups(string sGroups)
{
do
{
Console.WriteLine("Please enter a number of groups (1-3):");
}
while ((!int.TryParse(Console.ReadLine(), out iGro)) || (iGro < 1) || (iGro > 3));
return iGro;
}
static int Students(string sStudents)
{
do
{
Console.WriteLine("Please enter a number of students(1-5): ");
}
while ((int.TryParse(Console.ReadLine(), out iStu) == false) || (iStu < 1) || (iStu > 5));
return iStu;
}
static int Notes(string sNotes)
{
do
{
Console.WriteLine("Please enter a note (2-5): ");
}
while ((!int.TryParse(Console.ReadLine(), out note)) || (note < 2) || (note > 5));
return note;
}
static void TabData()
{
int i, j, k;
Subjects("Please enter a number of subjects (2-4):");
Groups("Please enter a number of groups (1-3):");
tab1 = new int[iGro][,];
for (i = 0; i < iGro; i++)
{
Console.WriteLine("Group NO.{0}", 1 + i);
Students("Please enter a number of students(1-5): ");
tab1[i] = new int[iStu, iSub];
for (j = 0; j < iStu; j++)
{
for (k = 0; k < iSub; k++)
{
Console.WriteLine("Student NO.{0}", 1 + j);
Console.WriteLine("Subject NO.{0}", 1 + k);
tab1[i][j, k] = Notes("Please enter a note (2-5): ");
}
}
}
Console.WriteLine("\n");
Console.WriteLine("\n");
for (i = 0; i < iGro; i++)
{
Console.WriteLine("Group NO.{0}: ", 1 + i);
for (j = 0; j < tab1.Length; j++)
{
Console.WriteLine("Student NO.{0}/Group NO.{1}: ",1+ j, 1 + i);
for (k = 0; k < iSub; k++)
{
Console.Write("Subject NO.{0}: ", 1 + k);
Console.Write(tab1[i][j, k]);
Console.Write("\n");
}
Console.WriteLine("\n");
}
}
}
static void avgG()
{
int i, j, k;
TabData();
for (i = 0; i < iGro; i++)
{
for (j = 0; j < iStu; j++)
{
for (k = 0; k < iSub; k++)
{
iSum = iSum + tab1[i][j, k];
}
}
fAvg = iSum / iSub;
Console.WriteLine("Sum: " + iSum);
Console.WriteLine("Average of all grades for Group NO. {0}: {1}", i, fAvg);
}
}
static void Main(string[] args)
{
avgG();
Console.ReadKey();
Console.ReadKey();
}
}
}
This program will sort numbers and depending if they are greater than or less than 100, put them into their own array.
The problem I have is printing this array. I would like the last number on the line, to not be followed by a space. I have tried many many times to get this to work now and figured I'd ask here.
I know of Console.Write("\b"); but I prefer to find a way of editing the loop so I don't have to do this. Here is the code:
using System;
using System.Linq;
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
for (int i = 1; i < bigIndex; ++i)
{
Console.Write(bigNumbers[i]);
Console.Write(" ");
}
Console.WriteLine();
//Console.WriteLine($"{bigNumbers[0]}");
Console.Write("Little: ");
for (int i = 0; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
Console.Write(" ");
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
You could just capture your Console.Write(" "); in an if statement.
if(i != littleIndex - 1)
{
Console.Write(" ");
}
littleIndex - 1 is the last time your loop executes, so this will just prevent it from adding the trailing white space. Just do the same for your big numbers as you're printing them out.
There is a builtin utility string.Join
var str = string.Join(" ",bigNumbers);
Console.WriteLine("Big: " + str);
I was playing around some more and just thought I'd try posting the first object in the array before running this loop (also changed loop so the first item didn't get printed twice).
Thank you everyone - I solved it! :)
using System;
using System.Linq;
namespace Arrays
{
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
Console.Write($"{bigNumbers[0]} ");
for (int i = 1; i < bigIndex; i++)
{
Console.Write(bigNumbers[i]);
if (i != bigIndex - 1)
{
Console.Write(" ");
}
}
Console.WriteLine();
Console.Write("Little: ");
Console.Write($"{smallNumbers[0]} ");
for (int i = 1; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
if (i != littleIndex - 1)
{
Console.Write(" ");
}
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
}
This is a code sample that multiplies a matrix by a number of user input. The action should be repeated by the number of user input. For example if I put a number 3 I get 3 same printed matrix. Instead I want that matrix is multiplied with number 3 for 3 times (each new matrix is multiplied by number 3). Does anyone have idea how I can do it? Thank you
*using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace user_input
{
class Program
{
static void Main(string[] args)
{
string[] nodes = { "1", "2", "3", "4", "5", "6" };
int[,] adjmatrix = new int[,]
{{2,7,3,8,4},
{7,0,8,2,6},
{6,8,4,9,7},
{8,5,9,8,8},
{4,9,7,8,1}
};
int[,] newmatrix = new int[adjmatrix.GetLength(0), adjmatrix.GetLength(1)];
Printmatrix(adjmatrix, nodes, nodes, "Input Matrix");
Newline();
int n = 0;
System.Console.WriteLine("Please enter a number");
n = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < n; i++)
{
MultipliedMatrix(ref newmatrix, adjmatrix, n);
Newline();
Printmatrix(newmatrix, nodes, nodes, "Multiplied Matrix");
}
Console.ReadKey();
}
private static void Newline()
{
Console.Write("\n");
}
private static void MultipliedMatrix(ref int[,] newmatrix, int[,] adjmatrix, int n)
{
for (int i = 0; i < adjmatrix.GetLength(0); i++)
{
for (int j = 0; j < adjmatrix.GetLength(1); j++)
{
newmatrix[i, j] = adjmatrix[i, j] * n;
}
}
}
private static void Printmatrix(int[,] adjmatrix, string[] nodes_h, string[] nodes_v, string title)
{
if (adjmatrix.GetLength(0) != 0)
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write("{0}\n", title);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("\t");
for (int i = 0; i < adjmatrix.GetLength(0); i++)
Console.Write("{0}\t", nodes_v[i]);
for (int i = 0; i < adjmatrix.GetLength(0); i++)
{
Newline();
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("{0}\t", nodes_h[i]);
for (int j = 0; j < adjmatrix.GetLength(1); j++)
{
Console.ForegroundColor = ConsoleColor.DarkGray;
if (adjmatrix[i, j] < 500) Console.Write("{0}\t", adjmatrix[i, j]);
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("-\t", adjmatrix[i, j]);
}
}
Console.ForegroundColor = ConsoleColor.White;
}
Newline();
}
}
}
}*
*
first I would change the multiply to a function instead of void method call, so it looks nicer an then
this would be the pseudocode:
n = userinput;
i=0;
int[,] result;
do
i+=1;
result = MultiplyMatrix(result, n);
while i<n
int[,] MultiplyMatrix(adjmatrix, n){
(multiply)
return resultMatrix };
You keep passing the same matrix as input to MultipliedMatrix(), so it keeps doing the same thing.
To make it operate on the new matrix, add the following line immediately after the call to Printmatrix() inside the loop:
adjmatrix = newmatrix;
Alternatively (and better IMO) is to change MultipliedMatrix() to return the new matrix, like so:
private static int[,] MultipliedMatrix(int[,] adjmatrix, int n)
{
int[,] newmatrix = new int[adjmatrix.GetLength(0), adjmatrix.GetLength(1)];
for (int i = 0; i < adjmatrix.GetLength(0); i++)
for (int j = 0; j < adjmatrix.GetLength(1); j++)
newmatrix[i, j] = adjmatrix[i, j] * n;
return newmatrix;
}
Then your code in the multiply loop would look like this:
for (int i = 0; i < n; i++)
{
adjmatrix = MultipliedMatrix(adjmatrix, n);
Newline();
Printmatrix(adjmatrix, nodes, nodes, "Multiplied Matrix");
}
Note that this loses the reference to the original adjmatrix, which is not a problem for your current code.
However if you needed to keep the original reference, do it like this:
var newMatrix = adjmatrix;
for (int i = 0; i < n; i++)
{
newMatrix = MultipliedMatrix(newMatrix, n);
Newline();
Printmatrix(adjmatrix, nodes, nodes, "Multiplied Matrix");
}