Arrays in C++ - Reading Assignment

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

  2. Index 1.

  3. The size of an array is the array length multiplied by element size.

  4. You can initialise an array via the use of an initialiser list, or zero initialisation.

  5. sizeof(array)

  6. array size= sizeof(array)/sizeof(array[0])

  7. undefined behaviour

1 Like

Part 1

  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?
    You would use the index 1 as the index starts counting at 0. eg. array[1].

  3. What can you say about the size of an array?
    The size of an array object is always equal to the second template parameter used to instantiate the array template class (N).

Part 2

  1. How can you initialize an array?
    You would enter the values into the curly brackets ({}), separating the values with commas. Eg. array[5]{1, 2, 3, 4, 5}

  2. How can you get the size of an array in bytes?
    By using the sizeof operator.

  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?
    C++ does not do any checking to make sure that your indices are valid for the length of your array. When this happens, you will get undefined behaviour – For example, this could overwrite the value of another variable, or cause your program to crash.

1 Like

I usually consider the size as the size in bytes and length as the number of elements.

What happened to the rest of your homework? :wink:

Thank you for the help! And yes I had to go afk so I just replied to save the work I had done so far.

Reading Assignment: Arrays in C++

Part 1

  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? To access the second element of an array, we use the array name followed by the subscript operator, being the number “1” as all arrays start counting at “0”. In other words, it would go like this… arrayName[1]
  3. What can you say about the size of an array? Fixed arrays (arrays whose lengths are known at compile time) are used to allocate multiple variables of the same type.

Part 2

  1. How can you initialize an array? An array is initialized by naming the identifier of the array, defining the quantity or elements to be within the array within [] brackets (this can also be left empty), and then listing the elements within () separated by commas.
  2. How can you get the size of an array in bytes? The std::size() function from the header can be used to determine the length of arrays.
  3. How can you use the function sizeof in order to calculate the number of elements in an array? “…by dividing the size of the entire array by the size of an array element.”
  4. What happens when you try to write outside the bounds of the array? The result is undefined behavior by the program. “For example, this could overwrite the value of another variable, or cause your program to crash.”
1 Like
  1. Array is kind of like a list of variables of the same type. You predefine its category.

  2. array[1]

  3. it is the index of the last variable. You can pre-set it in the square brackets or leave it empty.

  4. doing it row by row or simply int prime[5] {2, 3, 5, 7, 11}

  5. sizeof(array);

  6. Divide the size of array by the size of any array element - sizeof(array)/sizeof(array[0])

  7. Undefined (dangerous) behaviour.

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. array[1]

  3. arrays can store large amounts of data.

  4. initialize an array - they are not initialized when created, but after using the initializer list method within braces, can also be initialized to 0 i.e. { }

  5. size in bytes - use the sizeof operator i.e. sizeof(array)

  6. It will be written in memory where the missing element would have been, leads to undefine behavior and possibly crash the program

1 Like

First reading:

  1. What is an array?
    An array is an aggregate data type that can store 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 second variable in an array is indexed as [1].

  3. What can you say about the size of an array?
    The size of an array is the number of variables contained in the array. A fixed size array has its size set at declaration and that size cannot be changed after the array is instantiated.

