I have a two-dimensional array of integers and i want to accept only values that are different from those that were already read. I tried to do it this way:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("Number: ");
scanf("%d", &d[i][j]);
for (k = 0; k < i; k++)
{
for (l = 0; l < j; l++)
{
while (d[i][j] == d[k][l])
{
printf("Number: ");
scanf("%d", &d[i][j]);
}
}
}
}
}
Turns out it doesn't work correctly. How can i make this validation work?
The while statement shouldn't be in the inner loop, because it is only validating against that particular k, l and not against the other indices.
Split out your test into a separate function to test for a duplicate up to i,j:
int duplicateExists(float value, int i, int j)
{
for (k = 0; k <= i; k++)
{
for (l = 0; ((k < i) && (l < 5)) || (l < j); l++)
{
if(d[k][l] == value)
return 1;
}
}
return 0;
}
Then you can validate like this:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf ("Number: ");
scanf ("%d", &d[i][j]);
while (duplicateExists(d[i][j], i, j))
{
printf ("Number: ");
scanf ("%d", &d[i][j]);
}
}
}
The problem is that you are not checking every previously entered value.
So when i == 2 and j == 3, values have been inputted into d[0][0 through 4], d[1][0 through 4], and d[2][0 through 2]. However, because of your for (l = 0; l < j; l++), you are checking d[0][0 through 2], d[1][0 through 2], and d[2][0 through 2].
Let's say your code has reached the inner loop, with some value of i and j.
The "validation" needs to compare d[i][j] against the following sets of values
set1: for k = 0 to i-1 compare with d[k][l] for l = 0 to 5
set2: compare with d[i][l] for l = 0 to j-1
Essentially set1 is about comparing all the rows previously read, and set2 is comparing all preceding elements in the current row.
Your two nested loops are not comparing against the combination/union of those two sets.
Note: it is not a particularly good idea to name a variable l, since it looks like a 1 (numeral one) and it is easy to make typos that are hard to see, but really screw up the meaning of your code.
You should try to change your code like this. Put an 'if', so you can see if the number you wrote is the same, of course you should change my code, but this is the base of the logic.
printf("Number: ");
scanf ("%d", &numb);
for (k = 0; k < i; k++)
{
for (l = 0; l < j; l++)
{
if (numb == d[k][j])
{
printf("Same number, try again\n");
}
else
{
d[i][j] = numb;
}
}
You have missed some of the previous entries because you didn't check the whole of each previous row, and didn't check any of the current row.
int had;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
do
{
had = 0;
printf ("Number: ");
scanf ("%d", &d[i][j]);
// check previous rows
for (k = 0; k < i; k++)
{
for (l = 0; l < 5; l++) // <--- change end condition
{
if (d[i][j] == d[k][l])
{
had = 1;
continue;
}
}
}
//check this row
for (l = 0; l < j; l++)
{
if (d[i][j] == d[i][l])
{
had = 1;
continue;
}
}
} while (had);
}
}
It will benefit you if you break the task down into a couple of functions as indicated by others. This does away with, at minimum, 4 independent iteration variables for the indexes in the nested loop. After you have your initial array, then your primary goal is to iterate over each value in your original and verify that the new value you are attempting to add to the second doesn't exist in the first.
Take for example an existing array and an empty second array (a and b below):
int a[][ASZ] = {{19, 1,38,51,37},
{95,74,42,23,76},
{17,24,14,22,25},
{11,50,10,84,45},
{78,44,66,46,98}};
int b[ASZ][ASZ] = {{0}};
(Note: any significantly large array, iterating over every value for every addition to the second is very inefficient. To improve the efficient, it would make sense to sort the original (even in a temp array) allowing a bisection/bracketing type search to dramatically cut down on the iterations needed to check for duplicate values)
Checking for duplicates, in its simplest sense could be an integer function taking the original array and the proposed value as arguments (along with the array size) and then comparing the values, returning 1 or 0 for unique or non-unique determinations. Something like the following:
int check_uniq (int a[][ASZ], size_t n, int v)
{
size_t i, j;
for (i = 0; i < n; i++)
for (j = 0; j < ASZ; j++)
if (a[i][j] == v)
return 0;
return 1;
}
(where: ASZ is simply a constant for the row-size of the array)
With a way to check for unique values, filling the array reduces to your basic approach:
/* fill second array with values unique to values in a[][] */
for (i = 0; i < n; i++) {
for (j = 0; j < ASZ; j++) {
for (;;) {
tmp = rand() % 100 + 1;
if (check_uniq (a, n, tmp))
break;
}
b[i][j] = tmp;
}
}
(note: you can use any type of internal loop you prefer. for, while, or do .. while. A simple continual iteration with a break after a unique value is found is as simple as anything else).
Lastly, testing. Rather than having to type proposed values over and over during testing, sometimes it makes sense to set up a simple way to fill the second array with random numbers to allow thorough validation. The following is a short example putting all the pieces together. Hopefully this will help. Let me know if you have any questions:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ASZ 5
int check_uniq (int a[][ASZ], size_t n, int v);
void prn_array (int a[][ASZ], size_t n);
void prn_array_1d (int a[][ASZ], size_t n);
void quick_sort (int *a, size_t n);
int main (void) {
int a[][ASZ] = {{19, 1,38,51,37},
{95,74,42,23,76},
{17,24,14,22,25},
{11,50,10,84,45},
{78,44,66,46,98}};
int b[ASZ][ASZ] = {{0}};
int tmp = 0;
size_t i, j;
const size_t n = sizeof a/sizeof *a;
srand (time (NULL));
/* fill second array with values unique to values in a[][] */
for (i = 0; i < n; i++) {
for (j = 0; j < ASZ; j++) {
for (;;) {
tmp = rand() % 100 + 1;
if (check_uniq (a, n, tmp))
break;
}
b[i][j] = tmp;
}
}
printf ("\n the original array is:\n\n");
prn_array (a, n);
printf ("\n the second array with unique values is:\n\n");
prn_array (b, n);
printf ("\n comparison in sorted 1D array format (easier to check):\n\n");
prn_array_1d (a, n);
printf ("\n");
prn_array_1d (b, n);
printf ("\n\n");
return 0;
}
int check_uniq (int a[][ASZ], size_t n, int v)
{
size_t i, j;
for (i = 0; i < n; i++)
for (j = 0; j < ASZ; j++)
if (a[i][j] == v)
return 0;
return 1;
}
void prn_array (int a[][ASZ], size_t n)
{
size_t i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < ASZ; j++)
printf (" %3d", a[i][j]);
printf ("\n");
}
}
void prn_array_1d (int a[][ASZ], size_t n)
{
size_t i, j;
int tmp [n * ASZ];
for (i = 0; i < n; i++)
for (j = 0; j < ASZ; j++)
tmp [i * ASZ + j] = a[i][j];
quick_sort (tmp, n * ASZ);
for (i = 0; i < n * ASZ; i++)
printf (" %3d", tmp[i]);
}
void quick_sort (int *a, size_t n)
{
int pvt, tmp;
size_t i, j;
if (n < 2) return;
pvt = a[n / 2];
for (i = 0, j = n - 1;; i++, j--)
{
while (a[i] < pvt) i++;
while (pvt < a[j]) j--;
if (i >= j)
break;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
quick_sort (a, i);
quick_sort (a + i, n - i);
}
Output
$ ./bin/array_2d_fill_uniq
the original array is:
19 1 38 51 37
95 74 42 23 76
17 24 14 22 25
11 50 10 84 45
78 44 66 46 98
the second array with unique values is:
81 16 34 69 65
87 88 35 67 79
89 43 55 18 12
77 83 93 9 99
34 94 75 2 72
comparison in sorted 1D array format (easier to check):
1 10 11 14 17 19 22 23 24 25 37 38 42 44 45 46 50 51 66 74 76 78 84 95 98
2 9 12 16 18 34 34 35 43 55 65 67 69 72 75 77 79 81 83 87 88 89 93 94 99
Related
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <malloc.h>
#define n 6
void insertarray(int arr[n][n])
{ for(int j = 0; j < n; j++){
if(j==0){
for (int i = 0; i < n; i++){
arr[i][j] = rand()%50;
}
}
if(j==1){
for (int i = 0; i < n; i++){
if(i==0){
arr[i][j] = 0;
}
else if(i==5){
arr[i][j] = 0;
}
else arr[i][j] = rand()%50;
}
}
if(j==2){
for (int i = 0; i < n; i++){
if(i==0 || i==1 || i==4 || i==5){
arr[i][j] = 0;
}
else arr[i][j] = rand()%50;
}
}
if(j==3){
for (int i = 0; i < n; i++){
if(i==0 || i==1 || i==4 || i==5){
arr[i][j] = 0;
}
else arr[i][j] = rand()%50;
}
}
if(j==4){
for (int i = 0; i < n; i++){
if(i==0){
arr[i][j] = 0;
}
else if(i==5){
arr[i][j] = 0;
}
else arr[i][j] = rand()%50;
}
}
if(j==5){
for (int i = 0; i < n; i++){
arr[i][j] = rand()%50;
}
}
}
}
int NewIndex(int x, int y) //пересчет индексов
{ int j=0;
for(int i=0; i<x; i++) j+= n-i;
return j+y-x;
}
void Put(int vec [], int x, int y, int v) // Запись в вектор (сжатие)
{ if (y >=x) vec[NewIndex(x, y)] = v;
}
int Get(int vec [], int x, int y) // Чтение из вектора
{ if (y >=x) return vec[NewIndex(x, y)];
else return 0;
}
void printarray(int a[n][n])
{ for(int i = 0; i < n; i++)
{ for (int j = 0; j < n; j++)
printf("%3i", a[i][j]);
printf("\n");
}
}
int main()
{ int vec[n*n/2+n/2];
int array[n][n];
insertarray(array);
printarray(array);
for(int i = 0; i < n; i++)
for (int j = 0; j <n ; j++)
Put(vec, i, j, array[i][j]); //сжатие массива
for(int i = 0; i < n*n/2+n/2; i++) //выдача результата сжатия
printf("%3i", vec[i]);
printf("\n\n");
for(int i = 0; i < n; i++)
{ for (int j = 0; j < n; j++) //чтение из сжатого представления
printf("%3i", Get(vec,i,j));
printf("\n");
}
return 0;
}
Well, i have a totally working code which firstly made an array which contained the null elements under the main diagonal, compresses it into a vector and then reads from it. But now i have to make an array which contains null elements in two triangles above and under the crossing of diagonal.
it must looking like this
6 0 0 0 0 2
3 1 0 0 4 3
2 9 2 1 5 6
7 8 6 2 4 6
8 7 0 0 2 1
9 0 0 0 0 9
and the first step of making it was succesful: i generate such array, but the problem is that it doesn't compress it normally. it needs to convert all the elements that are not in the triangles but it compresses like it's having null elements only under the main diagonal. the problem with the reading is that it reads the array like the past one but also with the triangle of null element above the crossing. can you help me redoing the code? i've added a picture of running my program
To achieve this pattern, we test that our current column is within the range of our current row relative to either edge, up to our halfway point. We then invert our calculations past there.
Converting a matrix to and from an array is just a matter of iterating through your matrix bounds, writing/reading to/from the array, and advancing your array pointer.
To compress the matrix we need to apply the inverse of our calculations as a filter, storing only non-zero values. Decompressing follows the same logic as our initial fill operation, but sourcing from an array instead.
Note that the size calculation done here:
int vec[n*n/2 + n/2];
Does not create a correctly sized array that for the results (for size 6 this produces 21, when you need at least 24). Take a look at the function non_zero_count below for an accurate calculation for finding the amount of non-zeroes this pattern produces for any given size.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fill_matrix(int sz, int m[sz][sz]) {
for (int i = 0; i < sz; i++) {
for (int j = 0; j < sz; j++) {
if ((i <= sz / 2 && j > i && j < sz - 1 - i) ||
(i > sz / 2 && j > sz - i - 1 && j <= i - 1))
m[i][j] = 0;
else
m[i][j] = rand() % 99 + 1;
}
}
}
void pack_matrix(int *array, int sz, int m[sz][sz]) {
for (int i = 0; i < sz; i++)
for (int j = 0; j < sz; j++)
if (!(i <= sz / 2 && j > i && j < sz - 1 - i) &&
!(i > sz / 2 && j > sz - i - 1 && j <= i - 1))
*array++ = m[i][j];
}
void unpack_matrix(int *array, int sz, int m[sz][sz]) {
for (int i = 0; i < sz; i++) {
for (int j = 0; j < sz; j++) {
if ((i <= sz / 2 && j > i && j < sz - 1 - i) ||
(i > sz / 2 && j > sz - i - 1 && j <= i - 1))
m[i][j] = 0;
else
m[i][j] = *array++;
}
}
}
void print_matrix(int sz, int m[sz][sz]) {
for (int i = 0; i < sz; i++) {
printf("[ ");
for (int j = 0; j < sz; j++)
printf("%02d ", m[i][j]);
printf("]\n");
}
}
int non_zero_count(int n) {
int is_even = n % 2 == 0;
return (n * n) - ((is_even ? n : n - 1) / 2) * (n - (is_even ? 2 : 1));
}
#define MSZ 6
int main(void) {
int matrix[MSZ][MSZ];
int matrix2[MSZ][MSZ];
int array[non_zero_count(MSZ)];
srand(time(NULL));
fill_matrix(MSZ, matrix);
print_matrix(MSZ, matrix);
puts("----");
pack_matrix(array, MSZ, matrix);
unpack_matrix(array, MSZ, matrix2);
print_matrix(MSZ, matrix2);
}
Output:
[ 59 00 00 00 00 79 ]
[ 91 50 00 00 25 37 ]
[ 24 85 19 23 24 25 ]
[ 67 97 54 14 12 34 ]
[ 44 78 00 00 14 01 ]
[ 25 00 00 00 00 12 ]
----
[ 59 00 00 00 00 79 ]
[ 91 50 00 00 25 37 ]
[ 24 85 19 23 24 25 ]
[ 67 97 54 14 12 34 ]
[ 44 78 00 00 14 01 ]
[ 25 00 00 00 00 12 ]
Im currently struggling to implement a insertion sort algorithm for a 2D pointer array.
NO Qsort solutions please, it needs to be old school
Here is my code
void insertionSort(double **arr, int rows,int c)
{
double *temp;
int i, j;
for (i = 1; i < rows; i++) {
temp = *(arr+i);
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j][c] > arr[i][c]) {
int r = j + 1;
*(arr+r) = *(arr+j);
j = j - 1;
}
int t= j + 1;
*(arr+t) = temp;
}
}
heres where i call it(rows = 3, the value 4 says which column to sort according to):
insertionSort(student,rows,4);
It needs to sort every row according to the value in the last column of each row: example : sort by column 3
input
10 11 71
71 25 65
98 42 16
output:
98 42 16
71 25 65
10 11 71\
Any help would be appreciated since this is due this week :)
Presuming arr is an allocated block of pointers where each pointer holds the address of an allocated block of double, you simply need to compare by the last column in each block of double and swap pointers in arr to sort. Your insertionSort() function can be reduced to:
void insertionSort (double **arr, int rows, int cols)
{
for (int i = 0; i < rows; i++) /* insertion sort of a by last col */
for (int j = i; j > 0 && arr[j][cols-1] < arr[j-1][cols-1]; j--) {
double *tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
}
(note: c has been changed to cols)
This will not work with a 2D array. With a 2D array you must save and copy rows instead of pointers with a loop or memcpy(). This all presumes your double **arr is correct and you have allocated pointers and allocated blocks for the double and are now sorting be the last double in each row of arr. An example would be:
#include <stdio.h>
#include <stdlib.h>
void insertionSort (double **arr, int rows, int cols)
{
for (int i = 0; i < rows; i++) /* insertion sort of a by last col */
for (int j = i; j > 0 && arr[j][cols-1] < arr[j-1][cols-1]; j--) {
double *tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
}
void prnrowscols (size_t rows, size_t cols, double **arr)
{
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++)
printf (j ? " %4g" : "%4g", arr[i][j]);
putchar ('\n');
}
}
int main (void) {
double tmp[][3] = { {10, 11, 71},
{71, 25, 65},
{98, 42, 16} },
**arr = NULL;
size_t rows = sizeof tmp / sizeof *tmp,
cols = sizeof *tmp / sizeof **tmp;
if (!(arr = malloc (rows * sizeof *arr))) {
perror ("malloc-arr");
return 1;
}
for (size_t i = 0; i < rows; i++) {
if (!(arr[i] = malloc (cols * sizeof *arr[i]))) {
perror ("malloc-arr[i]");
return 1;
}
for (size_t j = 0; j < cols; j++)
arr[i][j] = tmp[i][j];
}
puts ("orignal array:");
prnrowscols (rows, cols, arr);
insertionSort (arr, rows, cols);
puts ("\nsorted array:");
prnrowscols (rows, cols, arr);
for (size_t i = 0; i < rows; i++) /* free memory */
free (arr[i]);
free (arr);
}
Example Use/Output
$ ./bin/inssort_ptr2ptr
orignal array:
10 11 71
71 25 65
98 42 16
sorted array:
98 42 16
71 25 65
10 11 71
Look things over and let me know if you have further questions.
I got my answer to my question, just had to point to the c column using pointers in my while loop as a comparable(instead of arr[i][c] it became *(temp+c):
void insertionSort(double **arr, int rows,int c)
{
double *temp;
int i, j;
for (i = 1; i < rows; i++) {
temp = *(arr+i);
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j][c] > *(temp+c) ) {
int r = j + 1;
*(arr+r) = *(arr+j);
j = j - 1;
}
int t= j + 1;
*(arr+t) = temp;
}
}
tx for help everyone
void print2DArray(int aRRay[][COLS], int r, int c);
int main()
{
int aRRay[ROWS][COLS];
int n;
int r, c;
srand(time(NULL));
for (r = 0; r < ROWS; r++)
{
for (c = 0; c < COLS; c++)
{
aRRay[r][c] = -40 + rand() % (80 + 1 - (-40));
}
}
print2DArray(aRRay[r][c], r, c);
printf("Enter an integer between -40 and 80: \n");
scanf("%d", &n);
while (n >= 40 || n <= -80)
{
printf("Thie is an invalid integer, please re-enter an integer between
-80 and 40");
scanf("%d", &n);
}
return 0;
}
void print2DArray(int aRRay[][COLS], int r, int c)
statement
{
int j, k;
for (j = 0; j < ROWS; j++)
{
for (k = 0; k < COLS; k++)
{
printf("%d ", aRRay[r][c]);
}
printf("\n");
}
}
How do I print out a 2D array that is initialized in function main in C?
How do I get the function to work? I'm supposed to use the random number generator to create the numbers for my 2D array and then print it out in a void function.
int your last fonction {printf("%d ", aRRay[r][c]); } do this instead {printf("%d ", aRRay[j][k]); }. Because you are doing a loop but you are not using your loop to do anything, so use the j and k to loop in your printf. Hope it helps!!
How do I print out a 2D array ...?
OP's code is amiss:
// printf("%d ", aRRay[r][c]);
printf("%d ", aRRay[j][k]);
How it is initialized/assigned is not so important. Pass the dimensions to the print function first and then the array.
Array dimensions are best typed as size_t than int.
// C99 solution using a variable length array
void print2DArray(size_t rows, size_t cols, int aRRay[rows][cols]) {
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) {
printf("%d ", aRRay[r][c]);
}
printf("\n");
}
}
Sample use
#define ROWS 6
#define COLS 7
int main() {
int aRRay[ROWS][COLS];
size_t r, c;
int n = 0;
for (r = 0; r < ROWS; r++) {
for (c = 0; c < COLS; c++) {
aRRay[r][c] = ++n;
}
}
print2DArray(ROWS, COLS, aRRay);
int bRRay[2][3] = {{11,12,13}, {14,15,16}};
print2DArray(2,3, bRRay);
}
Output
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
11 12 13
14 15 16
OP had "I'm supposed to use the random number generator to create the numbers for my 2D array " which is fine. The above use ++n as it is more illustrative.
See also Passing a multidimensional variable length array to a function.
This is what I have so far
https://notepad.vn/lvqrsmz99
#include<stdlib.h>
#include<stdio.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[20];
int i,n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printArray(arr, n);
mergeSort(arr, 0, n - 1);
printf("\nSorted array is \n");
printArray(arr, n);
return 0;
}
This is what I need to print prior the final sorted array:
3
14
3 14
1
12
5
1 3 14
5 12
Noobie, there is a pretty good hint about where the "merge" is taking place in your code. That would provide a perfect place to look at the left and right sub-arrays before the merge.
If you look at the merge() function, you see the left and right sub-arrays being populated in the following code:
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
With a little creativity, you could output the sub-arrays as they are being filled to obtain your desired output, e.g.
for (i = 0; i < n1; i++) {
L[i] = arr[l + i];
printf (" %d", L[i]);
}
putchar ('\n');
for (j = 0; j < n2; j++) {
R[j] = arr[m + 1 + j];
printf (" %d", R[j]);
}
putchar ('\n');
(you could even add an additional putchar ('\n'); after your first call to printArray (arr, n); to format the output a bit nicer)
Example Use/Output
When implemented, your output would be:
$ echo "5 3 14 1 12 5" | ./bin/mergeprn
3 14 1 12 5
3
14
3 14
1
12
5
1 3 14
5 12
Sorted array is
1 3 5 12 14
(the input values were gleaned from your question)
Other Issues
Don't use magic numbers in your code (except where absolutely required like with the scanf field-width modifier). Instead, If you need a constant, #define one (or more), or use a global enum to do the same thing. That way you have one single place at the top of your code to change things if needed and you don't have to go picking through your declarations or loop limits to change things. E.g.
#define MAXA 20
...
int arr[MAXA] = {0}; /* always initialize arrays */
Always Validate scanf Return
Any time you are using scanf you must validate the return or you are just asking for Undefined Behavior in the event of a matching or input failure. It doesn't take much more effort, but will save you a world of grief, e.g.
if (scanf ("%d", &n) != 1) {
fputs ("error: invalid array size\n", stderr);
return 1;
}
if (n > MAXA) { /* protect your array bounds */
fprintf (stderr, "error: array size exceeds bound '%d'\n", MAXA);
return 1;
}
if (n < 2) { /* make sure you have something to sort */
fputs ("error, 'n' less than 2, nothing to sort\n", stderr);
return 1;
}
for (i = 0; i < n; i++)
if (scanf ("%d", &arr[i]) != 1) {
fprintf (stderr, "error: invalid input 'arr[%d]'\n", i);
return 1;
}
Now you can rest assured you are processing valid input, and not some accidental character that causes a matching failure and Undefined Behavior in your code.
I am trying to load my matrix so that consecutive numbers will go down the columns using pointer/addressing methods. Currently my program prints the consecutive numbers across the rows.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
int twodArray[5][5], *twodArrayptr;
int add = 0;
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
twodArray[i][j]= (i*5) + j;
}
}
twodArrayptr = &(twodArray[0][0]);
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
printf("%d ", *(twodArrayptr +((i*5)+j)));
}
printf(" \n");
}
}
If your point is to load the matrix with the opposite order, go with 4py's solution, if your point is to make use of the pointer to access the array in column order, then your solution is below.
You were SO CLOSE, your problem is here (you had i and j swapped). To change from row/col major ordering, you can do:
printf (" %2d", *(twodArrayptr + ((j * MAX) + i)));
Also note the main is type int and therefore returns a value.
Putting it together, you could do something like:
#include <stdio.h>
#define MAX 5
int main (void)
{
int i, j, twodArray[MAX][MAX] = {{0}}, *twodArrayptr = (int *)twodArray;
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
twodArray[i][j] = (i * MAX) + j;
printf (" %2d", twodArray[i][j]);
}
putchar ('\n');
}
putchar ('\n');
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++)
printf (" %2d", *(twodArrayptr + ((j * MAX) + i)));
putchar ('\n');
}
return 0;
}
Example Use/Output
$./bin/rowcol2d
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
0 5 10 15 20
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
Also note:, you do not need to use the variadic function printf to output a single character use putchar instead :)
Change the assignment logic to twodArray[i][j]= (j*5) + i;
Works like a charm.
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
twodArray[i][j]= (j*5) + i;
}
}