Arrays in C++ - Reading Assignment

  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++, arrays are 0-indexed based so I would use index 1 to access the 2nd variable in an array.

  3. What can you say about the size of an array?
    – For the size of an array of length N, the array elements are numbered 0 through N-1. This is called the array’s range. The size of an array is the range of the array multiplied by the size of each element

  4. How can you initialize an array?
    – An array can be initialized element by element but this approach is not efficient. Fortunately, an array can be initialized using an initializer list as shown in the following example: int prime[5]{ 2, 3, 5, 7, 11 }; // use initializer list to initialize the fixed array
    NOTE: Even if the length of the array is omitted the compiler will use the number of elements in the initializer list to determine the length.
    NOTE: If the initializer list is omitted, the elements are uninitialized, unless they are a class-type.

  5. How can you get the size of an array in bytes?
    – The sizeof() function from the header can be used to determine the size of an array.

  6. How can you use the function sizeof in order to calculate the number of elements in an array?
    – You can divide the sizeof the array by the size of an element (usually the first element which should exist) to determine the number of elements in an array.

  7. What happens when you try to write outside the bounds of the array?
    – Undefined behavior - such as overwriting the value of another variable, or causing the program to crash - could result if an attempt is made to write outside the bounds or range of the array.

**** QUIZ ****

double temperatures[365}{};

#include

namespace Animals {
enum Animals {
chicken,
dog,
cat,
elephant,
duck,
snake,
max_animals
};
}

int main() {

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

std::cout << "An elephant has " << legs[Animals:elephant] << "legs.\n";

return 0;

};

1 Like

1.) An array is an aggregate data type that allows us to access many variables of the same type through a single identifier.
2.) [1]
3.) An array can have a fixed length or a dynamic length.
4.) The letting the initializer list define it, or listing every element out manually.
5.) sizeof(array)
6.) sizeof(array)/sizeof(array[0])
7.) When you write out of bound of an array it will return unidentified behavior. This could rewrite variables of crash your computer.

1 Like

While loops

  1. A while statement helps us execute a list of statements as many times as the expression in the brackets evaluate to true.
  2. The expression in the bracket needs to evaluate to true in order for the loop to continue.
  3. An infinite loop happens when the expression always evaluates to true.
  4. Iteration is each time the loop executes.

Quiz Q#1:
Variable inner is declared inside the outer while block instead of after the declaration of variable outer (in main loop), because for the variable inner not to be destroyed after each iteration, it is enough to declare it above the nested loop. Declaring it in main loop also works.
Quiz Q#2:

    char a { 'a' };
    char z { 'z' };
    int counter {static_cast<int>(a)};
    int limit = static_cast<int>(z);
    while(counter <= limit){
        cout << static_cast<char>(counter) << " " << counter << endl;
        counter++;
    }

Quiz Q#3:

    int outer{ 1 };
    while (outer <= 5)
    {
        int inner{ 5 };
        while (inner >= outer)
        {
            cout << inner-- << ' ';
        }
        cout << '\n';
        ++outer;
    }

Quiz Q#4:

    int row{ 1 };
    while (row <= 5)
    {
        int col{ 5 };
        while (col >= 1){
            if (col > row) {cout << "  "; --col;}
            else {cout << col-- << ' ';}
        }
        cout << '\n';
        ++row;
    }

For loops

  1. It is better to use a for loop when we know exactly how many times we want to execute a statement list.
  2. for(int count{0}; count < 10; ++count) {statement list} <- executes statement list 10 times
  3. An off-by-one error is when the loop iterates one too many or one too few times.

Quiz Q#1:

    for (int number {0}; number <= 20; ++number)
        if (number % 2 == 0) cout << number << " ";

Quiz Q#2:

int sumTo(int value){
    int sum {0};
    for (int counter {1}; counter <= value ; ++counter)
        sum += counter;
    return sum;
}

Quiz Q#3:
// Print all numbers from 9 to 0

for (unsigned int count{ 9 }; count >= 0; --count)
cout << count << ' ';

Once the count gets to 0, it is set to 4294967295 and the loop starts again.
Variable count should be just int.

2 Likes

Good job! :raised_hands: you just posted in the wrong thread :smile:

2 Likes
  1. An array is a data type used to store a collection of data of the same type.

  2. arrayName[1]

3 the size of a (fixed length) array is determined at compile time and has therefore to be declared before runtime.


  1. You can initialize it in various ways:

