Reputation: 21
User is asked to give a number of rows and columns to fill an array of 10x10 array with random numbers.(A part of the table will be filled e.g 2x2). Then a function called printArray will print its values.Then,function change_array will find in every row the biggest value and replace the elements left of it with the value.
For instance:
Initial Array
<p>41 67 34 0 </p>
<p>69 24 78 58</p>
<p>62 64 5 45</p>
changed Array
<p>67 67 34 0 </p>
<p>78 78 78 58 </p>
<p>64 64 5 45 </p>
However,the program gives this:
Initial Array
<p>41 67</p> <p>34 0</p>
Changed Array
<p>67 67</p>
<p>24576000 508</p>
Why is this happening?
The modified array must be printed in main()
#include <stdio.h>
#include <stdlib.h>
#include "simpio.h"
void populate_data(int R, int C, int A[R] [C]);
void printArray(int R, int C, int A[R] [C]);
void change_array(int R, int C, int A[R] [C]);
int main(void)
{
int A[10] [10],R,C,i,j;
while (TRUE)
{
printf("Give the number of rows: ");
R = GetInteger();
if (R>=0 && R<=10)
break;
else
{
printf("Wrong Answer\n");
}
}
while (TRUE)
{
printf("Enter the number of columns: ");
C = GetInteger();
if (C>=0 && C<=10)
break;
else
{
printf("Wrong Answer\n");
}
}
populate_data(R,C,A);
printf("Initial Array\n");
printArray(R,C,A);
change_array(R,C,A);
printf("Changed Array\n");
for (i=0; i<R; i++)
{
for (j=0; j<C; j++)
{
printf("%d ",A[i] [j]);
}
printf("\n");
}
return 0;
}
void populate_data(int R, int C, int A[R] [C])
{
int i,j;
for (i=0; i<R; i++)
{
for (j=0; j<C; j++)
{
A[i] [j] = rand() % 100;
}
}
}
void printArray(int R, int C, int A[R] [C])
{
int i,j;
for (i=0; i<R; i++)
{
for (j=0; j<C; j++)
{
printf("%-3d ",A[i] [j]);
}
printf("\n");
}
}
void change_array(int R, int C, int A[R] [C])
{
int i, j, max[R], m[R];
for (i=0; i<R; i++)
{
max[i] = A[i] [0];
for (j=0; j<C; j++)
{
if (max[i]< A[i] [j])
{
max[i] =A[i] [j];
m[i] = j;
}
}
}
for (i=0; i<R; i++)
{
for (j=0; j<C; j++)
{
if (j<m[i])
A[i] [j] = max [i];
}
}
}
Upvotes: 1
Views: 83
Reputation: 155
This happens if the max value in a row is on first position, so you will never enter this block
if (max[i]< A[i] [j])
{
max[i] =A[i] [j];
m[i] = j;
}
and m[i]
will stay uninitialized. Just add a
m[i] = 0;
before that loop.
Edit:
You must change your function definitions from A[R][C]
to A[10][10]
, because R and C are unknown to the function at that point.
Also, there is no reason to declare the array with size 10x10. You can do that after you got the dimension from input with the correct number of rows and columns.
Upvotes: 2