Home


Lesson 2

Statical arrays, I/O

Arrays: how to store multiple values?

Task 0

Create an integer array, which size will be determined by a preprocessor constant.

Assign value of each element as value of cell's index.


#include <iostream>
#define constant_size 10

int main() {
    std::cout << constant_size << std::endl;
}
            
Example: using arrays

// creating statical array
int integers[40];
// assigning values
integers[0] = 10;
// reading value
int last = integers[39];
                
Task 1

Check C++ array access mechanism:

  1. read a value outside bounds of the array
  2. read uninitialized value of array element
Task 2

Write a method, which will return a number from range [1,100]. Use the code below and % operator.

Check, how programs changes on srand method invoking.


#include <cstdlib>
#include <iostream>
#include <ctime>

using std::srand;
using std::time;
using std::rand;

int main() {
    // setting global seed
    srand(time(nullptr));
    // randomizing in range: [0,RAND_MAX]
    std::cout << "[0, " << RAND_MAX << "]: " << rand() << std::endl;
}
            
Task 3

There is a 3D point structure (x,y,z). Write a program which:

  1. Try to create a statical array of 3D points with size given by user.
  2. Fulfill the array with random values.
  3. Save results to a file with extension csv.

Try decomposite your program with writing own methods.


#include <iostream>
#include <fstream>
#include <cstdlib>

int main() {
    std::fstream file;
    file.open("results.csv", std::ios::out);
    if (!file.good()) {
        std::cout << "Error" << std::endl;
        return 1;
    }
    file << "lorem ipsum";
    file.close();
    std::cout << "Success" << std::endl;
}
            
Mode Meaning
in Opening a file for reading
out Opening a file for writing
binary File won't be load as text.
app New data will be append at the end of a file.
trunc Truncating content of file at the beginning
Task 4

Create own database for one entity.

  1. Application should ask user, if he wants execute one of the action:

    • Adding a record
    • Deleting a record
    • Override a record
    • Read a record (by id)
  2. Database should be stored in RAM.
  3. After each modification of data, database should store all changes in a file.