Arrays in C++ - Reading Assignment

1. What is an array?
An array is a aggregate type, which lets us access multiple variables through a single identifier. To access the individual values the identifier and an index is required.

2. Which index would you use to access the 2nd variable in an array?
1, as the indexing starts to count at 0

3. What can you say about the size of an array?
The size of an array most commonly is its length. Furthermore the size can also be the array length multiplied by the element size, which gives the array size in byte.
For static arrays the length is defined at compile time for dynamic arrays the size is defined at runtime.

  1. How can you initialize an array?
    With an initializer list. The list can be empty, in this case all values are initialized with 0. Alternatively the values can be provided in the list. Are there fewer items in the list as the length of the array, these items will be initialized with 0.

  2. How can you get the size of an array in bytes?
    With the sizeof() function. This will return the array size: array length * element size

  3. How can you use the function sizeof in order to calculate the number of elements in an array?
    By dividing the byte size by the size of one element:
    sizeof(array)/sizeof(array[0])

  4. What happens when you try to write outside the bounds of the array?
    The value will get stored at the memory location where this additional item would have been located. This can result in over writing values of another variable. It will cause undefined behavior, potentially crashing the program.

1 Like

Part i.

1. What is an array?
An array is a collection of variables of the same type, grouped under the same identifier.

2. Which index would you use to access the 2nd variable in an array?
When dealing with arrays, it is best to think of the index number as an offset amount, as in how many positions from the beginning of the array do you want to start at. For example, index 0 is 0 positions away from the start, therefore 0 is the first element in the array. Index 4 would be the 5th element (4 positions away from the 1st element which is index 0).

3. What can you say about the size of an array?
For fixed arrays the length of the array must be known at compile time because the compiler allocated memory for each of the elements. Dynamic arrays can be set at runtime and changed but are more complex regarding intantiation.

Part ii.

  1. How can you initialize an array?
    You can initialise an array with an initialiser list - this is where the elements of an array are housed within curly brackets like these { }.
    You cannot have more initialisers in the list than what the array can hold.

  2. How can you get the size of an array in bytes?
    you can use the sizeof operator to determine the size of the array.

  3. How can you use the function sizeof in order to calculate the number of elements in an array?
    The function sizeof can be used to determine the number of elements in the array by getting the total size of the array and dividing it by the size of one of the elements. For example, sizeof(array) / sizeof(array[0])

  4. What happens when you try to write outside the bounds of the array?
    If you try to write outside of the bounds of the array, you will generally get undefined behaviour. For example, if you try to add a value into an element that doesn’t exist, it may overwrite one of the predefined elements or cause the program to crash.

Quiz Parts:

//The following is part 1 of the quiz section.  I couldn't tell if it wanted anything done with this array or for it just to be zero initialised. - note, this is within the main function.

double myTemperature[365]{};

//The following is part 2 of the quiz section.
//Set up an enum with the names of the following animals: chicken, dog, cat, elephant, duck, and snake. Put the enum in a namespace.
namespace Animals
{
    enum Animals
    {
    chicken,
    dog,
    cat,
    elephant,
    duck,
    snake,
    max_animals
    };
}

