I am having some problems with writing a 2d array, then displaying it, and then showing the sum of all of the elements. A major part of this problem is that i nave to write three seperate functions to achieve this. it is supposed to do this:

For this exercise you will use both arrays and functions! Write a program called matrix.c that adds every element in a 2-dimensional array (matrix). Your matrix will be 5 x 5 (5 rows and 5 columns). The requirement is to use nested "for loops" in your program.

You must develop 3 functions within this program: One to read user input; another to display the 2-D array; and a third that returns the total of all elements in the 2-D array. The 3rd function should NOT print the value, rather the value should be returned from the function to main, and main will display the result. Your function prototype might look like this: int addArray( int arr[ ][ COLSIZE ] );

Make the program flexible so that you can easily change the size of the table. A suggestion for doing so is to use a define, for example: #define rowSIZE 5.

Input
5 x 5 matrix

Output
Output the matrix

Output the matrix sum

Below is a sample of expected output (my input is in blue - this is to illustrate only, yours will not be blue):

Please enter enter data for a 5 by 5 array:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

Our Array to sum is:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

The total of all elements in our array is: 325
Press any key to continue . . .

this is the code i have, i fear it is way wrong as i am getting error codes of "expected primary-expression before 'int' " , "expected ';' before 'int' " (both of these in my main staement line 47), and "expected '}' at end of input " (line 78 in my return statement)...

Here is my "sure to be flawed" code:

#include <stdio.h>
#include <stdlib.h>

#define rowSIZE 5
#define colSIZE 5

int myMatrix[rowSIZE][colSIZE];

int myFunction(void)
{
int row = 0,
col = 0;

for (row = 0; row < rowSIZE; row++)
for (col = 0; col < colSIZE; col++)
printf("Please enter the data for our %d by %d array: ", rowSIZE, colSIZE);
scanf("%i", &myMatrix[row][col]);
}


int printArray(int myMatrix[rowSIZE][colSIZE])
{
    int row, col;
    
    for ( row = 0; row < rowSIZE ; row++ ) 

            for ( col = 0; col < colSIZE ; col++ )

                              printf("%d\t", myMatrix[ row ][ col ]);

            printf("\n");
}

