Problems displaying max & min values in 2D array - c

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.

Related

Input multiple values to multidimensional array C

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.

C - Entering values for 2d Array using for loop produces different values than entered

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).

C language. How to find the maximum minimum. (2D arrays)

I have written code that allows you to enter one dimension of a NxN double array. It will then print random numbers in a 2D array and it finds the maximum and minimum number of each row. It then prints them and their coordinates (row and column).
ATTENTION!!!!
I have altered my code in such a way that it finds the minimum number of the maximum. I now don't know how to find it's coordinates
My code is as follows:
int N, i, j, min=1000, max, m , o;
time_t t;
int masyvas[100][100], minmax[100];
printf("Enter one dimension of a NxN array\n");
scanf("%d", &N);
srand((unsigned) time(&t));
for (i=0; i<N; i++)
{
for (j=0; j<N; j++)
{
masyvas[i][j] = rand() % 10;
printf("%4d", masyvas[i][j]);
}
printf("\n");
}
int k, l, idkeymax, idkeymin;
for(k=0; k<N; k++)
{
max=-1000;
for(l=0; l<N; l++)
{
if(max<masyvas[k][l])
{
max=masyvas[k][l];
}
}
minmax[k]=max;
}
for(m=0; m<N; m++)
{if(minmax[m]<min)
min=minmax[m];
}
printf("maziausias skaicius tarp didziausiu yra %d eiluteje %d stulpelyje %d\n",min);
Here's the pseudo code of what you need to do.
for row in grid {
row_max = max_in_row(row)
grid_min = min(grid_min, row_max)
}
Step one is to write a routine that finds the max and location in a list. You could do this as one big function, but it's much easier to understand and debug in pieces.
You also need the index where it was found. Since C can't return multiple values, we'll need a struct to store the number/index pair. Any time you make a struct, make routines to create and destroy it. It might seem like overkill for something as trivial as this, but it will make your code much easier to understand and debug.
typedef struct {
int num;
size_t idx;
} Int_Location_t;
static Int_Location_t* Int_Location_new() {
return calloc(1, sizeof(Int_Location_t));
}
static void Int_Location_destroy( Int_Location_t* loc ) {
free(loc);
}
Now we can make a little function that finds the max number and position in a row.
static Int_Location_t* max_in_row(int *row, size_t num_rows) {
Int_Location_t *loc = Int_Location_new();
/* Start with the first element as the max */
loc->num = row[0];
loc->idx = 0;
/* Compare starting with the second element */
for( size_t i = 1; i < num_rows; i++ ) {
if( row[i] > loc->num ) {
loc->num = row[i];
loc->idx = i;
}
}
return loc;
}
Rather than starting with some arbitrary max or min, I've used an alternative technique where I set the max to be the first element and then start checking from the second one.
Now that I have a function to find the max in a row, I can now loop over it, get the max of each row, and compare it with the minimum for the whole table.
int main() {
int grid[3][3] = {
{10, 12, 15},
{-50, -15, -10},
{1,2,3}
};
int min = INT_MAX;
size_t row = 0;
size_t col = 0;
for( size_t i = 0; i < 3; i++ ) {
Int_Location_t *max = max_in_row(grid[i], 3);
printf("max for row %zu is %d at %zu\n", i, max->num, max->idx);
if( max->num < min ) {
min = max->num;
col = max->idx;
row = i;
}
Int_Location_destroy(max);
}
printf("min for the grid is %d at row %zu, col %zu\n", min, row, col);
}
I used a different technique for initializing the minimum location, because getting the first maximum would require repeating some code in the loop. Instead I set min to the lowest possible integer, INT_MAX from limits.h which is highest possible integers. This allows the code to be used with any range of integers, there are no restrictions. This is a very common technique when working with min/max algorithms.

C factorial Table (1!-5!) Using For Loop

This my first post on here. I'd like to ask about a problem that I am trying to do for homework.
I'm supposed to be constructing a for loop for the "first 5 factorials" and display results as a table. I followed an example in the book, and I have my for loop and my operations set up, but I don't know what to do to produce the loop in the table. Here is my program:
#include <stdio.h>
int main(void) {
//Problem: Display a range for a table from n and n^2, for integers ranging from 1-10.
int n, factorialnumber, i;
printf("TABLE OF FACTORIALS\n");
printf("n n!\n");
printf("--- -----\n");
for (n = 1; n <= 10; n++) {
factorialnumber = factorialnumber * n;
printf("\n %i = %i", factorialnumber, n);
}
return 0;
}
I know the printf here is wrong. What would I type?
BTW, I'm using codeblocks.
The problem is that you didn't initialize the variables (e.g. factorialnumber). If it has an initial value of 6984857 let's say, the whole algorithm would be messed up.
Try this :
#include <stdio.h>
int main(void) {
//Problem: Display a range for a table from n and n^2, for integers ranging from 1-10.
int i, factorialnumber = 1;
int n = 10; // Max number to go through
printf("TABLE OF FACTORIALS\n");
printf("i i!\n");
printf("--- -----\n");
for (i = 1; i <= n; i++) {
factorialnumber *= i;
printf("%d! = %d\n", i, factorialnumber);
}
return 0;
}

How to count how many times values were used in the array C?

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);

Resources