Using arrays in C
I have a troubling homework assignment and would like pointers in the correct开发者_C百科 direction.
The task is to develop a C program that accomplishes the following:
- In the
main()
, create an a 2D array named qqqqq that can hold 48 integers (6 rows, 8 columns) - Populate
qqqqq
with randomly generated integer values between 1 and 15. - Calculate the total for each row.
- Calculate the total for each column.
- Display the contents of the 2D array in tabular format with the row totals to the right of the rows and the column totals at the bottom of the columns.
Where to start after main
?
Here is what I have so far:
int main (void)
{
int qqqqq [6] [8];
int r;
int c;
srandom ((unsiged) time (NULL));
for (r=0; r <=6; r++)
{
for(c=0; c <=8; c++)
{
qqqqq[r][c] = random ( )
What do I do next?
I appreciate any help or guidance.
Thanks -James
Algorithmic Thinking
Here is how I would tackle this problem:
- Write the algorithm in my own words.
- Find out how to generate random numbers in the C language.
- Learn how to print information on the screen.
Algorithm
The algorithm is the set of steps you need to solve the problem. The task at hand already describes the problem, but it is often good practice to re-write it in your own words. (As a practical point, you can then take your words to your client -- in this case, your teacher -- and confirm that your understanding of the problem is correct.)
- Create a 2D array
- Populate the array with random numbers.
- Calculate the sum of each row of numbers (need a row sum counter).
- Calculate the sum of each column of numbers (need a column sum counter).
- Print the 2D array to the screen.
- Print the sum of each row at the end of each row.
- Print the sum of each column at the end of each column.
Assumption: Neither sum of sums are printed. (For example, the sum of the column sum.)
Generate Random Numbers
Google is helpful here. Try a Google search for:
generate random integers C
You will find lots of help, especially tips about the rand()
function. Modify the Google search:
generate random integers C rand()
This search finds a great resource: http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Print Information
Again, a Google search can help here:
print information on the screen in C
This yields: http://www.daniweb.com/software-development/c/threads/9688
The printf
function seems handy. Find out more about it:
printf C
This yields a familiar site: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Development
If you really want to "wow" your professor:
- Identify the parts of your program that are most likely to change and make them constants.
- Separate your program into logical areas (called functions).
- Use meaningful variable names. Yes
r
andc
likely represent rows and columns, but for the amount of time it takes to spell outrow
andcolumn
, it will save anyone reading your code from having to either make a guess or read the code to discover its true use. - Tell your professor that
qqqqq
could use a better name. Suggest one, even.
For example:
#include <stdio.h>
/* Subject to change; only change it in one spot. */
#define MAX_ROWS 6
#define MAX_COLS 8
#define MIN_RANDOM_NUMBER 1
#define MAX_RANDOM_NUMBER 15
/** Returns a number between MIN_RANDOM_NUMBER and MAX_RANDOM_NUMBER. */
int randomNumber() {
return 0; /* FIX ME to use rand() and the modulus operator. */
}
int main( int argc, char *argv[] ) {
int qqqqq[MAX_ROWS][MAX_COLS];
/* FIX ME: Move these variables into the display function. */
int sumRows = 0;
int sumCols = 0;
/* Use different random numbers each time the program runs. */
seedRandomNumber();
/* Initialize the array with random numbers. */
for( int row = 0; row < MAX_ROWS; row++ ) {
for( int col = 0; col < MAX_COLS; col++ ) {
qqqqq[row][col] = randomNumber();
}
}
/* Display the array to the screen along with the sum totals. */
display( qqqqq );
}
Note that you have a choice to make.
You could pass the sumRows
variable into the display
function, or you could code the display
function to call calculateSumRows
itself. My preference is to always simplify the function prototypes. That is, reduce the number of parameters. It makes things easier to change in the future.
So write display
as something like:
void display( int randomValues[MAX_ROWS][MAX_COLS] ) {
int sumCols = 0;
for( int row = 0; row < MAX_ROWS; row++ ) {
/* FIX ME: Write the calculateSumCols function. */
sumCols = calculateSumCols( randomValues, row );
for( int col = 0; col < MAX_COLS; col++ ) {
/* FIX ME: Use printf here to display the value at this row/column. */
}
}
/* FIX ME: Use printf here to display sumRows. */
for( int col = 0; col < MAX_COLS; col++ ) {
/* FIX ME: Use printf here to display the value of the rows. */
printf( "%d ", calculateSumRows( randomValues, col ) );
}
}
That should get you started.
Note that there are a number of simplifications and optimizations you could make here. Forget them. Get the code so that it actually works first. Once the code works, save it. Make a back up copy, even.
Then start to change it. See if you can remove variables. Perhaps you can even remove some of the for
loops. If you make a mistake, you can always reference your back up copy. Eventually your "back up" copy will become a "source code repository".
That's a pretty good start! Note, though, that the valid indices for an arrayof dimension X are 0...(X-1). Your loops should look like
for (r=0; r <6; r++)
(Note that "<6" rather than "<=6".
Now you need another array to hold the row totals, and an array to hold the column totals, and then some more loops to calculate those and store them in the arrays.
Some key things:
- What does random() return?
- What is the total of a row/column? This is just adding up all the numbers in the row/column. Try writing a function to add up all the values in one given row or column.
- Think of how to print out a row of a matrix. Then do this for every row in the matrix.
There are 6 rows and 8 columns, and you need a total for each of those. Start by making some more arrays as places to store those totals.
精彩评论