C++ recursive linear search fails [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am writing this simple code of linear searching using recursion, but still getting some problem.
Always getting false as return value.
The code is as follows:
main()
{
int arr[10] = {12,13,75,23,6,45,90,41,61,56};
int i, j, num;
cout<<" Find number :- ";
cin>>num;
bool check = find(arr, num, 0, 10);
cout<<" check = "<<check<<endl;
system("PAUSE");
return 0;
}
bool find(int arr[], int key, int first, int size)
{
if(first > size)
return false;
else
{
if(arr[first] == key)
return true;
else
find(arr, key, first+1, size);
}
}

Try to add return before to launch the function
bool find(int arr[], int key, int first, int size)
{
if(first > size)
return false;
else
{
if(arr[first] == key)
return true;
else
return find(arr, key, first+1, size);
}
}

Two things:
if(first > size)
return false;
This should be >= not >, or else you'll end up trying to access past the bounds of the array, below.
if(arr[first] == key)
return true;
else
find(arr, key, first+1, size);
Here, you need to remember to explicitly return the value of find(). Otherwise you'll just get a garbage return value instead (which coincidentally happens to be false).

I think it's simple enough
first of all you have to check till 9th index only because the index starts from 0 and ends at 9.
otherwise it may cause run-time error.
take care of declaration of functions and and header files.

Related

I have made a program to implement stack but it is not working properly [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
The code is not throwing any error but it is not taking the values that we pass in the enqueue function.
Here is the code:
#include <bits/stdc++.h>
#include <climits>
using namespace std;
struct Queue{
int *arr;
int front , rear;
int cap;
Queue(int c){
cap = c;
front = -1;
rear = -1;
arr = new int[cap];
}
void enqueue(int x){
if(rear == cap-1){
cout<<"The array is full";
}
rear++;
arr[rear] == x;
cout<<arr[rear]<<endl;
if(front == -1){
front = 0;
}
}
int dequeue(){
int data;
if(front == -1){`your text`
cout<<"Array is empty";
return INT_MIN;
}
data = arr[front];
arr[front] = 0;
if(front == rear){
front = rear = -1;
}
else{
front++;
}
return data;
}
};
int main() {
Queue q(3);
q.enqueue(24);
q.enqueue(30);
q.enqueue(42);
cout<<q.dequeue();
return 0;
}
the enqueue function is taking some garbage value instead of the integer value that we are passing in the argument.
Hi and welcome to Stackoverflow.
The problem is that you ignored your compiler warnings. Under https://godbolt.org/z/Pn1Mf115T i have thrown your code in an online compiler and it tells me/you:
<source>:20:19: warning: equality comparison result unused [-Wunused-comparison]
arr[rear] == x;
~~~~~~~~~~^~~~
<source>:20:19: note: use '=' to turn this equality comparison into an assignment
arr[rear] == x;
^~
=
1 warning generated.
Compiler returned: 0
So the compiler tells you that you comparing instead of assigning the values. Thats the reason why your queue takes garbage values, it just never gets data assigned and the output is the uninitialized memory from your C-style array.
Rule of thumb: Do not ignore compiler warnings.

Can some one help debug this C++ code? Don't really understand what the error messages points to [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
bool if_duplicate (const vector <Assignment> & assgt, const string & ID) {
int i;
for (i=0; i<assgt.size();i++) {
if (assgt[i].getId() == ID) {
return true;
}
else {
return false;
}
}
}
error message i keept getting: warning: control reaches end of non-void function [-Wreturn-type]
285 | }
It is a warning not an error.
The warning says that you are have no return from your function in the case the for loop won't run.
Try this:
bool if_duplicate (const vector <Assignment> & assgt, const string & ID) {
int i;
for (i = 0; i < assgt.size(); i++) {
if (assgt[i].getId() == ID) {
return true;
}
else {
return false;
}
}
return false;
}
I also think that your function doesn't really do what you want. Did you mean to write this?
bool if_duplicate (const vector <Assignment> & assgt, const string & ID) {
int i;
for (i = 0; i < assgt.size(); i++) {
if (assgt[i].getId() == ID) {
return true;
}
}
return false;
}
Your code is wrong (buggy). The complete function you can write with this one line. Test, you'll have same result:
bool if_duplicate (const vector <Assignment> & assgt, const string & ID) {
return (assgt.size() != 0) && (assgt[0].getId() == ID);
}

in c++ i get the error: cannot convert 'bool' to 'bool*' in return [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Im new to c++ and im trying to get a bool* function with a dynamic array as its parameter and its size to return true or false when none of them is zero but im getting an error: cannot convert 'bool' to 'bool*' in return.
bool* noneZero(int *zero, int N) {
int PL = 0;
for (int i = 0; i < N; i++) {
if (i == 0) {
PL++;
}
}
if (PL == N)
return false; //cannot convert 'bool' to 'bool*' in return
else
return true; //cannot convert 'bool' to 'bool*' in return
}
int main(int argc, char** argv) {
int *z=new int[5]{0,0,0,0,0};
cout << noneZero(z,5);
}
Also the question is how the teacher gave it to me. we dont work with vectors. Basically i have to return false when all of the numbers in my dynamic array are 0 and true when they arent. My question is why i get an error: cannot convert 'bool' to 'bool*' in return
Frankly, there are many problems in your code and I suggest to start from scratch.
First, dynamic arrays in C++ are std::vector. You need a good reason to use something else.
Next, your function is too complicated. You need not count the number of zeros if all you want is to check if there is none or at least one:
bool noneZero(const std::vector<int>& in) {
for (size_t i=0; i< in.size(); ++i) { // a vector "knows" its size !
if ( in[i] == 0 ) return false; // no need to search further
}
return true;
}
int main() {
std::vector<int> z{1,2,3,4,5};
bool x = noneZero(z);
if (x) std::cout << "there is no 0 in the vector\n";
for (const auto& e : z) {
std::cout << e << " ";
}
}
A std::vector manages the memory for you, ie no need for manual new or delete. It is not clear why you use the pointer returned from the function as if it points to an array (it does not and your code has undefined behavior). I added a loop that prints the vectors elements.
Problem:
A bool* must return a pointer a pointer to a bool, not a bool itself.
You're checking the value of i, not the values of the array.
Solution:
Change the function from a bool* to a bool.
Change i == 0 to *(zero + i) == 0.
Additional information:
Seems like you're using using namespace std;. using namespace std; is considered a bad practice (More info here).
You probably should use std::vector if you can.
Full code:
#include <iostream>
bool noneZero(int *zero, int N) {
int PL = 0;
for (int i = 0; i < N; i++) {
if (*(zero + i) == 0) {
PL++;
}
}
if (PL == N)
return false;
else
return true;
}
int main(int argc, char** argv) {
int *z = new int[5]{0,0,0,0,0};
std::cout << noneZero(z,5);
delete[] z;
}

c++ sudoku program using Back tracking, Segmentation fault (core dumped) ,all suggestions are welcomed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
#include <iostream>
using namespace std;
//defining 9X9 grid.
int a[9][9] ={{0,0,3,0,9,2,6,0,0},
{1,0,0,3,0,0,8,0,0},
{0,0,5,0,1,0,0,4,0},
{0,3,0,0,0,0,2,5,8},
{2,4,0,0,5,0,0,0,0},
{0,0,0,6,2,0,0,0,3},
{0,1,4,0,0,9,0,3,0},
{6,0,0,7,0,0,1,0,0},
{3,0,0,0,0,4,0,0,2} };
// class sudoku.
class sudoku{
public:
int row,col,i,j,num;
//to check presence of element in particular row.
bool rowCheck(int a[9][9],int &row,int num)
{
for(j=0;j<9;j++)
{
if(a[row][j]==num)
return true;
}
return false;
}
//to check presence of element in particular column.
bool colCheck(int a[9][9], int &col, int num)
{
for(j=0;j<9;j++)
{
if(a[j][col]==num)
return true;
}
return false;
}
//to check presence of element in particular 3X3 grid.
bool boxCheck(int a[9][9],int &row ,int &col ,int num)
{
int x,y;
if(row<3)
x=0;
else if(row>=3 && row<6)
x=3;
else
x=6;
if(col<3)
int y=0;
else if(col>=3 && col<6)
y=3;
else
y=6;
for(i=x;i<x+3;i++)
{
for(j=y;j<y+3;j++)
{
if(a[i][j]==num)
return true;
}
}
return false;
}
//to check index which is unassigned.
bool unAssigned(int a[9][9],int &row,int &col)
{
for(row=0;row<9;row++)
{
for(col=0;col<9;col++)
{
if(a[row][col]==0){
return true;}
}
}
return false;
}
//to return true if position is suitable to insert .
bool isSafe(int a[9][9],int &row,int &col,int num)
{
if(!rowCheck(a,row,num) && !colCheck(a,col,num) &&
!boxCheck(a,row,col,num))
return true;
else
return false;
}
//function to solve sudoku.
bool sudokuSolver(int a[9][9])
{
if(!unAssigned(a,row,col))
return true;
for(i=1;i<=9;i++)
{
if(isSafe(a,row,col,i))
{
a[row][col]=i;
cout<<a[row][col];
if(sudokuSolver(a))
return true;
a[row][col]=0;
}
}
return false;
}
void display(int a[9][9])
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
//class ends
};
//main method
int main()
{
sudoku s;
s.sudokuSolver(a);
s.display(a);
return 0;
}
After calling: unAssigned(a,row,col) the value of row is 9 and the value of colis 9 when unAssigned() returns false. This is a consequence of using references to row and col.
bool unAssigned(int a[9][9],int &row,int &col)
{
for(row=0;row<9;row++)
{
for(col=0;col<9;col++)
{
if(a[row][col]==0){
return true;}
}
}
// here: row is 9 and col is 9
return false;
}
This means that you can return from sudokuSolver() with row and col out of bounds. This will trigger a segmentation fault in the following line:
if(sudokuSolver(a))
return true;
// here row or col are equal to 9 which is out of bounds
a[row][col]=0; // seg-fault here
You never initialize row and col which leads to undefined behaviour once you use their values.
Apart from that, I would suggest you to avoid hard coded array bounds and raw loops. If you use containers and iterators instead you can avoid out of bounds errors completely (not the problem here, but a line for(i=1;i<=9;i++) looks very suspicious and makes me think twice to realize that it is ok).
Moreover, dont pass by reference if the parameter is actually not modified by the method. E.g. bool colCheck(int a[9][9], int &col, int num) does not modify col, thus it is rather confusing why it takes col as reference. Also it is confusing that both row and col are members of the class but at the same time you pass them between the methods. I would suggest to rename the members to max_row and max_col, respectively.

Beginning of an nQueens game in c++. Where is the error located in my code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting errors when trying to compile the following code. The error is
expected ',' or ';' before '{' token.
It says there's an error on the parentheses after the bool check_row(x)
If I comment it out the same happens for bool check_col(x).
I kept looking back at my books if I didn't define my functions properly but they seem correct, logically.
This is the beginning of an nQueens game on a 4x4 board.
The Queen is represented by the number 1.
The two boolean functions are to check if the row and columns are free.
startGame() assigns 0 to all boxes, and showBoard() shows results of the board.
#include <cstdlib>
#include <iostream>
using namespace std;
int x=0, y=0;
int square[4][4];
void startGame()
{
for(x=0;x<4;x++)
{
for(y=0;y<4;y++)
{
square[x][y]=0;
}
}
}
void showBoard()
{
for(int x=0;x<4;x++)
{
if(x!=0)
{
cout<<endl;
}
for(int y=0;y<4;y++)
{
cout<<square[x][y];
}
}
cout<<endl;
}
bool check_row(x)
{
for(y=0;y<4;y++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(y==3)
{
return true;
}
continue;
}
}
}
bool check_col(y)
{
for(int x=0;x<4;x++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(x==3)
{
return true;
}
continue;
}
}
}
int main(){
startGame();
showBoard();
return 0;
}
bool check_col(y) isn't a valid prototype. You need to provide a type for y - for example bool check_col(int y). The same applies to bool check_row(x).
you have to specify the datatype which you are passing as a parameter in your function..considering x and y are of int type and are local, your function prototype should be
bool check_row(int x)
bool check_col(int y)
If x and y are global then there is no need to pass them..simply
bool check_row()
bool check_col()
will work as the visibility of global variables will be throughout the program, unless shadowed