This loop checks the previous element in an array. The question is how can it be avoided to check the arr[0][0]
with its previous element which causes undefined behavior?
Here is the code so far but it has this issue with the the first element being checked with its previous element.
int main()
{
int arr[2][4];
int k, n;
for (k = 0; k < 2; k ) {
for (n = 0; n < 4; n ) {
do {
printf("Provide a number");
scanf("%d", &arr[k][n]);
printf("This is %d in the position[%d][%d]\n", arr[k][n], k, n);
if (n==0) break;
printf("The arr[k][n] is %d and the arr[k][n-1] is %d and n-1 means %d\n", arr[k][n], arr[k][n - 1], n - 1);
} while (arr[k][n] <= arr[k][n - 1]); //Here is the issue
}
}
for (k = 0; k < 2; k ) {
for (n = 0; n < 4; n ) {
printf("%d\n", arr[k][n]);
}
}
}
The issue:
Adding the if (n==0) break;
causes the program to allow adding smaller numbers than the ones inserted so far. While not including this line causes undefined behavior. How can this be fixed?
This is how it works now, which is not correct:
2 3 4 5
2 4 5 6
The printf
statements are only for the purpose of viewing what is going on.
CodePudding user response:
You only check with previous column. That is not related to your break
but due to broken logic.
You could do it like this:
int main()
{
int arr[2][4];
int k, n;
int last_number, new_number;
for (k = 0; k < 2; k ) {
for (n = 0; n < 4; n ) {
do {
printf("Provide a number");
scanf("%d", &new_number);
printf("This is %d in the position[%d][%d]\n", new_number, k, n);
if (n==0 && k == 0)
break; // Don't check for increasing values.
} while (new_number < last_number);
arr[k][n] = new_number;
last_number = new_number;
}
}
for (k = 0; k < 2; k ) {
for (n = 0; n < 4; n ) {
printf("%d\n", arr[k][n]);
}
}
}
CodePudding user response:
Change
while (arr[k][n] <= arr[k][n - 1]);
to
while (n > 0 && arr[k][n] <= arr[k][n - 1]);
This works because && short circuits the test when n == 0 and does not do the second test.
You will also need to fix the print statement.