array size in for loop

Hello, I am wondering about getting the size of an array and using it in a for loop. Is this possible? Code given below. In the first for loop I used 10 as the condition, since I know the array is size 10, but then I am wondering, what if I do not know the size of the array but i want the for loop to be less than the size of array, how do I work that? I try .length, but that does not work. Is there a way to do this? Thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #include <iostream>

using namespace std;

int main()
{
	int arr[] = { 1, 3, 5, 3, 5, 1, 2, 2, 6, 1 };

	for (int i = 0; i < 10; i++)
	{
		for (int j = i+1; j < arr.length; j++)
		{
			if (arr[i] == arr[j])
			{
				cout << arr[j] << endl;
			}
		}
	}
	return 0;
}
Have you considered using std::vector instead of the old fashioned C style arrays?

Unlike the old fashioned and dangerous C style arrays a std::vector knows it's size.

But to answer your question, you can use the sizeof operator to get the size of the array (as long as the array is actually in scope).

I am learning from a book currently and only arrays have been covered. I have not went over vectors yet, This problem that I was solving was asked to be completed was with an array like i done. But I will look at vectors now to know what they are. Oh I know the sizeof operator, I read that in the book yesterday, but I thought that only worked for bytes though so thought that would not work for me. I will try that, thank you.
it is in bytes, but you can force it back.

int arrSize = sizeof(arr)/sizeof(arr[0]);

size of the array in bytes
---------------------------- = num locations
size of one location in bytes

this is using a lot of trouble to find what you already knew.
{ 1, 3, 5, 3, 5, 1, 2, 2, 6, 1 };
--1--2--3-4-5--6--7--8-9-10---
array is sized 10. you told it that when you made it :)
Last edited on
If arr is in scope, then for 1-dimensional arrays you can use std::size() [since C++17]. If arr is passed as a parameter of a function, then there is a clever template construct that is used to obtain the size of the passed array in the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main()
{
	int arr[] = {1, 3, 5, 3, 5, 1, 2, 2, 6, 1};

	for (int i = 0; i < size(arr); ++i)
		for (int j = i + 1; j < size(arr); ++j)
			if (arr[i] == arr[j])
				cout << arr[j] << endl;
}

Instead of std::vector you also can use std::array.
http://www.cplusplus.com/reference/array/array/
@MyOnlinePersona,
As a matter of interest, what is your code intended to do once it does know the array size?

After all ... it may not need to know the array size.
Last edited on
Topic archived. No new replies allowed.