Whenever I run this code and enter a number over 500,000, the program crashes. Also is there away to make this more simple/efficient without using: vectors, multiplication, division and %. Thanks a lot!
#include <iostream>
using namespace std;
int get_primes(int array[], int num);
void sieve(int array[], int num);
void goldbach(int primes[], int nprimes, int num);
void show(int array[], int num);
int main()
{
int num;
cout << "Enter a number to calculate up to." << endl;
cin>>num;
if ( num < 2 )
return 0;
int array[num];
array[0]= array[1]= 0;
for ( int i= 2; i < num; ++i )
array[i]= i;
int nprimes = get_primes(array, num);
show(array, nprimes);
goldbach(array, nprimes, num);
return 0;
}
void show(int array[], int num)
{
for (int i=0; i<num; i++)
if (array[i] > 0)
cout << array[i] << " "<< endl;
cout << endl;
}
int get_primes(int array[], int num)
{
sieve(array, num);
int pos = 0;
for (int i = 2; i < num; ++i)
if (array[i] > 0)
array[pos++] = array[i];
return pos;
}
void sieve( int array[], int num )
{
for ( int i= 0; i < num; ++i )
{
if ( array[i] > 0 )
{
for ( int j = i+i; j < num; j += i )
{
array[j] = 0;
}
}
}
}
void goldbach(int primes[], int nprimes, int num)
{
int a;
for (int a = 4; a<=num; a+=2)
{
bool found = false;
int i, j;
for (i = 0; !found && i < nprimes && primes[i]; ++i)
for (j = 0; !found && j < nprimes && primes[i]; ++j)
{
found = a == (primes[i] + primes[j]);
if (found)
cout << a << '\t' << primes[i] << " + " << primes[j] <<endl;
}
if (!found)
cout << a << "\tnot found" << endl;
}
}
Saying int array[num] is saying "allocate num * sizeof(int) bytes from the stack."
So it might be that your stack is only one megabyte in size, and when you ask for more you hit an underflow condition.
Change
int array[num];
to
int* array = new int[num];
and change all the function arguments from using
int array[]
to
int* array
you will still be able to access the pointers normally like array[i].
I would recommend you to look up stack vs heap memory in C++ to understand why this works, and to read up on pointers too.
Related
I am having a tough time trying to follow the logic here as to why it is not working correctly
expected output :
1 5 6 8
any help is greatly appreciated
Update: I got selection sort and insertion sort mixed up
OUTPUT:
unaltered array
5 8 1 6
1 -858993460 -858993460 6
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "SelectionSORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "SelectionSORT2\n";
}
cout << "SelectionSORT3\n";
}
#include <iostream>
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
UPDATE
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "Selection SORT1\n";
int I;
for (i = 0; i < n ; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = i;
int j;
for (j = i + 1;j < n ;j++)
{
std::cerr << j << ' ' << firstIndex << '\n';
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
swap(arr[i], arr[firstIndex]);
}
cout << " \n";
}
cout << " \n";
}
#include <iostream>
#include "BubbleSort.h"
#include "InsertionSort.h"
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
unaltered array
5 8 1 6
SelectionSORT1
1 0
2 0
3 2
2 1
3 2
3 2
5 6 1 8
You are using the selection sort method not the insertion sort method.
Bit in any case the function is incorrect
void InsertionSort(int *arr,int n)
{
cout << "INSERTION SORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "INSERTION SORT2\n";
}
cout << "INSERTION SORT3\n";
}
For starters it will not sort an array that has two elements due to this for loop
for (i = 0; i < n - 2; i++) //-1 ||-2//
Secondly, the variable firstIndex is not initialized by a value of the index i
firstIndex = arr[i];
So the condition in this if statement
if (arr[j] < arr[firstIndex])
does not make a sense.
Thirdly this inner for loop
for (j = i + 1;j < n - 1;j++)
ignores the last element of the array.
Fourth, this unconditional call of the function swap within the inner for loop
swap(arr[i], arr[firstIndex])
also does not make a sense.
The function can look the following way
void SelectionSort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[min] )
{
min = j;
}
}
if ( min != i ) swap( a[i], a[min] );
}
}
And in main the variable size should have the type size_t - the type of the value of the expression with the operator sizeof
const size_t size = sizeof(array) / sizeof(array[0]);
And instead of the magic number 4 in for loops in main you should use the named constant size or you could use the range-based for loop as
for ( const auto &item : array )
{
cout << item << ' ';
}
cout << endl;
If you indeed mean the insertion sort method then a corresponding function can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Thank you all for your help
I got it to work like this
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void InsertionSort(int arr[],int n)
{
int i;
for (i = 0; i < n ; i++)
{
int firstIndex,j;
firstIndex = i;
for (j = i + 1;j < n ;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
}
swap(arr[i], arr[firstIndex]);
}
}
The following is C++:
std::set<int> sorted_array({ 5,8,1,6 });
If you have duplicates and need to keep them, use:
std::multiset<int> sorted_array({ 5,8,1,6 });
Done. One line.
I am running project called Horse Board Game. When it got almost done, it happened an error at the end of the execution part. The error is:
Run-Time Check Failure #2 - Stack around the variable 'board' was corrupted.
Where is the mistake here? Everything seems to work properly, only that error occurs.
#include <iostream>
#include <ctime>
#include <Windows.h>
using namespace std;
void printHorizontalLine(int size) {
for (int i = 0; i < size; i++) {
cout << " -----------";
}
cout << "\n";
}
void printVerticalLine(int size) {
cout << "|";
for (int i = 0; i < size; i++) {
cout << " |";
}
cout << "\n";
}
void displayBoard(int size, char board[50][50]) {
for (int i = 0; i < size; i++) {
printHorizontalLine(size);
printVerticalLine(size);
cout << "|";
if (i % 2 == 0) {
for (int j = 0; j < size; j++) {
cout << " " << board[i][j] << " |";
}
}
else {
for (int j = size - 1; j >= 0; j--) {
cout << " " << board[i][j] << " |";
}
}
cout << "\n";
printVerticalLine(size);
}
printHorizontalLine(size);
}
void init_board(char board[50][50], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = ' ';
}
}
}
void enteringPlayerName(char name[], int n) {
for (int i = 0; i < n; i++) {
cout << "Player " << i + 1 << " enter name: " << "\n";
cin >> name[i];
}
}
void beginningPos(int n, int pos[]) {
for (int i = 0; i < n; i++) {
pos[i] = -1;
}
}
void rollDice(int max, char board[50][50], int pos[], char name[], int size, int n, int cur) {
int step = rand() % max + 1;
cout << name[cur] << " roll " << step << "\n";
if (step + pos[cur] > size * size - 1) {
cout << "Cannot move forward\n";
}
else {
pos[cur] += step;
for (int i = 0; i < n; i++) {
if ((pos[cur] == pos[i]) && (i != cur)) {
pos[i] = -1;
cout << name[i] << " is kicked to the Start!!\n";
}
}
}
}
void updatingBoard(char board[50][50], char name[], int pos[], int n, int size) {
init_board(board, size);
for (int k = 0; k < n; k++)
{
int x, i, j;
x = pos[k];
i = x / size;
j = x % size;
board[i][j] = name[k];
}
}
char playGame(int max, int n, int size, char board[50][50], int pos[], char name[], int finish_point) {
char winner = ' ';
int cur_turn = 0;
while (winner == ' ') {
rollDice(max, board, pos, name, size, n, cur_turn % n);
updatingBoard(board, name, pos, n, size);
displayBoard(size, board);
if (pos[cur_turn % n] == finish_point) winner = name[cur_turn % n];
cur_turn++;
}
return winner;
}
int main() {
int size, n;
cin >> size;
cin >> n;
const int MAX = 50;
int max = 3;
int pos[200];
char name[10];
char winner = ' ';
char board[MAX][MAX];
int finish_point = size * size - 1;
srand(time(0));
enteringPlayerName(name, n);
init_board(board, size);
beginningPos(n, pos);
winner = playGame(max, n, size, board, pos, name, finish_point);
if (winner == ' ') cout << "Tie game";
else cout << winner << " is the winner";
return 0;
}```
When I set size to 4 and n to 2 as recommended in the comments section, then the line
board[i][j] = name[k];
in the function updatingBoard causes a buffer underflow.
The first time that line is executed, i has the value 0 and j has the value 0, which is ok, but the second time that line is executed, i has the value 0 but j has the value -1. This is obviously wrong, because board[0][-1] is accessing the array out of bounds.
That is the reason for the error message that you are receiving.
You can easily see this by running your program line by line in a debugger.
#include <iostream>
using namespace std;
int list [50];
void bsort(int list[], int n);
void printArray(int list[], int n);
int main ()
{
for (int i = 100; i > 50; i--)
{
list[i] = i;
cout << list[i] << endl;
}
int n = sizeof(list) / sizeof(list[0]);
bsort(list, n);
printArray(list, n);
return 0;
}
void bsort(int list[], int n)
{
int i, j;
for (i = 0; i <= 48; i++)
{
for (j = i+1; j <= 49; j++)
{
int temp;
if (list[i] > list[j])
{
temp = list[i];
list[i] = list [j];
list[j] = temp;
}
}
}
}
void printArray(int list[], int n)
{
for (int i = 0; i < n; i++)
cout << list[i] << " ";
cout << endl;
}
I'm in an intro-level computer science course and I am currently trying to write a program that calls the function 'bsort' to arrange the elements of the array 'list' in increasing order but my output is 49 zeros and I am not sure why? My professor wanted us to initialize the array 'list' starting at 100 and ending with 51 (in decreasing order).
Your initialisation loop is incorrect. Try like this
for (int i = 0; i < 50; i++)
{
list[i] = 100 - i;
cout << list[i] << endl;
}
Your version did list[100] = 100, list[99] = 99, etc but the array only has size 50.
When I run the following only the large numbers come out but, the numbers for "Multiples of the minimum elements" doesn't show.
I can't see what's wrong with the code yet. Advice appreciated.
int A[15];
void fill(int arr[], int n, int left, int right)
{
for (int i = 0; i < n; i++)
arr[i] = rand() % (right - left + 1) + left;
}
void output(int arr[], int n, int w)
{
for (int i = 0; i < n; i++)
{
cout << setw(w) << arr[i];
}
cout << endl;
}
int findMinElem(int arr[], int n)
{
int minelem = arr[0];
for (int i = 0; i < n; i++)
{
if (arr[i] % minelem == 0) minelem = arr[i] ;
return true;
}
return false;
}
int main()
{
int n = 15;
fill(A, n, 0, 50);
output(A ,n , 15);
if (findMinElem(A, n ))
cout << "Multiples of the minimum elements =\n";
else
cout << "No multiples of the minimum element elements\n";
system("pause");
return 0;
}
Here's my code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void buildArray(int arr[], int size) {
srand(time(NULL));
for (int i = 0; i < size; ++i) {
arr[i] = rand() % 100 + 1;
}
}
void showArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << i << arr[i] << " ";
}
}
void curveArray(int arr[], int size, int curve) {
for (int i = 0; i < size; ++i) {
arr[i] += curve;
}
}
int maxNum(int arr[], int size) {
int maxnum = arr[0];
int position = 0;
for (int i =1; i < size; ++i) {
if (arr[i] > maxnum ) {
maxnum = arr[i];
position = i;
}
}
return position;
}
int minNum(int arr[], int size) {
int minnum = arr[0];
int position = 0;
for (int i =1; i < size; ++i) {
if (arr[i] < minnum) {
minnum = arr[i];
position = i;
}
}
return position;
}
int main()
{
const int size = 10;
int arrayx[size];
buildArray(arrayx, size);
showArray(arrayx, size);
//curveArray(arrayx, size, 5);
//showArray(arrayx, size);
int maxVal = maxNum(arrayx, size);
cout << endl << endl << maxVal;
int minVal = minNum(arrayx, size);
cout << endl << endl << minVal;
return 0;
}
Whenever I try to run this code it generates a random array (as it's supposed exactly) but then when I use the functions to get the Max and Min Values it generates random number so here's the output when I run it
http://imageshack.com/a/img27/725/4jv9.png
This is from a C++ practice video but It works with the tutor but not with me and it's almost the same code!!
You are returning position of Max and Min value from the function, not the actual max and min values. It should be
return arr[position];
instead of
return position;
Your code returns positions of min and max values. To take values use
int maxVal = arrayx[maxNum(arrayx, size)];
cout << endl << endl << maxVal;
int minVal = arrayx[minNum(arrayx, size)];
cout << endl << endl << minVal;
also your showArray is incorrect. Change it to
void showArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
}