Int array in C++ - c++

I am trying to loop through the array and get the elements inside in C++. Here is my code:
int result;
int index_array [] = {11,12,13,14,15,16,17,18,19,20};
for (int count =0; count < index_array.length() ; count++){
if(count%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
If I change the for loop to:
for (int count =0; count < 10 ; count++){
There is no error because my array only consists of 10 items. But if I used the .length() method, there is an error which is expression must have a class type. I have no idea what is it, as in if it is in Eclipse, there contains a more detailed error description. What might be wrong?
Updated answer
for (int count =0; count < sizeof(index_array)/sizeof(index_array [0]) ; count++){
if((count+1)%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}

You can't call length() on int index_array[], it is a primitive array, not an object.
You could call size(), if you have, for example vector<int> index_array.

There is not .length for a plain array in C++.
Instead use std::vector and you can use method size() :
std::vector<int> index_array {11,12,13,14,15,16,17,18,19,20};
for (int count =0; count < index_array.size() ; count++){
if(count%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
Also in your case, you can calculate the length of the array:
int length = sizeof(index_array)/sizeof(index_array[0]);

int index_array [] = {11,12,13,14,15,16,17,18,19,20};
This is not an object that you can invoke some length() method on. Instead, it's a regular array, just like in C.
You can do one of two things.
The first is to use one of the C++ collection classes such as std::vector (adjustable size) or std::array (constant size) with their size() methods:
// C++11 syntax
std::vector<int> index_array {11,12,13,14,15,16,17,18,19,20};
// Pre C++11 syntax
int ia_src[] = {11,12,13,14,15,16,17,18,19,20};
vector<int> index_array (ia_src, ia_src + sizeof (ia_src) / sizeof (*ia_src));
std::array<int,10> index_array = {11,12,13,14,15,16,17,18,19,20};
The second is to simply treat the array as an array, in which case the length of that array can be found with the expression:
sizeof (index_array) / sizeof (*index_array)
Just be aware that this only works for arrays. If you pass that array to a function, it will decay to a pointer to the first element and sizeof will no longer work as you expect. You need to get the size while it's still an array and pass that along with it.

Arrays in c++ are not object (classes) so they don't have neither methods nor attributes.
May be you can use the Array class instead and get the size like std::array::size()

Related

How do you build an array with certain elements from another array in C++?

Given a one-dimensional array with n integers and a whole number A,
list how many elements are larger than A
and build an array with these elements.
I'm having problems with the last part.
The answer is almost already in the question
(giving it here, assuming that the question is really as simple as it confusingly seems to me):
count the relevant elements, print/"list" that number
create a new std::array of that size
(consider asking whether using a std::vector is an option, it would allow doing this in a single pass)
(explicitly do NOT attempt to use the non-C++ construct of C-style VLA, variable length arrays, like std::cin>>n; int NewArray[n];)
go through the input array again and copy the relevant elements to the new array
count indexes in both arrays separatly, because the index in the first array will soon be larger than the index into the new array
Note:
I intentionally do NOT provide code, because I feel that the compromise described here should be applied: How do I ask and answer homework questions?
First you have to create two arrays (if you can use std::vectors, i think they will work nicely in this scenario) - first one as a base, and the second one for storing values larger than A.
Get input of A and n.
Use a for loop to put n values into the base array.
Use a for loop to check if baseArray[i] is bigger than A, if true - put baseArray[i] into the second array (if youre using std::vectors do it by push_back()).
Display the number of values higher than A by secondArray.size().
Without using the std::vector:
#include <iostream>
using namespace std;
int main()
{
int n;
int A;
int howManyBiggerThanA = 0;
cin >> n;
cin >> A; //you haven't specified how the n and A are supposed to be implemented so ill assume its going to happen this way
int *array = new int[n]; //creating an array with n integers
array[0] = A; //assigning A to the array as specified in the question - "and a whole number A"
for (int i = 1; i < n; i++)
{
array[i] = i; //filling the array with n integers of value 1 to n-1 (u havent specified what values are supposed to be inside this array)
}
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
howManyBiggerThanA++; //determining how many values are bigger than A
}
}
int *arrayForBiggerThanA = new int[howManyBiggerThanA]; //creating an array for values that are bigger than A
int assistant = 0;
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
arrayForBiggerThanA[assistant] = array[i]; //filling the second array with elements that are bigger than A
assistant++;
}
}
cout << "How many elements bigger than A: " << howManyBiggerThanA << endl;
cout << "Values bigger than A: ";
for (int i = 0; i < howManyBiggerThanA; i++)
cout << arrayForBiggerThanA[i] << ", ";
delete[] array;
delete[] arrayForBiggerThanA;
return 0;
}

Creating array size of passed value gives garbage value

int higher_element = arr[0];
for(int i = 0; i < length; i++)
if(arr[i] > higher_element)
higher_element = arr[i];
cout << "Higher element in an unsorted array :" << higher_element << endl;
int Hash[higher_element] = {0};
Here I want to create a new array of size higher_element and initialize it to 0 but array is not creating, only a garbage value is created.
The output of the higher element is 12.
Since you are using C++, I suggest you to use vector.
Here's the std::vector solution for your problem.
std::vector<int> Hash(higher_element);
Vectors initialize to 0 automatically. But for your clarification,
std::vector<int> Hash(higher_element,0);
You can only use const in declaring the array.
If you want to use a variable to define the size of the array, try this
int *Hash;
Hash = new int[higher_element];
Hope to help you.

initializing a 2D array (Matrix) in C++

I am trying to create a 2D array by a for loop but I get some garbage random numbers
code:
unsigned int i, j;
int matrix[10][10];//={{},{}};
for (i = 0; i < sizeof(matrix[i])/sizeof(int); i++) {
for (j = 0; j < sizeof(matrix[j])/sizeof(int); j++) {
cout <<matrix[i][j] << " " << flush;
}
cout << endl;
}
and when I change cout part to the following
cout <<matrix[i][j] = {{i},{j}} << " " << flush;
I get an error.
how can I make it?
Thank you in advance.
The dimension of an array is how many indices are used to access it, which is different than the size of a dimension (how many elements are in a row of the dimension), which is different than the size of an array or the number of elements in the complete array.
With what you have written, you are writing a 2-dimensional array of 10 rows, each containing 10 elements for a total size of 100 elements.
If you want to do an initializer list in that syntax, you must specify each row and each element in nested braces. You have one top level set of braces for the total array, then a set of braces for each sub-array. You can do this with curly braces enclosing each row, specifying each element as a comma separated list:
unsigned int i, j;
int matrix[10][10] = {{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10}};
EDITED: The expression sizeof(matrix[i]) gives the size of the array as 40 because the compiler is able to figure that out at compile time, but it can be risky to rely on this since if you change it to a pointer to an array or the array is passed as a parameter to a function, it will give the size of the pointer instead of the array (as explained here: How do I determine the size of my array in C?). It would be better to display the array like this with the known length:
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
cout <<matrix[i][j] << " " << flush;
}
cout << endl;
}
Usually, for safety and convenience in changing, you can define the size using a macro like this:
#define ROWS 10
#define COLS 10
int matrix[ROWS][COLS] = ...;
then
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
cout <<matrix[i][j] << " " << flush;
}
cout << endl;
}
This way, if you decide to change the size of the matrix in the future, you only change the number in one place, the macro definition, instead of hunting through the code looking for each individual constant (especially with duplicate constants of 10, you might miss one or change an extra one that meant something else, which would cause problems somewhere else).

