I have an assignment where I have to make a program that takes in 3 sets of data of 5 values and adds them to a 3 * 5 array. I have already made a program where you type in each individual value, but I would rather want it to take in five values over 3 different inputs.
The code is not finished. I also have to do some operations on the data but I got that covered.
#include <stdio.h>
#include <stdlib.h>
#define THREE 3
#define FIVE 5
void totalArray(int, int, int set_numbers[][FIVE]);
void totalArray(int row, int column, int set_numbers[][FIVE]){
int total, subtotal;
printf("\tThe total of your 3-by-5 array is:\n");
for(row = 0, total = 0; row < THREE; row++){
// for each row, the numbers are summed
for(column = 0, subtotal = 0; column < FIVE; column++){
subtotal += set_numbers[row][column];
printf("%d %d", row, subtotal);
total += subtotal; // Total for entire array
}
}
}
int main(){
// 2D array of 15 numbers declaration
int set_numbers[THREE][FIVE] = {{}, {}, {}};
//counter variables for the loop
int i, j, column, row;
printf("\tYou're given an array which is a 3 by 5 array.\n");
printf("\tYou're going to put in each of the total 15 values.\n");
printf("\t___________________________________________________\n");
printf("\n\t\t\t--ATTENTION--\n");
for(i = 0; i < 3; i++){
for(j = 0; j < 5; j++){
printf("\n\t ******************************************");
printf("\n\t ** Array values have to be integers **");
printf("\n\t ******************************************");
printf("\n\tWhich values do you want in set_numbers[%d][%d]\n", i, j);
scanf("%d", &set_numbers[i][j]);
}
}
totalArray(row, column, set_numbers);
printf("The average of your three sets of numbers are: \n\n");
for(i = 0; i < 3; i++){
for(j = 0; j < 5; j++){
printf("%d", set_numbers[i][j]);
if(j == 4){
printf("\n");
}
}
}
return 0;
}
I should specify, that what i want it to do, is take in sets of data. Something along the lines of
int array[][] = {{}, {}, {}}
First, you should rename the macros THREEto COLUMNS and FIVE to ROWS, because it doesn´t make much sense to name macros after values. Consider, that you might want to change the values later and the understanding of what these macros are meant for is unclear at first sight.
Furthermore i don´t see any reason for declare the separate variables column and row inside of main() if you already have such macros. Please adjust that (You also need to change the declaration of totalArray() respectively).
Than you can incorporate this loop:
for (i = 0; i < COLUMNS; i++)
{
scanf("%d %d %d %d %d", &set_numbers[i][0], &set_numbers[i][1], &set_numbers[i][2], &set_numbers[i][3], &set_numbers[i][4]);
}
And you should really only use the macros, instead of hardcoding the actual values in the program. Consider you need to change the values later, then you need to go through the whole program again and change the according parts (which is relatively easy in your case, but just shouldn´t be). Consider also, you need to change them thereafter back again. That is the reason also, what the macros are meant for.
Related
I have this simple program I am working on in class, it initialized a 3x5 2d Array of integers whose values are inputted for each cell by the user. The program then calls a function which runs through the array with a for loop to display each value, then calls a function which again uses a for loop to double every value, and calls the previous display function to show the array again.
All of this seems to be working, however I am consistently getting odd outputs for certain areas when initializing the values for the 2dArray.
For example: Entering 5 rows of "1, 2, 3" and then calling the display function produces this as output:
1,1,2,
1,2,3,
1,2,3,
1,2,5,
1,2,3
Further more, the doubling function produces further strange results but only in the areas where the output was different from what the user had inputted.
Output of the double function on the array I just posted displays as:
2,4,8
2,4,6
2,4,6
2,4,10,
4,8,6
The only real mathematical operation in the entire program is in the doubling functions, where it runs through a for loop setting the value of "array[j][i] = (array[j][i] = array[j][i] * 2)"
I cannot for the life of me figure out which part of the program I've written would cause the user inputs to change to what has been displayed. Inputting values other than "1,2,3" produces similarly odd results. Anyone have any idea what is wrong here? I feel like it must be a very simple mistake I am missing. Here is my source code:
#include <stdio.h>
#include <stdlib.h>
void displayArray(int array[][4]);
void doubleArray(int array[][4]);
int main() {
int dArray[2][4];
int i, j, k;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
printf("Enter a value for the array at position %d,%d.\n", j, i);
scanf("%d", &dArray[j][i]);
}
}
printf("Displaying your original array...\n");
displayArray(dArray);
printf("Doubling your array...\n");
doubleArray(dArray);
printf("Displaying your doubled array....\n");
displayArray(dArray);
system("pause");
}
void displayArray(int array[][4]){
int i, j;
for(i = 0; i <= 4; i++){
printf("\n");
for(j = 0; j <= 2; j++){
if(j == 2 && i == 4){
printf("%d", array[j][i]);
}
else{
printf("%d,", array[j][i]);
}
//system("pause");
}
}
printf("\n");
}
void doubleArray(int array [][4]){
int i, j;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
array[j][i] = (array[j][i] * 2);
//printf("%d\n", array[j][i]);
}
}
}
It's all in one .c file, and I am using devc++ if that makes any difference.
To calculate the DIMENSIONS of your 2D C arrays you have to count how many columns and how many rows there are. In your examples, it is 3 columns and 5 rows, and those are the values you must enter in your array definition:
int array[3][5]
Then, because C starts indexing with 0 offset, you can referr to the elements of the array using the columns 0 to 2 (that is, 3 columns) and rows 0 to 4 (that is, 5 rows). As other people said, this can be achieved using "lower than the limit" (correct: <3 for the columns, <5 for the rows) instead of "lower or equal than the limit" (incorrect, out of bounds: <=3 for the columns, <=5 for the rows).
I'm trying to write a program that analyzes a (3 x 4) matrix of strings provided by the user. Ultimately, it needs to output the longest string present in the matrix, along with that string's length.
My program seems to read the input correctly, as judged its success in echoing back the input strings, but it does not correctly output the longest word. I'm sure I'm committing some kind of pointer-related error when I pass the value of longest word, but I do not have any idea how to solve it.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 4
#define N 5
#define MAX_DIM 20
void findMAX(char matrice[N][M][MAX_DIM]) {
char maxr;
int index;
int i, j, it;
index = 0;
maxr = *(*(*(matrice+0)+0)+MAX_DIM);
for (i = 0; i < N-1; i++) {
for (j = 0; j < M-1; j++) {
if (index < strlen(matrice[i][j])) {
index = strlen(matrice[i][j]);
// I save the longer line's value
it = i;
// I save the maximum's value
maxr = *(*(*(matrice+i)+j)+MAX_DIM);
}
}
}
printf ("The MAX is: -/%s/- and it's long: -/%d/- \n", maxr, index);
printf ("It is content in the: %d line, which is: \n", it);
for (j = 0; j < N-1; j++) {
printf("%s ", matrice[it][j]);
}
}
void leggi(char matrice[N][M][MAX_DIM]) {
int i, j;
for (i = 0; i < N-1; i++) {
for (j = 0; j < M-1; j++) {
printf ("Insert the element matrix [%d][%d]: ", i, j);
scanf ("%s", matrice[i][j]);
fflush(stdin);
}
}
}
void stampa(char matrice[N][M][MAX_DIM]) {
int i, j;
printf("\n(4 x 3) MATRIX\n");
for (i = 0; i < N-1; i++) {
for (j = 0; j < M-1; j++) {
printf("%s ", matrice[i][j]);
}
printf("\n\n");
}
}
int main(int argc, char *argv[]) {
char matrix[N][M][MAX_DIM]; //Matrix of N*M strings, which are long MAX_DIM
printf("************************************************\n");
printf("** FIND THE LINE WITH THE MAXIMUM ELEMENT **\n");
printf("** IN A (4 x 3) MATRIX **\n");
printf("************************************************\n");
printf ("Matrix Reading & Printing\n");
leggi (matrix);
stampa (matrix);
findMAX(matrix);
return 0;
}
First of all to address some misconceptions conveyed by another answer, consider your 3D array declared as
char matrix[N][M][MAX_DIM];
, where N, M, and MAX_DIM are macros expanding to integer constants.
This is an ordinary array (not a variable-length array).
If you want to pass this array to a function, it is perfectly acceptable to declare the corresponding function parameter exactly the same way as you've declared the array, as indeed you do:
void findMAX(char matrice[N][M][MAX_DIM])
But it is true that what is actually passed is not the array itself, but a pointer to its first element (by which all other elements can also be accessed. In C, multidimensional arrays are arrays of arrays, so the first element of a three-dimensional array is a two-dimensional array. In any case, that function declaration is equivalent to both of these:
void findMAX(char (*matrice)[M][MAX_DIM])
void findMAX(char matrice[][M][MAX_DIM])
Note in particular that the first dimension is not conveyed. Of those three equivalent forms, I find the last clearest in most cases.
It is quite odd, though, the way you access array elements in your findMAX() function. Here is the prototypical example of what you do:
maxr = *(*(*(matrice+i)+j)+MAX_DIM);
But what an ugly and confusing expression that is, especially compared to this guaranteed-equivalent one:
maxr = matrice[i][j][MAX_DIM];
Looking at that however, and it how you are using it, I find that although the assignment is type-correct, you are probably using the wrong type. maxr holds a single char. If you mean it to somehow capture the value of a whole string, then you need to declare it either as an array (into which you will copy strings' contents as needed), or as a pointer that you will set to point to the string of interest. The latter approach is more efficient, and I see nothing to recommend the former for your particular usage.
Thus, I think you want
char *maxr;
... and later ...
maxr = matrice[0][0];
... and ...
maxr = matrice[i][j];
That sort of usage should be familiar to you from, for example, your function stampo(); the primary difference is that now you're assigning the expression to a variable instead of passing it directly to a function.
And it turns out that changing maxr's type that way will correct the real problem here, which #AnttiHaapala already pointed out in comments: this function call ...
printf ("The MAX is: -/%s/- and it's long: -/%d/- \n", maxr, index);
requires the second argument (maxr) to be a pointer to a null-terminated array of char in order to correspond to the %s directive in the format string. Before, you were passing a single char instead, but with this correction you should get mostly the expected result.
You will probably, however, see at least one additional anomaly. You final loop in that function has the wrong bound. You are iterating with j, which is used as an index for the second dimension of your array. That dimension's extent is M, but the loop runs to N - 1.
Finally, I should observe that it's odd that you allocate space for a 5 x 4 array (of char arrays) and then ignore the last row and column. But that's merely wasteful, not wrong.
Try something like this:
void findMAX(char matrice[N][M][MAX_DIM]){
// char maxr
char maxr[MAX_DIM];
int index;
int i, j, it;
index = 0;
// maxr = *(*(*(matrice+0)+0)+MAX_DIM);
strncpy(maxr, *(*(matrice+0)+0), MAX_DIM);
for (i = 0; i < N-1; i++)
{
for (j = 0; j < M-1; j++)
{
if (index < strlen(matrice[i][j]))
{
index = strlen(matrice[i][j]);
it = i;
// maxr = *(*(*(matrice+i)+j)+MAX_DIM);
strncpy(maxr, *(*(matrice+i)+j), MAX_DIM);
}
}
}
printf ("The MAX is: -/%s/- and it's long: -/%d/- \n", maxr, index);
printf ("It is content in the: %d line, which is: \n", it);
// for (j = 0; j < N-1; j++){
for (j = 0; j < M-1; j++){
printf("%s ", matrice[it][j]);
}
}
It's possible to pass multi-dimensional arrays to C functions if the size of the minor dimensions is known at compile time. However the syntax is unacceptable
void foo( int (*array2d)[6] )
Often array dimensions aren't known at compile time and it is necessary to create a flat array and access via
array2D[y*width+x]
Generally it's easier just to use this method even if array dimensions are known.
To clarify in response to a comment, C99 allows passing of variable size arrays using the more intuitive syntax. However the standard isn't supported by Microsoft's Visual C++ compiler, which means that you can't use it for many practical purposes.
Hello I am trying to populate an array with random values between 0 and 10000, display each to the screen with their location then calculate max, min, and average value in addition to thier locations. I am having trouble displaying the results. Can someone please help?
Thank you!
#include <stdio.h>
#include<time.h>
#include<math.h>
int array [3][5];
int practice_array;
int i, row, col, max, min, sum, avg;
srand(time(NULL));
for ( row = 0; row < 2; row = row + 1){
for ( col = 0; col < 4; col = col +1){
array[row][col] = rand()%10000;
practice_array = array[row][col];
sum = array[row][col];
avg = sum / 15;
for(i =0; i< 8; i++){
printf("The value in row %d col %d is %d\n",row, col,practice_array);
}
}
}
for (i = 0; i < 8; i++){
max = array[0];
min = array[0];
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array [i];
}
}
printf("The max value is %d in row %d, col %d\n", max, row,col);
printf("The min value is %d in row %d, col %d \n", min, row,col);
return (0);
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define ROW 3
#define COL 5
int main(){
int array[ROW][COL];
int practice_array;
int i, row, col, max, min, sum, avg;
srand(time(NULL));
for ( row = 0; row < ROW; row = row + 1){
for ( col = 0; col < COL; col = col +1){
array[row][col] = rand()%(10000+1);
practice_array = array[row][col];
sum += practice_array;
printf("The value in row %d col %d is %d\n",row, col,practice_array);
}
}
avg = sum / (ROW*COL);//unused
int *pv = &array[0][0];
max = min = 0;
for (i = 1; i < ROW*COL; ++i){
if (pv[i] > pv[max])
max =i;
if (pv[i] < pv[min])
min = i;
}
printf("The max value is %d in row %d, col %d\n", pv[max], max/COL, max%COL);
printf("The min value is %d in row %d, col %d\n", pv[min], min/COL, min%COL);
return 0;
}
First you should really use defines for constants (array sizes, ...) like I've shown to you on the other thread otherwise your code is mess with magic numbers everywhere (for example in this code: 3, 5, 2, 4, 8, ...). And if you've to change a value, you need to change it everywhere; with a define you change it only once at one place.
Also, when it prints each values & location, they are duplicated 5 times before printing the next value this is because of this (completely useless) loop, just delete it and keep only the printf:
for(i =0; i< 8; i++){
printf("The value in row %d col %d is %d\n",row, col,practice_array);
}
For everything else, as far as I can see, you don't have fully understood how loops are working. I suggest you to learn the basics of the loops before trying to use them with arrays.
Also try to use step wise development by first building an array with simple numbers and printing it out. Then try adding random numbers to a specific location in each array position and so on with 2d stuff. It seems like you wrote down a bunch of code without stepping back and trying to run it a few times
After looking through you code I could see a few things that you still need to work on.
Don't forget all of that needs to be inside of the main method or the compiler will not know where to start. you will also need "#include <stdlib.h>" to get your srand to work.
If you try to find examples online on a simple srand being used, you will see what I mean. The variable sum is not finding the sum. You need to loop though all the locations and add them to the sum. It would then be easy to find the average using your method.
If you are looking to print out all of them, remember to also use that for loop and loop through every single location and print them out.
Here's my problem
If certain number has been entered into an array I need that number to be displayed and occurrence of that number in the array.
for example if user enters number 5 three times then "The number 5 has been entered 3 times so far" and so on
Here's my code so far:
int i,j;
int num_count = 0;
for(i=0;i<6;i++) {
num_count = 0;
for(j=1;j<43;j++) {
if( *(num + i) == j) {
printf("The number %d has been used %d times\n",j,num_count);
}//end if
}//end inner for
}//end outer for
I will like to suggest you a very time efficient method for this, but it needs some extra memory.
Assume the upper limit of numbers inside array is 'MAX_NUM_IN_ARRAY',
so you should create array (say counter) of size 'MAX_NUM_IN_ARRAY+1' and initialize it to 0.
int counter[MAX_NUM_IN_ARRAY+1]={0};
now scan the input array from first to last element,
for each number:
//say number is num
counter[num]++;
and at the end you have to just scan that counter array from index 1 to MAX_NUM_IN_ARRAY.
Sample code:
Suppose input array is a[],
number of elements in array is n,
maximum limit of number inside array is MAX_LIMIT
int counter[MAX_LIMIT]={0};
int i;
for(i=0; i<n; i++)
{
counter[a[i]]++;
}
for(i=0; i<MAX_LIMIT; i++)
{
printf("Number %d is appeared for %d times\n", i, counter[i]);
}
============EDIT
You could write a series of functions that handle your collection. the collection could be a 2 dimentional array like so numbers[][] where numbers[n][0] is your number, and numbers[n][1] is the number of times it occurred... and the gold would be in your add() function
add() does a few things, a user passes a value to add(),
first checks if number exists in numbers[n][0]
if the value exists at numbers[n][0]
numbers[n][1]++;
if it doesn't already exist,
check if the array is full
if it is full, copy all the data to a new, larger array
add it to the end of the array.. this is how to do it.
==OR
just design a 1 dimentional array numbers[] that holds all of your numbers.. and the add() function only:
if(it is full){copies to larger array}
adds number to the end;
and modify the code I wrote earlier (Below).. to print the most common number and it's occurrence count
============EDIT
I'm a Java guy so you'll need to translate (shouldn't be too hard..)
This is going to be just like a sorting algorithm with a little bit of extra logic (later search for Selection Sort)
int[] temp = {4,3,2,4,4,5};
////// find the most commonly occuring value
int times;
int moreTimes = 1;
int value = temp[0];
for(int i = 0; i < temp.length; i++) {
times = 1;
for(int j = i+1; j < temp.length; j++) {
if(temp[i] == temp[j])
times++;
}
if(times > moreTimes) {
moreTimes = times;
value = temp[i];
}
}
/////// count the most common value
int count = 0;
for(int i = 0; i < temp.length; i++) {
if(temp[i] == value)
count++;
}
System.out.println("number: " + value + ", count: " + count);
The program should create a 2D table 8*8 which consists o random number<3
it should print that table.
Another task is to translate this table into another
For Example
120
210
111
The number in the center should be changed to the sum of all numbers around it 1+2+0+2+0+1+1+1=8
and that should be done for everything;
then the program should be printed
if there are any numbers larger than 9 it shoul be translated to hexadecimal.....
I didn't do the hexadecimal yet. but it is still not working ....
#include <stdio.h>
#include <stdlib.h>
#define cols 8
#define rows 8
void printA(int A[][cols]);
void printC(char C[][cols]);
void SumThemUp(int A[][cols], char C[][cols]);
int main()
{
srand(time(NULL));
int A[rows][cols];
char C[rows][cols];
int i, j;
for(i=0; i<rows; i++)
for(j=0; j<cols; j++)
A[i][j]=rand()%3;
printA(A);
SumThemUp(A,C);
printC(C);
return 0;
}
void printA(int A[][cols])
{ int i, j;
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
{printf("%d ", A[i][j]);}
printf("\n");}
return ;
}
void printC(char C[][cols])
{
int i, j;
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
{printf("%ch ", C[i][j]);}
printf("\n");}
return ;
}
void SumThemUp(int A[][cols], char C[][cols])
{
int i,j;
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
C[i][j]=0;}
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
A[i][j]=C[i++][j];
}
for(j=0;j<cols; j++)
{for(i=0;i<rows;i++)
C[i][j]+=A[i][j++];
}return;
}
So - I'm not entirely sure I know what you want the output to be -- but there are several problems with what you have:
0: For your arrays, the names should describe what the array actually holds, A and C are quite ambiguous.
1: Use { } for scoping, and put the { } on their own lines. (Maybe it just pasted poorly in Stack Overflow)
2: You have a set of loops which basically sets everything in C to 0:
for(i=0;i<rows;i++)
{
for(j=0;j<cols; j++)
{
C[i][j]=0;
}
}
Then immediately after that you have:
for(i=0;i<rows;i++)
{
for(j=0;j<cols; j++)
{
A[i][j]=C[i++][j]; // <--- problem here
}
}
So after that, both A and C are full of all 0s. On top of that, you have i++ inline when accessing columns in C. This actually changes the value that your for loop is using, so i is getting incremented for every row and every column. Presumably you want:
A[i][j]=C[i+1][j];
3: You have a similar problem here:
for(j=0;j<cols; j++)
{
for(i=0;i<rows;i++)
{
C[i][j]+=A[i][j++]; // Presumably you want j+1
}
}
4: Why are you using a char array for C? If it's holding the sum of integers it should probably be declared int. If this was your idea of printing the ints as hex (or just plain ints), it would be easier to simply use printf to output the ints as hex:
// use %d to print the integer "normally" (base 10)
// use %x if you want a hex value with lowercase letters
// use %X if you want a hex value with capital letters
printf("125 as hex is: 0x%x", 125); // 0x7d
I hope that points you in the right direction.
-- Dan
Do I understand correctly, that given matrix A, you want to get matrix C in SumThemUp, where each cell in C is a sum of its adjacent cells? In that case, these lines look suspicious as you modify the loop counters
A[i][j]=C[i++][j];
and
C[i][j]+=A[i][j++];
.
Anyway, a simple example, how I would do the summing part.
NB! Note that I use int type for matrix C. Given that you want to convert it to hex and you happend to have values 3 in all adjacent cells somewhere, you get decimal value of 3 * 8 = 24, which requires more than one character to represent. Thus, you should convert to hex during printing. (I understand that char can contain intergral values up to 255 also, but for the sake of consistency)
void SumThemUp(int A[][cols], int C[][cols]) {
int i, j, di, dj, i2, j2;
// iterate through all the rows
for (i=0 ; i<rows ; ++i) {
for (j=0 ; j<cols ; ++j) {
// initialize the cell to zero
C[i][j] = 0;
// iterate over nearby cells
for (di=-1 ; di<=1 ; ++di) {
for (dj=-1 ; dj<=1 ; ++dj) {
// do not count in the center
if (di == 0 && dj == 0) {
continue;
}
// make sure, we do not try to count in cells
// outside the matrix
i2 = i + di;
j2 = j + di;
if (i2 < 0 || j2 < 0 || i2 >= rows || j2 >= cols) {
continue;
}
// append the score here
C[i][j] += A[i2][j2];
}
}
}
}
}
Also, I did not test this code, so it may contain mistakes, but maybe it helps you finishing your summing part.
NB! And take note of comments of #Dan.