How to print the array?
I am not able to get the array to print.. Any ideas why? I am a beginning programmer so any words of advice are appreciated.
![]()
6 Answers 6
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.
This will print it in the following format
if you want more exact formatting you’ll have to change how the printf is formatted.
There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.
I would suggest something like this:
The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.
How to print all elements of a list in C#
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
The List<T> class in the System.Collection.Generic namespace represents a collection of strongly typed elements and offers many ways to iterate and manipulate the list.
Below are some of the ways to print the items of a C# list.
Creating a list of strings
Here, we create a list of months.
Using the for loop
The simplest method to access the elements is by using the for loop. We can access the individual items in the list by their index, months[i] , and then print the element using the Console.WriteLine() method.
Using the foreach loop
The foreach loop is a convenient construct to iterate through the items in a collection – it can be used to print the elements.
Using the ForEach method
The List<T> class provides the ForEach(Action<T>) method to perform a specified action on each of the list elements.
Распечатать массив в C#
В этом посте мы обсудим, как печатать одномерные массивы в C#.
1. Использование foreach петля
The оператор foreach предоставляет простой и понятный способ перебора элементов массива. В следующем примере показано использование оператора foreach для печати одномерных массивов в C#.
В приведенном выше коде используется Console.WriteLine() который выводит каждый элемент на отдельной строке. Чтобы напечатать каждый элемент в одной строке, используйте Console.Write() , как показано ниже:
Мы также можем использовать цикл for для обработки элементов в порядке возрастания индекса, начиная с индекса 0 до индекса Length — 1 , как показано ниже: Решение обрабатывает завершающие символы-разделители.
2. Преобразовать в список
Другой подход заключается в использовании ToList() method to convert the array into a generic List<T> and then call its ForEach() метод для выполнения операции печати для каждого элемента списка.
Этот подход не рекомендуется, так как он включает создание списка в качестве промежуточного шага.
How to print an array in C++
By default, the initialization of the array is from left to right. We can say that none of its elements could be set as any particular location of the memory of the array. After setting the range or element of the array, we can give values after the equal sign in the curly braces <>. We can explicitly initialize specific values when we declare them. The number of values shall not be greater than the range that we set as a range of the array.
Insert and print array:
Here we show you how we simply initialize, insert and print an array. We can access the value of the array just like we access the simple variable of the identical data type. If we exceed the limit of the array, there is no error in compile-time, but it can cause a runtime error.

Here add our input-output stream and add namespace standards. Then we initialize an integer array with the name of ‘a’ and assign it some values. In the main body of the code, we simply display the array with its indexes. To make our output readable, we print every value to a new line with the help of the endl statement.

Print array with loop:
In the above example, we use a cout statement for every index that makes our code lengthy and takes space in the memory. We use the loop to cout our array; this makes our code short and saves our time and space.

Now we can see that we initialized a long array with the length of 10 and assigned members at each index. Then we write a loop, and the limit of the loop is the same as the limit of the array in the main body of the code. In the loop, we just write the cout statement along with the endl and display each member of the array that starts from zero until the condition is false.

Get value and print array:
As we know that in programming, there are a lot of problems to solve, so we need something that has versatility in our development. The array can allow us to enter your value. That array will store it in its indexes, and we can use these values according to our choice or condition.

Here we include our library and namespace and start the main body of the program. In our main function, we initialized our array with the data type of integer. After that, we start our loop and ask the user to enter the values at every loop index. We save these values in their respective indexes. Then we start another loop to display the values that we entered in the earlier loop.

Get the size and value, then print array:
As we said above, the array gives us many facilities to make us comfortable while coding. Here we talk that we can also define the size of our array. To save our memory at run time. If we don’t know the size while coding, you can just empty the array and ask the user to set the size at run time.

As you see in this example, after the protocols of the code, we start our main body and initialize a variable with the data type of integer. After taking the value from the user, we store this variable. Then we assign this value as the size of the array. After that, we start the loop to get values of the array from the user and store them at their indexes. Quickly after that, we use another loop to display our value, and we use “\t” to enter a tab between the value and them separate from others.

Print 2D array:
We discuss now the liner or 1D, which is a one-dimension array. Here we discuss the other and main type of array that is called a 2D array or two-dimension array. This array is just like a matrix, and we enter our values at its indexes. That is how it has to index: one is from left to right or in a row; the second is from up to down or in the column.
The syntax of the 2D array in C++ is data type variable name [rang] [range] = <

Here we can see there is no difficult thing in this code; we just simply initialized an integer 2D array. You can say we take a matrix of 2×2. Then assign values to this array. After that, we just print these arrays, and you can see the values on their respective indexes.

Conclusion:
This article defines the array and briefly discusses all its basic features. Also, we study how many ways we can read and write arrays in the code. Then we describe the main type of array, a 2D array, and then we explain how we can display it in multiple ways with the help of different examples.
About the author

Omar Farooq
Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.