Hello guys, I'm new to C++, the following code is a homework assignment and the compiler that I'm using is codeblocks' GNU compiler. When i try to run the code below, using the random number option and setting the length of the haystack to 13 or bigger (i.e. length>=13), the program just crashes and the computer pops out the "Windows is searching for a solution..." window. The program runs perfectly for length <=12 though, which is why I'm really confused. Help is much appreciated.
Put the code you need help with here.
//Needle in a haystack.
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
usingnamespace std;
int main()
{
//basic description
cout << "This project aims to find a needle in a haystack." << endl;
cout<<"We define a haystack as a random ordered 1-line array of numbers."<<endl;
cout<<"We define a needle as an element such that all elements after the needle is smaller than or equal to in "<<endl<<"value to the needle."<<endl;
cout<<"Please enter length of the haystack."<<endl;
//length refers to the size of the array/haystack
longint length;
cin>>length;
srand(time(NULL));
//haystack is the array of size length
//haystack[1][length] stores the elements
//haystack[2][length] stores the max
//haystack[3][length] stores the truth check if an element is a needle
longint haystack[3][length];
cout<<"Would you like the haystack to be randomly generated? (1/0)"<<endl;
int option;
cin>>option;
cout<<"What is the maximum element permitted?"<<endl;
longint max2;
cin>>max2;
//i is the loop counter for the 'for' loop.
longint i;
if(option==1){
for(i=1;i<=length;i++){
haystack[1][i-1]=rand()%(max2+1);
}
}
else{
for(i=1;i<=length;i++){
cout<<"Enter the "<<i<<" number of the haystack."<<endl;
cin>>haystack[1][i-1];
}
}
cout<<"This is the haystack:"<<endl;
//loop to display the contents of haystack.
for(i=1;i<=length;i++){
cout<<haystack[1][i-1]<<" ";
}
cout<<endl<<endl;
//last element is defined to be a needle
haystack[3][length]=true;
longint max1;
max1=haystack[1][length-1];
for (i=1;i<=length;i++){
cout<<"max1 = "<<max1<<endl;
if(haystack[1][length-i]>=max1){
haystack[3][length-i]=true;
max1=haystack[1][length-i];
cout<<"Term "<<length-i+1<<" = "<<haystack[1][length-i]<<" is a needle."<<endl;
}
else{
haystack[3][length-i]=false;
cout<<"Term "<<length-i+1<<" = "<<haystack[1][length-i]<<" is not a needle."<<endl;
}
}
cout<<endl<<endl<<"The following terms are needles:"<<endl;
//display loop
for(i=1;i<=length;i++){
if(haystack[3][length-i]==true){
cout<<"The "<<length-i+1<<" term = "<<haystack[1][length-i]<<endl;
}
}
return 0;
}
Thanks for your assistance. But the problem has been solved. haha. The problem was that I used the wrong dimensions for the array. I defined a 3xlength array, but used the 4th row of the array as I forgot the row number starts at 0. thanks anyways