int array[2] {1, 5, 7} --> that’s an an array of 3 int elements
int array[2] {63} --> that’s still an array of 3 int elements, the first of which is the integer 63 and the last two are set to 0 by default (zero initialization)
int array[] {11, 5, 86} --> this is also an array of 3 implicitly defined integer elements

  1. by using sizeof(arrayName) --> That will multiply the byte size of each element in the array with the total number of elements in the array, giving the total size.

  2. by doing sizeof(arrayName)/ sizeof(arrayName[0]) we get the total size of the array divided by size of the first element in the array, thus giving us the number of elements in the array.

  3. C++ doesn’t check whether you’re trying to write out of the bounds of an array and will still store the value in a memory region as if there was one more slot in the array. But since the array’s length is defined at compile-time and can’t be changed, that means that the value will be stored in a random memory location, with a chance of overriding another existing value at that memory address, yielding unpredictable results or even crashing our program.

1 Like

Thanks @Alko89
I didn’t notice, although it writes on the page header Arrays:))
I should read the page header before posting…

1. What is an array?
A variable where you can store indexed objects and the allocated memory is consecutive so by address reference access in Ansi C.

2. Which index would you use to access the 2nd variable in an array?
First index is 0. The second index is 1. You access the second variable with the index 1 : array[1];

3. What can you say about the size of an array?
The size of an array is the array length multiplied by element size. You can specify the array length during the declaration between brackets, otherwise, the compiler can do it for you if you initialize the array.

1. How can you initialize an array?
Many possibilities :

  • int array[3] = { 7 }; // only initialize the first element
  • int array[3] = { 0, 1, 2 }; // explicitly define length of the array
  • int array[] = { 0, 1, 2 }; // let initializer list set length of the array
    If multi-dimension array and/or initiates the same value for many element, a for loop with i/j/k as index

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?
sizeof(array)/sizeof(<type of element in your array>);
Example with array of int : sizeof(array)/sizeof(int);

4. What happens when you try to write outside the bounds of the array?
You get undefined behavior. You can overwrite a value in memory, the program can crash…

1 Like

-A-
1.
A collection of variables (called elements) of the same type, stored under a common name.

[1]

For fixed arrays it is defined as an integer. It has a length of whatever the number inside [] is. The length is a compile time constant, so should be defined in advance. It cannot be undefined or changed during program execution.
For dynamic arrays the size can change.

-B-
1.
We initialize an array the same way as we do with other variables - Define values wherever, presumably before the first use. We can define each value separately or many at once via an initializer list { }.

Using the sizeOf(array) function.

sizeOf(array) divided by sizeOf(array[0]) => gives you the number of elements

You get undefined behaviour and program might crash.

1 Like

Article 1*
1. What is an array?

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

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

The arrays described in the 1st article are fixed arrays which means their length must be determined at compile-time. The 2nd article says that the size of an array is the length of the array multiplied by the size of an element

Article 2*

  1. How can you initialize an array?

You can do it element by element, or you can use an initialiser list by wrapping the desired values inside braces {}

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

sizeof() returns the size of an array in bytes

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

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

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

the extra variable will be placed in the memory lot that it would have been in if the array was large enough, so it can overwrite another variable and cause undefined behaviour

1 Like
  1. What is an array?
    An aggregate data type that can help us index

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

  3. What can you say about the size of an array?
    It multiplies the length with the element size.

Part 2

  1. How can you initialize an array?
    one of the ways is with an initializer list.

  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?
    sizeof(array)/sizeof(array[0])

  4. What happens when you try to write outside the bounds of the array?
    When not correctly defined it will cause errors

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?
[1]

3. What can you say about the size of an array?
At compile time we declare how big the array will be and the integers will be allocated

  1. How can you initialize an array?
    You can do it element by element or use an initializer list

  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?
    sizeof(array) / sizeof(array[0])

  4. What happens when you try to write outside the bounds of the array?
    It will store it in memory where the next element would have gone if it existed. This can cause undefined behavior and the system to possibly crash or overwrite another variable

2 Likes