Second reading:

  1. How can you initialize an array?
    An array in C++ can be initialized by means of an initializer list in the form of array_type array_name[size]{value1, value2, ….}.

  2. How can you get the size of an array in bytes?
    The size of an array in bytes can be calculated by the sizeof() operator.

  3. How can you use the function sizeof in order to calculate the number of elements in an array?
    The number of elements in an array can be calculated by the size of the entire array (sizeof(array)) divided by the size of an individual array element, usually the one of index 0 (sizeof(array[0]).

  4. What happens when you try to write outside the bounds of the array?
    When value is assigned to an element outside the bounds of an array, undefined behaviour or compiler error may result.

1 Like

PART 1

  1. An array is an aggregate data type that allows us to access many variables of the same data type throughout a single identifier.

  2. To access the second variable in an array we use index [1].

  3. The size of a fixed array is determined by the programmer and must be known at compile time. Dynamic arrays allow us to vary the length of the array depending on how many elements are required.

PART 2

  1. To initialize an array in C++ we can either do it element-by-element, or by using an initializer list.

  2. To get the size of an array in bytes we use the sizeof(array) function.

  3. We can use the sizeof function to determine the number of elements in an array by dividing the size of the entire array by the size of an element.

  4. When the programmer tries to write outside the bounds of an array, the result is undefined behavior.

1 Like

1. What is an array?

A data structure where we can store multiple values and access them via their index (position) in the array.

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?

It can either be of fixed length or a dynamic length. A fixed length array is one where the size is known at compile time. Whereas a dynamic array’s length can be set at runtime.

  1. How can you initialize an array?

Example 1:

int numbers[4];
numbers[0] = 1;
numbers[1] = 8;
numbers[2] = 4;
numbers[3] = 2;

Example 2:

int numbers[4]{1,8,4,2}

Example 3:

int numbers[]{1,8,4,2}

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

via sizeof().

  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?

You get undefined behavior such as overwriting the value of another variable or cause your program to crash.

1 Like
  1. An array is an aggregate data type that allows us to store and access multiple values of the same type.
  2. The [1] index
  3. The size of an array can be fixed length or dynamic.

  1. As an example, you can initialize an array like this: int myArray[3] {7,7,7};
  2. cout << sizeof(array)
  3. Number of elements = sizeof(array) / sizeof(array[0]);
  4. This will generate an error.
1 Like
  1. What is an array?
    data set containing similar types of elements

  2. Which index would you use to access the 2nd variable in an array?
    the index is (1) so name[1]; where name is the name of the array

  3. What can you say about the size of an array? The size of the array must be known at compilation time. It is the length of the array

Think about the following questions while reading:

  1. How can you initialize an array?
    there are several ways either using empty brakets to initialize to zero(0), use a list within brackets for each element in the array or individual indexing and setting values

  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]); = size of array / sizeof array element

  4. What happens when you try to write outside the bounds of the array?
    It will allocate the space like if it was there but you may get undefined behavior. May over-write existing value or cause program to crash.

Questions at End of Chapter

  1. Declare an array to hold the high temperature (to the nearest tenth of a degree) for each day of a year (assume 365 days in a year). Initialize the array with a value of 0.0 for each day.

double temperature[365]{0.0};

  1. Set up an enum with the names of the following animals: chicken, dog, cat, elephant, duck, and snake. Put the enum in a namespace. 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.

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

#include <iostream>

using namespace std;

enum AnimalNames
{
chicken,
dog,
cat,
elephant,
duck,
snake,
max_animals

};

int main()
{
    cout << "Hello world!" << endl;

    int animalegs[max_animals]{2,4,4,4,2,0};
    cout<<"A chicken has only  "<<animalegs[chicken]<<"  legs"<<endl;
    cout<<"A dog has  "<<animalegs[dog]<<"  legs"<<endl;
    cout<<"A cat has  "<<animalegs[cat]<<"  legs"<<endl;
    cout<<"A snake has  "<<animalegs[snake]<<"  legs"<<endl;
    cout<<"A duck has only "<<animalegs[duck]<<"  legs"<<endl;
     cout<<"An elephant has  "<<animalegs[elephant]<<"  legs"<<endl;

    return 0;
}

// To do this for JavaScript it can be done like this;

var animals = [{chicken: 2}, {cat: 4},{dog: 4},{elephant: 4}, {duck: 2}, {snake: 0}];

console.log("number of legs on a chicken = " , animals[0].chicken);
console.log("number of legs on a cat = " , animals[1].cat);
console.log("number of legs on a dog = " , animals[2].dog);
console.log("number of legs on a elephant = " , animals[3].elephant);
console.log("number of legs on a duck = " , animals[4].duck);
console.log("number of legs on a snake = " , animals[5].snake);

// What do you like the best. With Javascript I like that you can put different types of elements in the array, function, variables, objects, booleans, and I can call a function in the array by using its location and invoke it by using a name found in the same array. It is a lot more flexible.

//Copy this array into your console and run:

