0

What is the best way to calculate the no of elements that array has? Any formula.

8th Jan 2017, 2:45 PM
Zahid Khan
Zahid Khan - avatar
10 Answers
+ 3
I think you need to: #include <array> http://www.cpluplus.com/reference/array/array/size/
8th Jan 2017, 3:25 PM
visph
visph - avatar
+ 2
Use built-in function/method ^^
8th Jan 2017, 2:48 PM
visph
visph - avatar
+ 2
In Python: len(myArray) In Javascript: myArray.length; In C++: myArray.size(); ( because the three languages were initialy tagged in question ^^ )
8th Jan 2017, 2:58 PM
visph
visph - avatar
0
which builtin function? One way of doing it in c++ is : cout<< sizeof(array)/sizeof(array[firstelement] ); But the problem with this is that; it is limited to the function, it is defined in.
8th Jan 2017, 2:51 PM
Zahid Khan
Zahid Khan - avatar
0
I think that you are looking for the len function
8th Jan 2017, 2:53 PM
Tito Campos
Tito Campos - avatar
0
I wanna know how many elements an array contains without using sizeof()
8th Jan 2017, 2:54 PM
Zahid Khan
Zahid Khan - avatar
0
#include <iostream> using namespace std; int main() { int array[10]; cout<<array.length; return 0; } producing error
8th Jan 2017, 2:58 PM
Zahid Khan
Zahid Khan - avatar
0
in cpp I am executing the above code. #include <iostream> using namespace std; int main() { int array[50]; cout<<array.size(); return 0; } it is producing error. @visph
8th Jan 2017, 3:19 PM
Zahid Khan
Zahid Khan - avatar
0
#include <iostream> using namespace std; int main() { int array[50]; cout<<array.size(); return 0; } it is producing error. This code above will not compile. If you want to get the size of array, you use the built in function with your variable attached. array.size(). The reason for the compile error is because you have to declare the array for it to get the size. int array[2] = {2, 4, 6} The reason is in order to get the number of elements, the compiler first gets int which equals 4. Then it calculate it by 3 to get the bits it takes up which is 12. For elements it divides by three 12/3. It doesn't do it for 50 because you may not use 50. It is just the max you set aside for it. I hope that helped a bit.
24th Jan 2017, 8:14 AM
Bryan Lopez
Bryan Lopez - avatar
- 1
09
10th Jan 2017, 11:31 AM
Xavier Cabiles
Xavier Cabiles - avatar