int main()
{
//The following is part 1 of the quiz.  I couldn't tell if it wanted anything done with this array or for it just to be zero initialised.

double myTemperature[365]{};



//Define an array with an element for each of these animals, and use an initializer list to initialize each element to hold the number of legs that animal has.

int animalsLegs [Animals::max_animals] {2, 4, 4, 4, 2, 0};

//Write a main function that prints the number of legs an elephant has, using the enumerator.

cout<< animalsLegs[Animals::elephant]<<endl;

1 Like

1. What is an array?
an array is a data type that lets us access many variables of the same type through a single identifier.

2. Which index would you use to access the 2nd variable in an array?
array[1]

3. What can you say about the size of an array?
Size of an array is the number of variables or elements that can be placed in one array

4. How can you initialize an array?
by individually defining the values int prime[5] = { 8, 3, 9, 2, 5};
or create an initializer list which is recommended =
“not” specify the length of the ‘fixed’ array and let C++ figure it out.
int prime [ ] = {0, 1, 2 ,3 ,4, 5};

5. How can you get the size of an array in bytes?
we can use sizeof(array);

6. How can you use the function sizeof in order to calculate the number of elements in an array?
sizeof (array) / sizeof (array [0])

7. What happens when you try to write outside the bounds of the array?
You get unexpected behavior like program crash, overwrite the value of another value.

1 Like
  1. What is an array?
    An array is an aggregate data type that lets us access many variables of the same type through a single identifier

  2. Which index would you use to access the 2nd variable in an array?
    The index I would use is number 1. In C++ indexing for arrays start from 0, making the second index number 1.

  3. What can you say about the size of an array?
    The user can set the array length by inserting the numbers of array length in the square bracket(subscript operator) ‘[ ]’ to let the compiler know amount of fixed arrays to store in the variable. Example: int array_variable[5]{}; //This array variable has a array length of 5 in the subcript operator.

  4. How can you initialize an array?
    Arrays are initialized element by element. To conveniently initialize entire arrays use a initializer list.

  5. How can you get the size of an array in bytes?
    By using the std::sizeof(array) operator, will call the array and return the total size value of the array length.

  6. How can you use the function sizeof in order to calculate the number of elements in an array?
    To determine the number of elements in an array, we can use the equation = sizeof(array) / sizeof(array[0]). The equation is calculating array size multiplied by the array length.

  7. What happens when you try to write outside the bounds of the array?
    Writing outside the bounds of the array can potentially cause the program overwrite values on another variable and lead to program errors and crash.

1 Like
  1. What is an array? An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Brackets [ ] tell the compiler that the variable is an array. The element has a parameter called a subscript so that the compiler knows which element is needed.
    int array[50]{}; allocates 50 integer variables or elements to a fixed array.
  2. Which index would you use to access the 2nd variable in an array?
    array[1]
    The index count starts at 0.
  3. What can you say about the size of an array?
    A fixed array is an array where the length is known at compile time. A fixed array declaration must be a compile time constant. Non-constant variables or runtime constants cannot be used. Fixed arrays cannot have a length based on either user input or some value calculated at runtime. The fixed array length cannot be changed. Dynamic arrays do not have a fixed size defined before compile time.

Think about the following questions while reading:

  1. How can you initialize an array? Use an initializer list int array[5]{3,5,2,1,8}; or int array[]{};.
  2. How can you get the size of an array in bytes? sizeof(array)
  3. How can you use the function sizeof in order to calculate the number of elements in an array? The sizeof function is used instead of size(array) in non C++ 17 compatible compilers. When using sizeof, the size of the entire array is divided by the size of an array element, i.e., sizeof(array) / sizeof(array[0])
  4. What happens when you try to write outside the bounds of the array? You will get an undefined behavior. It may overwrite the value of another element and cause the program to crash.
1 Like

An array is an aggregate data type that lets us access many variables of the same type through a single identifier.

index 1

If we use the “sizeof” operator on an array, we will get the number of elements of the array multiplied by the size of the type of the elements.
If we use the std::size() function, we will get the length of the array (the number of elements it holds)

The most convenient way to initialise an array is to use initialiser list.
eg.: int arr[4]{11,22,33,44}

By using the sizeof() operator. It will multiply the number of elements by the size of the type of the array.
eg.: double arr[3]{2.2, 3.4, 5.6};
std::cout << sizeof(arr);
This will print: 24
as in double(8) * number of elements(3)

double arr[3]{1.2, 2.4, 3.5};
std::cout << sizeof(arr)/sizeof(double) <<"\n";

This will print: 3

The excess input will be stored somewhere in memory or the compiler will trow an error in newer versions, in older versions, will result in undefined behaviour.

1 Like
  1. What is an array?
    An array is a group of variables of the same type with the same identifier but accessed via array subscript.

  2. Which index would you use to access the 2nd variable in an array?
    Use index 1 since array start counting from 0.

  3. What can you say about the size of an array?
    The size of an array needs to be define at compile time and it is fixed.

  4. How can you initialize an array?
    You initialize array by using empty bracket {} which initializes all elements to 0, you can also use element list using brackets to set a value to each element, or you can initialize each element one by one in separate lines.

  5. How can you get the size of an array in bytes?
    You can use the function sizeof() which will give you the size of the array in bytes.

  6. How can you use the function sizeof in order to calculate the number of elements in an array?
    sizeof() function takes the number of elements multiplied by the size of an element so to obtain the number of elements we can use formula sizeof(array) / sizeof(array[0]).

  7. What happens when you try to write outside the bounds of the array?
    It will cause undefined behavior.

1 Like

You can have a dynamic array that you define using *arr which size can later be initialized at runtime.
For example: int *arr = new int(n) where n a user can input from the keyboard :slight_smile:

2 Likes
  1. What is an array? “An array is an aggregate data type that lets us access many variables of the same type through a single identifier.”
  2. Which index would you use to access the 2nd variable in an array? index [1] Arrays always count starting from 0.
  3. What can you say about the size of an array? S quare brackets, i.e.[5], tell the compiler this is An array variable (verses a normal variable) and how many variables to allocate, which indicates length.

Read this article ( http://www.learncpp.com/cpp-tutorial/62-arrays-part-ii/ ).

  1. How can you initialize an array? Arrays can be initialized element by element:
    i.e.
    int prime[5]; // hold the first 5 prime numbers

prime[0] = 2;
prime[1] = 3;
prime[2] = 5;
prime[3] = 7;
prime[4] = 11;

or more conveniently via the use of an initializer list: i.e.

1 int prime[5]{ 2, 3, 5, 7, 11 }; // use initializer list to initialize the fixed array

  1. How can you get the size of an array in bytes? By use of the sizeof operator.
  2. How can you use the function sizeof in order to calculate the number of elements in an array? Divide the size of the array by the size acquired by each element, to get the total number of elements in the array.
  3. What happens when you try to write outside the bounds of the array? Undetermined behavior, undesirable results and it could cause your computer to crash.
1 Like

Hmmmm, you mean the size of each element combined? Wouldn’t that give you the same size of the entire array, thus resulting in 1? :thinking: Can you write an example?

1 Like
  1. What is an array?
    A variable that holds many values. A collection of data that groups everything under one identifier.

  2. Which index would you use to access the 2nd variable in an array?
    [1]

  3. What can you say about the size of an array?
    The size of a fixed array is constant that does not change. A dynamic array is a different animal that can be changed or set at runtime.

  4. How can you initialize an array?
    Intialize to zero:
    int array[3] = {0,0,0}; or int array[3] ={ };
    Fixed elements:
    int array[3] = {1,2,3,}; or int array[] {1,2,3};

  5. How can you get the size of an array in bytes?

sizeof(array)

  1. How can you use the function sizeof in order to calculate the number of elements in an array?
    sizeof(array) / sizeof(array[0])

  2. What happens when you try to write outside the bounds of the array?
    You will get an undefined behavior because the there is no index for the value. The return may be a number indicating location of memory or something.

1 Like
  1. An array is a collections of variables identifiable by an index.
  2. index[1]
  3. The size of an array is either fixed ( the length is known at compile time) or dynamic ( the length can be set at tun time and is changeable)

  1. First we specify the type of array, name and then the size. Then we assing values to each index. E.g. int myArray[2] = {1,2}

  2. sizeof(array)

  3. sizeof(array)/sizeof(array[0])

  4. Since index doesn’t exist, the value will be added to an address in memory outside the array, leading to undefined behavior.

1 Like

What kind of variables? :slight_smile:

1 Like

So I am learning and not an expert or a programmer, but this is what I’ve found:

“Logic. Get the occupied size of all array elements and divide it with the size of array type. Let suppose there is an integer array with 5 elements then size of the array will be 5*4=20 and the size of array type will be 4. Divide 20 by the 4 answer will be 5 which is the number of **array elements.”

#include <stdio.h>
int main()
{
	int arr[]={2,3,5,7,11};
	int n;
	
	n=sizeof(arr)/sizeof(int);
	
	printf("Number of elemenets are: %d\n",n);
	
	return 0;
}

Number of elements are 5.

1 Like

Yes this is correct :slight_smile: maybe I misunderstood your initial reply.
I thought you wanted to calculate the number of elements in the array by using the sizeof and dividing it with all the elements. :slight_smile:

1 Like

Basic types of variables might be int, floats, strings, etc ( basically number and letters)

An array can also store complex objects like structs :slight_smile: But is there a limitation to the types that a specific array can store? :slight_smile:

1 Like

PART I
1. What is an array?

An array is an aggregate data type that lets us access many variables of the same type through a single identifier.

2. Which index would you use to access the 2nd variable in an array?

In C++ the first element of an array is at index [0], therefore its 2nd variable would be at index [1]

3. What can you say about the size of an array?

The size of an array in C++ or its length can’t have a length based on user input or any other value calculated at runtime. It is fixed when the array is declared and cannot be changed because it must be known at compile time.

PART II

  1. How can you initialize an array?

The most convenient way to initialise an arrays is using an initialiser list.

  1. How can you get the size of an array in bytes?

Using the sizeof() operator.

  1. How can you use the function size of in order to calculate the number of elements in an array?

array length = sizeof(array) / sizeof(array[0])

  1. What happens when you try to write outside the bounds of the array?

One can’t really guess, you’d get undefined behavior.

QUESTION

#include <iostream>
 
void passValue(int value) // value is a copy of the argument
{
    value = 99; // so changing it here won't change the value of the argument
}
 
void passArray(int prime[5]) // prime is the actual array
{
    prime[0] = 11; // so changing it here will change the original argument!
    prime[1] = 7;
    prime[2] = 5;
    prime[3] = 3;
    prime[4] = 2;
}
 
int main()
{
    int value{ 1 };
    std::cout << "before passValue: " << value << '\n';
    passValue(value);
    std::cout << "after passValue: " << value << '\n';
 
    int prime[5]{ 2, 3, 5, 7, 11 };
    std::cout << "before passArray: " << prime[0] << " " << prime[1] << " " << prime[2] << " " << prime[3] << " " << prime[4] << '\n';
    passArray(prime);
    std::cout << "after passArray: " << prime[0] << " " << prime[1] << " " << prime[2] << " " << prime[3] << " " << prime[4] << '\n';
 
    return 0;
}

I was reading through the article and I could comprehend why the value after calling the function passValue is still the same, shouldn’t it be 99. I thought this was because if was a void type function but after trying to change to int type and returning its value the ending result was still the same. Can someone clarify this for me? Thanks in advance.

There is no limitation since arrays can be made from any data type.

For example:

struct student
{
char name[20];
int roll_no;
float marks;
string last name
};

Not necessarily :slight_smile: you can have a dynamic array whose size can be determined at runtime :slight_smile:
For example: int *arr = new int(n) where n can be a user input.

The reason this doesn’t work is because the function will receive a copy of this value and change that value so once the function ends, the result will be lost.
There are two ways you can fix this, one is to return the value

int passValue() // here you don't need to pass parameter
{
    return 99; // return 99
}

or pass the pointer of the memory location where the value is stored and change it

void passValue(int *value) // you pass the pointer to memory address of the value
{
    *value = 99; // change the value at that location
}

passValue(&value); // pass the address of the value, not the value itself
2 Likes