var arr = [
1, false,
{
name: "Imhotep”,
address: "1003 Main Street"
},
function(name){
var greeting= "hello ";
console.log(greeting + name);
},
"hello”

];
//Now my array contains numbers, booleans, objects and functions and a string. I can call any element I wish by starting with zero as first element in array:

console.log([0]);
console.log([1]);
console.log([2]);
console.log([3]);
console.log([4]);

//or I can just call the array

console.log(arr);

//or I can call the function in the array by first calling the function as above and then invoking the function by using parenthesis and calling the name I want to use in the function.//

arr[3](arr[2].name);

However, is there a way to enum each element and give it a name within the array. I do like this feature where you can give each location a name and then call that animal name and it will give the corresponding number of legs instead of having to remember the location of the animal so you can call on its name.

It would be nice to compare the two programming languages when we look at how different functions work like loops, if/else, arrays, functions, etc.

Here are two other methods of printing the number of legs for each type of animal using JavaScript. Again if you are using an array in java Script you have to remember the location of the animal in the array. I could not figure out another way to do this. But If I were using functions then I would name the function the type of animal and then just console.log the number of legs for that animal. See below

var animallegs = [function chicken(){console.log("A chicken has 2 legs")},function cat(){console.log("A cat has four legs")}, function dog(){console.log("A dog has four legs")}, function elephant(){console.log("A elephant has four legs")},function duck(){console.log("A duck has two legs")},function snake(){console.log("A snake does not have legs")}];
   
animallegs[0]();  // call chicken in location 1 and evoke
animallegs[1](); // call chicken in location 1 and evoke
animallegs[2]();  //call chicken in location 1 and evoke
animallegs[3]();  //call chicken in location 1 and evoke
animallegs[4]();  //call chicken in location 1 and evoke
animallegs[5]();  //call chicken in location 1 and evoke
    
//The best way I can figure to do this in Java Script is to set up a function for each animal and then simply call the animal function to print the number of legs for that particular animal.  See below...

 function chicken(){console.log("A chicken has 2 legs  ")};  
    
 function cat(){console.log("A cat has four legs  ")};
 
 function dog(){console.log("A dog has four legs  ")};
 
 function elephant(){console.log("A elephant has four legs  ")};
 
 function duck(){console.log("A duck has two legs  ")};
 
 function snake(){console.log("A snake does not have legs  ")};
    
console.log(chicken,"  ",cat,"  ",dog,"  ",elephant,"  ",duck,"  ",snake);
    
    chicken();
    cat();
    dog();
    elephant();
    duck();
    snake();
3 Likes

Part 1
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?
To access the second variable in an array you would use the scriptOperator[1].
3. What can you say about the size of an array?
The size of an array is either fixed or dynamic. It can be deduced by multiplying the array length and the element size.
Part 2
1. How can you initialize an array?
You initialize an array by using an initializer list. Eg. int prime[5]{2,3,5,7,11};
2. How can you get the size of an array in bytes?
You can get the size of an array in bytes by using the sizeof() on the array.
3. How can you use the function sizeof in order to calculate the number of elements in an array?
A way you can calculate the number of elements in an array is by dividing. Eg. sizeof(array)/sizeof(array[0])
4. What happens when you try to write outside the bounds of the array?
When you write outside the bounds of an array you get undefined behavior, which could overwrite the value of another variable or could cause your program to crash.

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

  2. To access the 2nd variable in an array we will use index 1 [1]

  3. The size of an array depends on the type. Fixed arrays have a fixed length that cannot be changed and in dynamic arrays the length can be set at runtime and can be changed.

  4. A way to “initialize” an array is, to do it element by element or to use an initializer list.

  5. We can get the size of an array in bytes by using the sizeof operator.

  6. We can divide the total size of the array by the size of the array element :
    sizeof (array) / sizeof (array [0])

  7. If we write outside the bounds of the array we will get undefined behavior it could overwrite the value of another variable, or crash the program.

1 Like

Part I
1.) Arrays are aggregate data types which allow us to access many variables of the same type through a single identifier.
2.) To access the 2nd variable in an array you need to use the 1 index, since the first variable’s index is 0.
3.) Array size is its length * data type size

