Printing an Array in C++

How to print the array?

What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them.

for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}

This will print it in the following format

10 23 42
1 654 0
40652 22 0

if you want more exact formatting you'll have to change how the printf is formatted.

How can I print an int array in C in one line (meaning, without for loops)?

No,In C you cannot print array with single line of code, there is no inbuilt function available in C to print the array in single line.

Python also doesn't print array in single line, it does use loops but those functions are not visible to us.

How ever there are ways by which we can print C array without for-loop, You can refer this Question answered in stack overflow for that.

Is printing array possible without any loop in the C Language?

Storing and printing array in C

#define AGE 12 and #define r(i,j) r[(i)*n+(j)] work in the same way.

In your program, the code matching AGE wioud be replaced by 12, the same way, the code maching r(i,j) will be replaced by r[(i)*n+(j)], i and j being the values passed as argument of the function-like macro.

Let's say i is 1, j is 2, and n is 5, r(i,j) = r(i-1,j) * r(0,j)

Would be equivalent to:

r[(1)*5 + (1)] = r[(1-1)*5 + (2)] * r[(0)*5 + (2)]

Wich will amount to:

r[6] = r[2] + r[2]

The array element with index 6 will be assigned the result of the sum of the values stored in array element with index 2.

About the what the function does, it's just array arithmetic to use a 1D array as if it was a 2D array, avoiding the need to use an actual 2D array to store/print the values.

If you replace the print loop, with something like:

for (i = 0; i < n * n; i++) { 
printf("%10ld", r[i]);
}

You'll see the same values but printed as a 1D array, which is really what it is.

The printed seemingly random numbers, are just a hint that you are accessing the array ouside its bounds invoking undefined behavior.

Printing an array in C++?

Just iterate over the elements. Like this:

for (int i = numElements - 1; i >= 0; i--) 
cout << array[i];

Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.

C: print an array

The "wierd" value you get from printing array is actually the memory address of the first element of the array.

In order to print an array, you need to use a for loop:

for (int i = 0; i < array_size; i++)
printf("%d\n", array[i]);


Related Topics



Leave a reply



Submit