initializing a dynamic array to 0?

int main()
{
int arraySize;
int arrayMain[arraySize-1];
cout << "\n\nEnter Total Number of Elements in Array.\n\n";
cin >> arraySize;
arrayMain[arraySize-1]={0};
cout <<"\n\n" <<arrayMain;
return 0;
}
my compiler freezes when I compile the above code. I am confused on how to set a dynamic array to 0?
You use a std::vector:
std::vector<int> vec(arraySize-1);
Your code is invalid because 1) arraySize isn't initialized and 2) you can't have variable length arrays in C++. So either use a vector or allocate the memory dynamically (which is what std::vector does internally):
int* arrayMain = new int[arraySize-1] ();
Note the () at the end - it's used to value-initialize the elements, so the array will have its elements set to 0.
if you want to initialize whole array to zero do this ,
int *p = new int[n]{0};
If you must use a dynamic array you can use value initialization (though std::vector<int> would be the recommended solution):
int* arrayMain = new int[arraySize - 1]();
Check the result of input operation to ensure the variable has been assigned a correct value:
if (cin >> arraySize && arraySize > 1) // > 1 to allocate an array with at least
{ // one element (unsure why the '-1').
int* arrayMain = new int[arraySize - 1]();
// Delete 'arrayMain' when no longer required.
delete[] arrayMain;
}
Note the use of cout:
cout <<"\n\n" <<arrayMain;
will print the address of the arrayMain array, not each individual element. To print each individual you need index each element in turn:
for (int i = 0; i < arraySize - 1; i++) std::cout << arrayMain[i] << '\n';