1. What is an array?

  • An array is a data structure in c++ that holds a fixed number of items.
    2. Which index would you use to access the 2nd variable in an array?
  • I would use index [1]
    3. What can you say about the size of an array?
  • The size of an array is fixed at the time of declaration (although there are dynamic sized arrays which we will learn about later).
  1. How can you initialize an array?
  • To initialize an array with 0’s, simply declare the array like this: double array[100]{}. If you want to initialize with a specific value, you can use “fill_n” found in library : std::fill_n(maxTemp,365,100.01); this fills the array with the value of 100.01.
  1. How can you get the size of an array in bytes?
  • To get the size of an array in bytes, use “sizeof”: sizeof(array)
  1. How can you use the function sizeof in order to calculate the number of elements in an array?
  • You need to divide the output of “sizeof” by the number of bytes of each element in the array. For example, if your array stores 4-byte integers, you would divide the output of “sizeof” by 4. If you want to do this programatically, do this: numberOfElements = sizeof(array)/sizeof(int).
  1. What happens when you try to write outside the bounds of the array?
  • Here is where you run into undetermined behavior. You won’t get an error, but you may overwrite a position in memory that your program needs resulting in unpredictable behavior. I enjoyed the youtube video from May, 2018 describing the EOS vulnerablity that was identified and resulted from this very issue.
1 Like

1.An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
2. int array[1];
3. Arrays are blocks of static memory whose size must be determined at compile time.

  1. Elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. Ex.: int array[5]={1,2,3,4,5};
    2.One way​ to find the length of an array is to divide the size of the array by the size of each element (in bytes).
    `#include
    using namespace std;

int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}`
3. :point_up:
4.You will get undefined behavior.

1 Like

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.

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

[1]

What can you say about the size of an array?

For an array of length N, the array elements are numbered 0 through N-1. This is called the array’s range.


How can you initialize an array?

via use of an initializer list

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

Using algebra, we can rearrange this equation: array length = array size / element size. sizeof(array) is the array size, and sizeof(array[0]) is the element size, so our equation becomes array length = sizeof(array) / sizeof(array[0]). We typically use array element 0 for the array element, since it’s the only element guaranteed to exist no matter what the array length is.

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

int main()
{
int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 };
std::cout << “The array has: " << std::size(array) << " elements\n”;

return 0;

}

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

You get undefined behavior

1 Like

Part 1

  1. What is an array?

An array is an aggregate data structure that allows us to access many variables of the same type.

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

1

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

Size of an array generally refers to the amount of elements within the array. However, this is different from the sizeof( ) function, which (depending on the architecture of the computer) will produce a number corresponding to the byte size of the array. The calculation is as follows: # of elements * element size (in bytes).

Part 2

  1. How can you initialize an array?

Arrays can be initialized with curly brackets that contain nothing. This will set each element to 0 by default. Otherwise, they can be initialized element-by-element by manually accessing each element by subscript.

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

sizeof() function

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

sizeof(array)/sizeof(element)

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

Undefined behavior could occur!

1 Like

First Part

  1. An array is an aggregate data type that lets us access many variables of the same type through a single identifier.
  2. 1
  3. For an array of length N, the array elements are numbered 0 through N-1. This is called the array’s range. It could be fixed or dynamic.

Second Part

  1. int array[]{elements separe by ,}; or double or string array;
  2. sizeof(array);
  3. sizeof(array) / sizeof(array[0]
  4. 0
1 Like

What do you mean by 0? Would writing out of bounds return a zero value? :slight_smile:

1 Like

Part One

  1. An array is an aggregate data type that lets us access many variables of the same type through a single identifier.
  2. To access the second variable in an array, you would use the index 1. As in Javascript, indices for arrays in C++ begin with 0.
  3. The size of an array is either fixed or dynamic. A fixed array has a constant length; it cannot be changed. On the other hand, a dynamic array’s length can be changed.

Part Two

  1. You can initialize an array element by element, but that process is painful and time-consuming, especially as the array grows longer. A simpler method is to use an initializer list that includes all of the values you want in your array.
  2. To get the size of an array in bytes, use an initializer list after you have defined your array.
  3. You can use the function sizeof to calculate the number of elements in an array. This function multiplies the defined array length by the element size.
  4. When you try to write outside the bounds of an array, you end up with undefined behavior.

If something in my answers is not accurate, let me know. Thanks!

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

  2. nameOfTheArray[1] , index[1]

  3. Size of the array is defined at initialization (array length * data type size) and can not be changed (for static arrays).

part 2:

  1. via use of an initializer list.

  2. By using the sizeof() function.

  3. You use it by dividing the size of the array by the size of the type of element in the array.

  4. its an undefined behaviour- but still C++ will not stop you from doing this.

1 Like

You use sizeof to get the size of the array in bytes.

Once you have the size in bytes you can divide that with the size of the element type for example sizeof(array)\suzeof(array[0]). :slight_smile:

1 Like