Doom Slayer
Doom Slayer

Reputation: 7

Problems with special arrays in C++

I am learning c++ by myself, by solving problems which are designed for other programming languages. So I will asks many questions. I founded very interesting one, and I kinda lost.

I need to write a program which:

1. creates one of these special arrays (8x8):

a. diagonal matrix

b. low triangular matrix

c. high triangular matrix

d. symmetric matrix

2. fills it with random integer numbers in a range [-30..45];

3. displays the filled array

4. transforms array into vector

5. searches for user specified element in vector using linear search algorithm

6. sorts vector using one of these algorithms:

a. Bubble

b. Insertion

c. Selection

7. displays the sorted vector.

I already started to work on it, but I have some problems.

  1. I've got no idea how to create those matrices, I guess that's it have something to do with a for loop.

  2. I know how to generate random numbers, but have no idea about range.

  3. I can display array using cout function, but it does not look like a matrix.

  4. What is the best way to transform?

  5. How do I implement this search algorithm?

Here is my code, I just managed to implement sorting algorithms, and create a matrix with a random numbers. But I don't think that I did it in a right way.

#include <algorithm>
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
template<typename ForwardIterator>
void selectionSort(ForwardIterator begin, ForwardIterator end) {
    for (ForwardIterator i = begin; i != end; ++i)
        iter_swap(i, min_element(i, end));


}
template<typename Iterator>
void bubbleSort(Iterator first, Iterator last)
{
    Iterator i, j;
    for (i = first; i != last; i++)
    for (j = first; j < i; j++)
    if (*i < *j)
    {
        iter_swap(i, j);
    }
}

void insertion_sort(int arr[], int length) {
    int i, j, tmp;
    for (i = 1; i < length; i++) {
        j = i;
        while (j > 0 && arr[j - 1] > arr[j]) {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            j--;
        }//end of while loop

    }//end of for loop
}//end of insertion_sort.



int main()
{

    int method, matrixTYPE, arr[8][8]; 
    for (int i = 0; i < 8; i++)

    {

        arr[i][i] = (rand() % 44) + -30;

    }
    for (int i = 0; i < 16; i++)
    {
        cout << arr[i][i] << endl;
    }
    system("pause");



    return 0;

} 

Upvotes: 0

Views: 154

Answers (1)

jrok
jrok

Reputation: 55425

You need two nested loops to visit all the elements of a 2D-array:

for (int i = 0; i < 8; ++i)
    for (int j = 0; j < 8; ++j)
        arr[i][j] = 42;

Your first loop only assigns to elemets along the diagonal:

[X] [ ] [ ] [ ]
[ ] [X] [ ] [ ]
[ ] [ ] [X] [ ]
[ ] [ ] [ ] [X]

The second one goes way out of bounds.

Upvotes: 1

Related Questions