C++ What's wrong with my array/loop?

I've just started learning C++ so I'm fairly sure the answer may be a simple one. As a test I'm just setting up an array and then wanting to print out the array by looping through it.
My code is below. It prints out my array as expected but then prints out a load of other numbers below it. What are these numbers and where are they coming from? I suspect that 'sizeof' isn't the best to use. All of the examples i've found are alot more complicated than I need. In any case I am interested to understand the extra numbers. Any insight available?
int age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
for (int i = 0; i <= sizeof(age); i++)
cout << age[i] << endl;
return 0;
...output:
23
34
65
74
4
2147307520
0
2293608
4198582
1
3084992
3085608
-1
2293592
1980179637
-725187705
-2
sizeof gives the size of an object in bytes. If the array elements are larger than one byte (as int usually is), the number will be larger than the array size.
One way to get the number of elements in an array is to divide by the size of an element:
for (size_t i = 0; i < sizeof(age)/sizeof(age[0]); i++)
std::cout << age[i] << '\n';
(note that you also need < rather than <=, or you'll still step off the end).
Another way is to pass a reference to the array to a function template, instantiated for the array size:
template <typename T, size_t size>
void print(T (&array)[size])
{
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << '\n';
}
print(age);
Yet another way is to use a std::vector or std::array instead of a plain array:
std::array<int, 4> age;
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
for (size_t i = 0; i < age.size(); ++i)
std::cout << age[i] << '\n';
sizeof(age) == sizeof(int) * number_of_elements ==>
number_of_elements = sizeof(age) / sizeof(int)
Then your code becomes:
for (int i = 0; i < sizeof(age)/sizeof(age[0]); ++i)
cout << age[i] << endl;
In C++ you may write a function to calculate the size for you(doesn't work with dynamic arrays):
template <class T, std::size_t size>
std::size_t array_size( T(&arr)[size] )
{
return size;
}
If you are up to C++11, you could go with for-each loop:
for(int element : age){
....
}
Also, free-function form of std::begin and std::end can do the job:
for(auto b = std::begin(age); b != std::end(age); ++b){
....
}
Sould be i < 4 because sizeof(age) is 16 on a 32 bits machine.
sizeof(age) is the number of bytes of age, not the number of elements.
Divide it by the size of an element of age to get that:
for (int i = 0; i < sizeof(age) / sizeof(*age); i++)
cout << age[i] << endl;
Note: for dynamic arrays, you have to store the size of the array separately:
std::size_t size = 4; // size_t corresponds to maximum size an array can hold
int* age = new int[size];
for (int i = 0; i < size; i++)
cout << age[i] << endl;
The other numbers are garbage past the end of the array.
age[10] is undefined behavior, which is essentially garbage numbers.
Sizeof is age array is 16 bytes I.e. Sizeof(int) * 4. You need array length.
Since sizeof(age) returns 16, you have your 4 values plus 12 ones whose value comes from the memory that is right after your array. Values in those memory segment is random, depending on what has been stored there right before you launched your program. If you used a memory check tool, you would have had an error since this memory is probably not allocated for your program.
As the other ones said, you should probably giving the exact number of element in your array as an additional variable.
const int COUNT = 4;
int age[COUNT];
age[0]=23; age[1]=34; age[2]=65; age[3]=74;
for (int i = 0; i < COUNT; ++i)
{
cout << age[i] << endl;
}