| | |
2d Array problems
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
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:
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:
•
•
•
•
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 . . .
Here is my "sure to be flawed" code:
C Syntax (Toggle Plain Text)
#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; }
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:
Here is what i have:
C Syntax (Toggle Plain Text)
#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?
C Syntax (Toggle Plain Text)
#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:
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!
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:
C Syntax (Toggle Plain Text)
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!
Manic twiddler of bits
•
•
Join Date: Oct 2008
Posts: 44
Reputation:
Solved Threads: 11
hmm, let's C
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.
c Syntax (Toggle Plain Text)
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; }
Last edited by zalezog; Aug 2nd, 2009 at 5:34 am.
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.
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
@RobBrown
Here's a heads up for the function that would prompt the user for input and load the array.
C Syntax (Toggle Plain Text)
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
Last edited by yellowSnow; Aug 2nd, 2009 at 6:24 am.
Manic twiddler of bits
I'm still having a hard time with the create array function. I use this code:
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?
C Syntax (Toggle Plain Text)
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?
![]() |
Similar Threads
- Array problems (C++)
- Array problems (C++)
- array problems (C++)
- Problem installing XP on a SATA Striping Array (Storage)
- error 88:'(' expected when trying to display an array any help (Pascal and Delphi)
Other Threads in the C Forum
- Previous Thread: GTK problem
- Next Thread: help with the IF- THEN -ELSE statement for my code please
| Thread Tools | Search this Thread |
#include * ansi append array arrays asterisks binarysearch calculate changingto char character cm convert copyimagefile cprogramme creafecopyofanytypeoffileinc database dynamic execv feet fflush fgets file fork forloop framework function getlasterror givemetehcodez grade gtkwinlinux hacking hardware histogram inches include incrementoperators input intmain() iso kernel keyboard km license linked linkedlist linux list lists locate logical_drives looping loopinsideloop. lowest matrix microsoft motherboard mqqueue number oddnumber odf opendocumentformat opensource overwrite owf pattern pdf performance pointer posix probleminc process program programming radix recursion recv recvblocked research reversing scanf scripting segmentationfault sequential socket socketprograming standard string systemcall testing threads turboc unix user variable voidmain() wab whythiscodecausesegmentationfault windowsapi