int sumArray(int myMatrix[rowSIZE][colSIZE])
{
    int row, col, sum = 0;
    
    for ( row = 0; row < rowSIZE ; row++ ) {

            for ( col = 0; col < colSIZE ; col++ )
                
                sum += myMatrix[row][col];
                
     return sum ;
}

int main (void)

{
    int sum = 0;
    int row, col;
    int arrayToSum[rowSIZE][colSize];
    
    for ( row = 0; row < ROWSIZE ; row++ ) {

            for ( col = 0; col < COLSIZE ; col++ )
{
            arrayToSum[row][col] = myFunction(myMatrix[row][col]);
}

    for ( row = 0; row < ROWSIZE ; row++ ) {

            for ( col = 0; col < COLSIZE ; col++ )
{
            arrayToSum[row][col] = printArray(myMAtrix[row][col])
}

    for ( row = 0; row < ROWSIZE ; row++ ) {

            for ( col = 0; col < COLSIZE ; col++ )
{
            arrayToSum[row][col] = sumArray(int myMatrix[row][col])
}

            printf("This is the sum of our matrix: %d\n", sum);
            
            return sum;
}

Recommended Answers

All 25 Replies

Your code is full of errors.
1. Check for matching curly braces.
2. main is returning "sum", it should return 0
3. Check for semicolons
4. C is case sensitive. What are ROWSIZE, COLSIZE?

I want main to return the sum, will it not work like that?

No. According to C standards main should only return 0, nothing else. Keep in mind it's a special function, you can't do things you do with other ones.

okay so here is something else i have been working on for this project, i am having problems with using nested for statements with the functions, and i havent set up the sum function either. any suggestions on getting the nested for loops to work how the assignment says they should would help, also how to return a sum function to main would too.

Here is what i have:

#include <stdio.h>
#include <stdlib.h>

#define R_SIZE 5
#define C_SIZE 5

void userInput (int matrix [R_SIZE][C_SIZE]) { //gathering user input
      scanf("%d", &matrix [R_SIZE][C_SIZE]);
}
void displayArray(int matrix [R_SIZE][C_SIZE]) { //dissplaying the Matrix
     printf("%d)", matrix [R_SIZE][C_SIZE]);
     }

int main(void)
{
    int row, col;
    int array[R_SIZE][C_SIZE];
    
    //UI Header
    printf("Please enter enter data for a 5 by 5 array:\n");
    
    //Gather User Input
    for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
            
{
      userInput(array[row][col]);
}
     
    
    //Display User Input
    printf("\n\n\nOur Array to sum is:\n");
    for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
            
{
      displayArray(array[row][col]);
      printf("\n");
   
}
  
    system("PAUSE");
    return 0;
}

I think this is really close it just some tweaking that after hours of looking at a screen is hard to find. for some reason i am having a problem with the matrix inout, after i enter the 5x5 numbers it does not print them it just waits for more input and never gets to a point where it stops and scans into the array....I am confused about what is going on here can anyone help?

#include <stdio.h>
#include <stdlib.h>

#define R_SIZE 5
#define C_SIZE 5

void userInput (int matrix[R_SIZE][C_SIZE], int a, int b)  //gathering user input
{ 
     int row, col;
     for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
        scanf("%d", &matrix[R_SIZE][C_SIZE]);
}

void displayArray(int matrix[R_SIZE][C_SIZE], int a, int b)  //displaying the Matrix
{
     int row, col;
     for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)  
        printf("%d)", matrix[R_SIZE][C_SIZE]);
}

int sumArray(int sum)  //summing the matrix
{
    int row, col, sum;    
     for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
        sum += matrix[row][col];
        
        return sum;
}
    

int main(void)
{
    int row, col, sum = 0;
    int array[R_SIZE][C_SIZE];
    
    //UI Header
    printf("Please enter enter data for a 5 by 5 array:\n");
    
    //Gather User Input
    for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
            
{
      userInput(array, row, col);
}
     
    
    //Display User Input
    printf("\n\n\nOur Array to sum is:\n");
    for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
            
{
      displayArray(array, row, col);
      printf("\n");
   
}

printf("The sum of our array is: %d", sumArray(sum));
  
    system("PAUSE");
    return 0;
}

Just a few points:

Always use curly braces for your for statements (and other control mechanisms as well e.g. while) - it will save you a lot of heartache especially later on if you decide to add more lines of code that should be executed as part of the for statement.

Keep your for loops encapsulated within your functions - there should be no reason to have them in main(). Your main function should be very simple and short - it should only have to call the three functions for creating, displaying and summing the array. For example:

int main (void) {

    int myArray[ROWSIZE][COLSIZE];

    createArray(myArray);
    printArray(myArray);
    printf("The total of all elements in our array is %d\n", sumArray(myArray));

    return 0;
}

If you have learnt about function prototypes, then use them to declare your functions.

As I said in another thread earlier, write some pseudocode to work out in your head how to solve the problem before any coding. Get one function working first (e.g. getting user input into 2-d array) before moving onto the next function.

Good luck!

hmm, let's C:twisted:

void userInput (int matrix[R_SIZE][C_SIZE], int row, int  col)  //gathering user input
{ 
     /*You are using a for loop in main().This function just accepts input for a paticular row and column*/
     /* This is the trouble >>
        scanf("%d", &matrix[R_SIZE][C_SIZE]);
  Here is the major problem.This should have resulted in a crash or seg - fault after a few runs owing to
 "array index out of bounds".
you specified that row < R_SIZE
Should be 
*/
 scanf("%d", &matrix[row][col]);


}

void displayArray(int matrix[R_SIZE][C_SIZE], int row, int col)  //displaying the Matrix
{
 /*Same here        
        printf("%d)", matrix[R_SIZE][C_SIZE]);
*/        
printf("%d)", matrix[row][col]);

}

int sumArray(int sum)  //summing the matrix
{
    int row, col, sum;    
     for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
        sum += matrix[row][col]; 
        
        return sum;
}
    

int main(void)
{
    int row, col, sum = 0;
    int array[R_SIZE][C_SIZE];
    
    //UI Header
    printf("Please enter enter data for a 5 by 5 array:\n");
    
    //Gather User Input
    for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
            
{
      userInput(array, row, col);
}
     
    
    //Display User Input
    printf("\n\n\nOur Array to sum is:\n");
    for (row = 0; row < R_SIZE; row++)
        for (col = 0; col < C_SIZE; col++)
            
{
      displayArray(array, row, col);
      printf("\n");
   
}

printf("The sum of our array is: %d", sumArray(sum));
  
    /*system("PAUSE"); Hey don't use this .*/
    getchar(); /*or its equivalent loop which eats characters until
       \n is encountered*/
    return 0;
}

Actually the reason why its stopping even after you entered 25 elements is that it actually expects 625 elements. Going by your 'original 'user input function.I changed just the names of the function parameters to row and col in both user input and output functions.

I still think the OP's better option is to keep main() simple and let the other functions (as prescribed in the assignment) do "the work". Use the main code in my previous post as a template.

@RobBrown
Here's a heads up for the function that would prompt the user for input and load the array.

void createArray(int arr2D[][COLSIZE]) {

    int row = 0, col = 0;

    printf("Please enter the data for our %d by %d array:\n", ROWSIZE, COLSIZE);
    for (row = 0; row < ROWSIZE; row++) {
        for (col = 0; col < COLSIZE; col++) {
            scanf("%d", &arr2D[row][col]);
        }
    }
}

I would suggest adding another line of code (via printf) to instruct the user of the program to enter COLSIZE integers each separated by a space and then pressing ENTER. That way you get a row of input at a time.

Using the above code as a template it should be a relatively straightforward exercise to code the "print array " and "sum array" functions.

A little hint for the "print array " function: you need to check when to print a newline character so that your output matches the requirement specified in the assignment (i.e. printing 5 integers per line of output). You can do this using modulo arithmetic (via the % operator).

Cheers,
JD

I'm still having a hard time with the create array function. I use this code:

void createArray(int arr2D[][C_SIZE])
{
   int row = 0, col = 0;
   
   printf("Please enter the data for our %d by %d array:\n", R_SIZE, C_SIZE);
   
      for (row = 0; row < R_SIZE; row++) 
{
   
      for (col = 0; col < C_SIZE; col++) 
{
   
      scanf("%d", &arr2D[row][col]);
   
}
  
}

}

the scanf function is still waiting for more than 25 variables, i am not sure what in my code is causing this too happen...

Any suggestions?

Okay...so i think i got the create array function to work, however now i am having problems with display array, when i run the program this is the output i get:

Please enter the data for our 5 by 5 array:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
This is our array to sum:
1999478136This is our array to sum:
1106490466This is our array to sum:
0This is our array to sum:
0This is our array to sum:
2761080This is our array to sum:
922545558This is our array to sum:
-2This is our array to sum:
1999480563This is our array to sum:
1999480635This is our array to sum:
2293460This is our array to sum:
2This is our array to sum:
2293700This is our array to sum:
1999578293This is our array to sum:
922539758This is our array to sum:
-2This is our array to sum:
1999478136This is our array to sum:
1999559854This is our array to sum:
8982408This is our array to sum:
8982128This is our array to sum:
2293560This is our array to sum:
1999559657This is our array to sum:
0This is our array to sum:
0This is our array to sum:
2293616This is our array to sum:
272Press any key to continue . . .

this is the code i am using for this garbage:

#include <stdio.h>
#include <stdlib.h>

#define R_SIZE 5
#define C_SIZE 5


void createArray(int arr2D[][C_SIZE])
{
   int row = 0, col = 0;
   
   printf("Please enter the data for our %d by %d array:\n", R_SIZE, C_SIZE);
   
      for (row = 0; row < R_SIZE; row++) 
{
   
      for (col = 0; col < C_SIZE; col++) 
{
   
      scanf("%d", &arr2D[R_SIZE][C_SIZE]);
   
}
  
}

}

void displayArray(int arr2D[][C_SIZE])  //displaying the Matrix
{
     int row = 0, col = 0;
     
     for (row = 0; row < R_SIZE; row++)
{
        for (col = 0; col < C_SIZE; col++)
{  
        printf("This is our array to sum:\n");
        printf("%d", arr2D[row][col]);
}

}

}

    

int main(void)
{
    int arr2D[R_SIZE][C_SIZE];
    
    createArray(arr2D);
    displayArray(arr2D);
    
    
    system("PAUSE");
    return 0;
}

any help is much appreciated...

Okay... Plan out your function first!
Look at your scanf in createArray(). What element are you writting to (over and over again)?

Look at your displayArray(). Why do you need to print "This is our array to sum:" over and over again? Take it out of the loop. Also note your number will not be formatted when you print them. You want to print a space after each number, and a '\n' after each for 'col' loop.

Good luck.

is this closer to what you mean (below), ive never worked with functions in this matter before and dont have many examples to go off so i'm not exactly sure how they are supposed to work.

void createArray(int arr2D[R_SIZE][C_SIZE])
{
   int row = 0, col = 0;
   
   printf("Please enter the data for our %d by %d array:\n", R_SIZE, C_SIZE);
   
      for (row = 0; row < R_SIZE; row++) 
{
   
      for (col = 0; col < C_SIZE; col++) 
{
      scanf("%d", &arr2D[row][col]);
   
}
  
}
     
}

void displayArray(int arr2D[R_SIZE][C_SIZE])  //displaying the Matrix
{
      int row = 0, col = 0;
      
      printf("\nThis is our array to sum:\n");
        
     for (row = 0; row < R_SIZE; row++)
{
          for (col = 0; col < C_SIZE; col++)
{
        printf("\n%d %d %d %d %d", arr2D[row][col]);
        printf("\n");
}

}
        
}

Yes, createArray() look's fine.

In displayArray(), use printf("%d ", arr2D[row][col]); and get rid of the other printf("\n"). The output should look something like this now: 1 2 3 4 5 1 2 3 4...

Next, you need to print a newline after each of your for 'col' loop:

for (col = 0; col < C_SIZE; col++) {
  /* What ever... */
}
printf("\n");

That should display your output like:
1 2 3 4 5
1 2 3 4 5
...
After that displayArray() should be fine.

When i change the code it still prints them out in 1 column like:

1
2
3
4
5
1
2
3
4
5
.
.
.
.

void displayArray(int arr2D[R_SIZE][C_SIZE])  //displaying the Matrix
{
      int row = 0, col = 0;
      
      printf("\nThis is our array to sum:\n");
        
     for (row = 0; row < R_SIZE; row++)
     
          for (col = 0; col < C_SIZE; col++)
{
        printf("\n%d", arr2D[row][col]);
        
}

        printf("\n");
        
}

this is why i'm so confused, i dont know what is wrong in my function to cause this.

Sorry, i was missing a { in my code, it works fine now. now i'm onto a sum function...wish me luck!

Got entire program running great now! Once again thanks to all that helped, sorry if i seem to be slow i'ts all really starting to click now though. Thanks again!!

Are you sure that R_SIZE and C_SIZE are each defined as 5?

The code is basically identical to the code I posted in my previous message.

Just to make sure there wasn't anything quirky with your code, I copied it and compiled it and it works fine. It takes input for exactly 25 integers.

For your intital test, are you just testing this function - i.e. one function call from main? If so, then the program should terminate after receiving 25 integers.

Don't take this the wrong way - but are you pressing ENTER?

For example I provide input like this (it can be done other ways):

1 2 3 4 5<ENTER>
5 4 3 2 1<ENTER>
6 7 8 9 1<ENTER>
9 8 7 6 5 <ENTER>
3 5 7 9 1<ENTER>
... program terminates.

Cheers,
JD

Please ignore my previous post - didn't realise there was a page 2 to this thread and was answering your query from the last post on page 1.

My apologies - long day - brain fade.
Glad you got it sorted.

this progrram is not write it makes so errors

can u add two values using only one variable????

hey yello snow can u add two values using only one variable

commented: You are annoying. You post messages to solved threads and post pointless messages. +0

You just don't get it - do you? You have already revived a 4.5 year old thread that had been solved and here you are again posting pointless messages to a SOLVED thread.

How to print the transpose of a matrix..IN C LANGUAGE.....PLS HELP ME......I WANT ITS CODE

I belive that when you join this discussion board you are advised in that this is not a place to have people do your homework for you it is a place to get help. with that being said you need to write some code that gets you in the general area of what you want before anyo9ne can or will help you. you should probably also start a new thread instead of posting on an old solved thread....the posts in this thread should get you in the ballpark for what you need, it did for me.

it is not my homework but i jus got in mind tat if we can add two matrices than y not find its transpose

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.