#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    4
    Rep Power
    0

    Beginner here, need help with matrix functions in C++


    so this is my goal im trying to create 3 matrix functions, but i am also trying to create another function that shows the numbers of each matrix.
    when I run my code it does what i want
    but it only outputs one grid
    (matrix1 im guessing) and the its a mess of numbers.
    im trying to achieve inputting all the numbers for each matrix and then i want the program to show me the results of each matrix.here is my code so far:

    Code:
    using namespace std;
    
    int matrix1();
    int matrix2();
    int matrix3();
    void result();
    
    int main()
    {
    
    	matrix1();
    	matrix2();
    	matrix3();
    	result();
    
    	system("pause");
    	return 0;
    }
    int matrix1()
    {
    	 int row,column;
        int arr[3][3]; 
    	cout << endl;
    	cout << "matrix1" << endl;
        for (row = 0; row < 3; row++)
            for (column = 0; column < 3; column++)
            {
                std::cout << "ENTER NUMBER " << (column + 1) + 3 * (row) << " : ";
                std::cin >> arr[row][column];
            }
    
        return 0;
    }
    int matrix2()
    {
    	int row,column;
        int arr[3][3];
    	cout << endl;
    	cout << "matrix2" << endl;
    
        for (row = 0; row < 3; row++)
            for (column = 0; column < 3; column++)
            {
                std::cout << "ENTER NUMBER " << (column + 1) + 3 * (row) << " : ";
                std::cin >> arr[row][column];
            }
    
        return 0;
    }
    int matrix3()
    {
    	int row,column;
        int arr[3][3];
    	cout << endl;
    	cout << "matrix3" << endl;
    
        for (row = 0; row < 3; row++)
            for (column = 0; column < 3; column++)
            {
                std::cout << "ENTER NUMBER " << (column + 1) + 3 * (row) << " : ";
                std::cin >> arr[row][column];
            }
    
        return 0;
    }
    void result()
    {
    	int row, column;
    	int arr[3][3];
        for (row = 0; row < 3; row++)
        {
            for (column = 0; column < 3; column++)
            {
                std::cout << arr[row][column] << " ";
            }
            std::cout << std::endl;
        }
        std::cout << "\n\nand here you have a matrix\n";
    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    arr is a local variable in each function. It does not exist outside of the function. There is no connection whatsoever between the arr in result and the arres in the other three functions. In result, its arr has not been initialized and hence is filled with garbage (ie, whatever random values had last been written to those memory locations). Therefore, you end up outputting garbage, as you have duly noted.

    The array(s) you are inputting values into must exist outside the functions, either as globals (strongly discouraged by the principles of structured programming) or as variables local to main and which are somehow passed in to the matrix functions.

    PS

    Two other scenarios.

    You could create the array dynamically in the function and pass a reference to it out to the calling function. This is generally discouraged because that would require the calling function to take care of deleting the array. Failure to do so would result in memory leaks which is a very serious problem in programs meant to run for extended periods of time. General good practice is for every function to be responsible for cleaning up after itself, which includes deleting dynamic objects that it creates.

    Second, you may be tempted to make arr static, which moves it into static memory thus allowing it to continue to exist after you exit the function. The problem with this is that that static array would only be visible inside that function. Therefore, there would exist four separate arrays, one for each function, only one of which, the uninitialized one filled with garbage, would be accessible from result().
    Last edited by dwise1_aol; May 10th, 2013 at 04:54 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    4
    Rep Power
    0
    The array(s) you are inputting values into must exist outside the functions, either as globals (strongly discouraged by the principles of structured programming) or as variables local to main and which are somehow passed in to the matrix functions.
    what exactly do you mean by exist outside of the functions? like in the main i must create 1 array or 3 seperate ones?
    im not really following what you wrote.
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    Yes, that is what I mean.

    Local variables are variables declared inside of functions. The local variables declared inside a function, such as matrix1(), are only visible and accessible inside of matrix1(). None of matrix1's local variables can be accessed by any of the other functions, nor by main, nor even by any function that matrix1 may call. Furthermore, local variables are of the auto storage class, which means that they don't exist until the function is called and they cease to exist when you leave the function by returning (which is also done by "falling off the end of the function").

    To summarize, a function's local variables:
    1. only exist within that function and only for that function call. And when you call the same function again, what you had stored in a local variable is no longer there (unless you declare it as static).

    2. can only be accessed within the function. This is also called visibility. Only the function can see and access its own local variables; no other function can see them.

    From what I read from your code, you want to create three arrays. That means that you need to declare those three arrays outside of the functions that load them with values. main() would be an acceptable place to put them, all three arrays. Then instead of three different functions to load an array, write only one function and call it three times, passing a different array to it each time. Similarly, pass whichever array to result that you want to display the contents of.

    Do you understand the nature of local variables? And of when they come into existence and when they cease to exist?

    Does your textbook talk about storage classes? In particular, the difference between static and auto? If not, then here's an explanation in Wikipedia, though there they term them as Storage duration specifiers. It is a very important concept in C and is absolutely vital to your problem.

    I hope that's making more sense.

    PS
    Yes, I said "in C". These same principles also apply equally in C++.
    Last edited by dwise1_aol; May 10th, 2013 at 05:40 PM.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    Code:
    int fileScope = 0 ;
    func1()
    {
    	int localScope = 1 ;
    }
    
    func2()
    {
    	int localScope = 2 ;
    }
    
    int main( int argc, char** )
    {
    	int localScope = 4 ;
    	func1() ;
    	func2() ;
    	
    	{ // a new scope
    		localScope = 5 ;
    		cout << fileScope << ',' << localScope << endl ;
    	}
    }
    Functions scope variables only "live" for the life of the function call and are only available inside that function. File scope variables are visible to everything in the compilation unit after the variable is declared or defined.
    I no longer wish to be associated with this site.
  10. #6
  11. No Profile Picture
    Permanently Banned
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    Chennai
    Posts
    6
    Rep Power
    0

    Beginner here, need help with matrix functions in C++


    Thanks for the help.I given below one examples please try to this get answers.

    #include <iostream.h>

    int main()
    {
    int row,column;
    int array[3][3]; // i put 3 because its 3 numbers across up to 3 numbers down

    for (row = 0; row < 3; row++)
    for (column = 0; column < 3; column++)
    {
    std::cout << "ENTER NUMBER " << (column + 1) + 3 * (row) << " : ";
    std::cin >> array[row][column];
    }

    for (row = 0; row < 3; row++)
    {
    for (column = 0; column < 3; column++)
    {
    std::cout << array[row][column] << " ";
    }
    std::cout << std::endl;
    }
    std::cout << "\n\nand here you have a matrix\n";
    return 0;
    }

    ---
    <removed fake signatures>
    Last edited by Scorpions4ever; May 11th, 2013 at 05:08 AM.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    4
    Rep Power
    0
    ok so in my void function i put

    void result(arr[][3][3]) // no errors

    but when i try to send the values to the function i get error

    result([arr],3);//it keeps telling me there is a syntax error as well as too many arguments in function call.

    i havent discussed static specifiers in class so im not really familiar with them. i would need a more detailed example with explanation to grasp it fully (i ask a lot of questions in class) but creating these multidimensional arrays is difficult for me.
  14. #8
  15. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    Please show us the code. result([arr],3); is just plain wrong, but I don't know whether that's a typo you committed when writing that message.

    Declaring a local variable as static would not help you here. Yes, it allows a variable to persist between function calls and it's usually used to remember what it was set to the last time that function was called. But its scope is limited to that one function and so is only visible within that one function; it cannot be used directly to make that variable available to another function.

    jwdonahue was right in using the term "scope", because a variable's scope is what we're talking about and dealing with here. Review what your textbook says about scope; that is the keyword to search on: http://en.wikipedia.org/wiki/Scope_(computer_science)#C
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    4
    Rep Power
    0
    OK, so i think im making progress but still not sure. For the first part i finally achieved what i was trying to do. where the program asks you for the numbers (input) for matrix 1 and then asks you for the input on matrix 2. although there are no errors in the written code when i execute it i get the error when i try to print out both matrices im still not grasping how to associate the input numbers with the final result. here is what i have so far:****** i remember you said to to create 3 separate arrays in the main function but would it be possible to do this instead?


    Code:
    #include "stdafx.h"
    #include <iostream>
    
    using namespace std;
    
    void printarray1(int arrays[][3])
    {
    	int row = 0;
    	int column;
    		cout << endl;
    		cout << "Matrix 1\n" << endl;
    	    for (row = 1; row < 4; row++)
    			for (column = 1; column < 4; column++)
    			{
    				while(row < 4)
    				{
    					int column = 1;
    					while(column< 4)
    					{
    					cout<<"enter number "<<column<<" in row "<<row<<" : ";
    					std::cin >> arrays[row][column];
    					column++;
    					}
    				cout<<"\n";
    				row++;
    				}
    			}
    }
    void printarray2(int arrays[][3])
    {
    	int row = 0;
    	int column;
    		cout << endl;
    		cout << "Matrix 2\n" << endl;
    	    for (row = 1; row < 4; row++)
    			for (column = 1; column < 4; column++)
    			{
    				while(row < 4)
    				{
    					int column = 1;
    					while(column< 4)
    					{
    					cout<<"enter number "<<column<<" in row "<<row<<" : ";
    					std::cin >> arrays[row][column];
    					column++;
    					}
    				cout<<"\n";
    				row++;
    				}
    			}
    }
    void printarrayfinal(int arrays[][3])
    {
    	int row,column, matrix;
            for (matrix = 1; matrix<2; matrix++)
           {
    	    cout << "Matrix " << matrix <<endl;
                for (row = 0; row < 3; row++)
    	    for (column = 0; column < 3; column++)
    	    {
    	          std::cout << arrays[row][column] << " ";
    	     }
    	    std::cout << std::endl;
    	 }
    }
    
    
    			
    int main()
    {
    	
    	int arrays[3][3];
    	
    	printarray1(arrays);
    
    	printarray2(arrays);
    
    	printarrayfinal(arrays);
    return 0;
    }
  18. #10
  19. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    OK, so you created one single array in main, then you pass it to printarray1 and then to printarray2. In both functions, which are virtually identical to each other, you enter values into the array that you pass in. You do realize that when you call printarray2 that you are overwriting what you had input into that very same array in printarray1, don't you?

    If you want to have three arrays that each contain different sets of values, then you must declare three arrays. You could declare three separate and differently named 3x3 arrays. Or you could declare an array of three 3x3 arrays. Either way would work. But when you declare an array of three two-dimensional arrays, then it has to be a three-dimensional array.

    And why have several functions that do the exact same thing? That defeats the purpose of having functions. Have one function that you use to load values into a 2-D 3x3 array and then simply pass to it the particular array you want to load. Similarly, you only need one function to display the contents of an array and then you simply pass to it the particular array you want to display.

    BTW, arrays are indexed from zero, not from one. In the printarrayn functions, you have:
    Code:
    	    for (row = 1; row < 4; row++)
    			for (column = 1; column < 4; column++)
    			{
    				while(row < 4)
    				{
    					int column = 1;
    					while(column< 4)
    					{
    					cout<<"enter number "<<column<<" in row "<<row<<" : ";
    					std::cin >> arrays[row][column];
    					column++;
    					}
    The rows and columns need to iterate from 0 to 2, not from 1 to 3. And I have no idea what that while statement is supposed to be doing there.

IMN logo majestic logo threadwatch logo seochat tools logo