Part II
1.) To initialize an array you use an initializer list.
2.) Size of an array is array length times element size, or use sizeof(array).
3.) Dividing these two functions: sizeof(array) / sizeof(int)
4.) This results in undefined behavior - it gets stored as the next element had it existed, or the program could crash.

1 Like
  1. An array is an aggregate or related data type that lets us access many variables of the same type through a single identifier. Square brackets used to tell the compiler that this is an array variable.

  2. In order to access a specific element in an array you would use a subscript of index so that the compiler knows the element we want. The array starts with element 0; so, in order to access the 2nd variable we would type the array name followed by [1]. Example: arrayName[1]

  3. You can have fixed arrays where the size of an array is known at compile time and dynamic arrays where the size of an array can be set at runtime. Best practice is to have the size of an array known at compile time. Example. int array[5]

  4. You can initialize an array one at a time; however, a convenient way to initialize entire arrays are with the use of an initializer list.

  5. You can get the size of an array in bytes by using the sizeof operator which will multiply the number of elements in an array by the byte size of an integer which is usually 4 bytes.

  6. The sizeof function will give you the total number of bytes in an array. Given that an integer is 4 bytes you can divide the number given to you by the sizeof function by 4 and determine the total number of elements in an array. Ex. Number of elements = sizeof(array) / sizeof(array[element 0])

  7. When you try to write outside the bounds of an array you will get undefined behavior as there is no location in memory allotted for that particular element. Given that, you could get a garbage number, the correct number or the program could crash. Anything could happen.

1 Like
  1. What is an array?
    Many variables that is stored in 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?
    An array is fixed by using brackets. The size of an array is the total amount of variables inside of it.

  4. How can you initialize an array?
    you create an array name [] and put the total amount of variables there are. Then you can put this
    { 2, 7, 8, 5, 1 }; to set the list in one line or multiple lines.

  5. How can you get the size of an array in bytes?
    By using
    sizeof(arrayname);
    or to get specific element use
    sizeof(arrayname[0]);

  6. How can you use the function size of in order to calculate the number of elements in an array?
    By dividing the entire array by the first array element.

  7. What happens when you try to write outside the bounds of the array?
    Your program wont wont, it’s an und behavior.

1 Like
  1. It is an aggregate data type, that lets us access many variables of the same type through a single identifier.
  2. index [1]
  3. There are both fixed and dynamic arrays. Fixed arrays have fixed sizes.
  4. Via the use of an initializer list:
    int prime[5]{2,3,5,7,11}
  5. sizeof(array)
  6. sizeof(array)/sizeof(array[0])
  7. We get undefined behaviour, it can crash the program
1 Like
  1. What is an array?
    a data type that lets us access many variables of the same type
    using 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?
    arrays have a fixed length that cannot be changed by a user at runtime, they must be
    input at compile time.

  4. How can you initialize an array?
    you can initialize each element individually, or use an initializer list

  5. How can you get the size of an array in bytes?
    using the std::size(array) function from the header, and multiply it by the
    size of each element. integers are often 4 bytes

  6. How can you use the function sizeof in order to calculate the number of elements in an array?
    you can find the size of an integer using std::cout <<sizeof(array)

  7. What happens when you try to write outside the bounds of the array?
    you end up with undefined behavior

1 Like

Hi All, I have a question here, based on the reading material in https://www.learncpp.com/cpp-tutorial/arrays-part-i/

It is doing an enum declaration like this:
enum Weekday
{
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday,

maxWeekday

};

I don’t get the syntax, what is maxWeekday ? It does not look like that it is an enumerator.

I see that it is being passed to an array int numberOfLessonsPerDay[maxWeekday]{};

Can somebody explain what is going on here ?

The full code is here:

int numberOfLessonsPerDay[7]{}; // Ok

// using a constexpr symbolic constant
constexpr int daysPerWeek{ 7 };
int numberOfLessonsPerDay[daysPerWeek]{}; // Ok

// using an enumerator
enum Weekday
{
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday,

maxWeekday

};
int numberOfLessonsPerDay[maxWeekday]{}; // Ok

// using a macro
#define DAYS_PER_WEEK 7
int numberOfLessonsPerDay[DAYS_PER_WEEK]{}; // Works, but don’t do this (use a constexpr symbolic constant instead)