Results 1 to 3 of 3

Thread: Problem with matrix

  1. #1

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    13

    Problem with matrix

    Hi guys, i'm new to C#. I have been trying to create a matrix or size 3x3 with the following code:

    Code:
    using System;
    class matrix
        {
            static void Main(string[] args)
            {
                Console.Write("Enter values for the matrix: ");
                int [,]matrx=new int[3,3];
                for(int i=0;i<3;i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        matrx[i, j] = Console.Read();
                    }
                }
                for(int i=0;i<3;i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        Console.Write(" " +matrx[i, j]);
                    }
                    Console.WriteLine();
                }
            }
        }
    The problem is that it accepts only 3(should be 9) values but gives an output of complete 3x3 matrix with random values. For eg. if i entered the first three numbers (elements) as 1,2 & 3 (after which the loop exits itself n goes to the output), it gives the following output:
    Code:
    Enter values for the matrix: 1
    2 
    3
    
    49 13 10
    50 13 10
    51 13 10
    Press any key to continue...
    It is my belief that the problem is with the Console.Read() line. However, i would be really grateful if you guys point out as to why i'm not getting the desired result. Thanking you all in advance.

  2. #2
    Frenzied Member axion_sa's Avatar
    Join Date
    Jan 2002
    Location
    Joburg, RSA
    Posts
    1,724

    Re: Problem with matrix

    You're right in that it is the Console.Read line - it reads the next character in the console input stream.
    So, what's actually happening here is it's detecting your enter keystroke - the 13 & 10 values are carriage return/line feed. You'll also note that Console.Read returns the character value - not the integer value itself.

    To work with the carriage return, i.e. accept a value when the user presses enter, and accept the user's input verbatim, change the first loop to:
    Code:
    for (int i = 0; i < 3; i++)
    {
    	for (int j = 0; j < 3; j++)
    	{
    		int lineInput;
    		string consoleInput = Console.ReadLine();
    		if (int.TryParse(consoleInput, out lineInput))
    			matrx[i, j] = lineInput;
    	}
    }

  3. #3

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    13

    Re: Problem with matrix

    Done it @axion_sa, thanks so much for yur help, repped ya.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width