why doesnt the bool function return false? - c++

I'm soo sorry I searched for and read similar questions but couldn't understand/use them to solve my own.
Im writing a bool function within an if statement but the function doesn't seem to return false, what am I doing wrong.
My bool function just checks if there are more than one of the given number in an array:
bool findsame(int a[], int b){
int k=0;
for(int i=0;i<20;i++){
if(a[i]==b){
k++;
}
}
if(k>1){
return true;
}
else{
return false;
}
}
int main()
{
const int size=20;
int a[size]={4,4};
int b=4;
if(findsame(a,b)){
cout<<"true";
}
}

I think you got confused why "false" is not getting printed on console with the function returning the false value.
You need to add to an extra else statement to print false on the console:
if(findsame(a,b)){
std::cout<<"true";
}else{
std::cout<<"false";
}
Also, there are two 4 values in the array, therefore always true will get printed.
Try passing value of b other than 4 and 0.
Have a look at the following implementation where value of variable b is equal to 1:
#include<iostream>
bool findsame(int a[], int b){
int k=0;
for(int i=0;i<20;i++){
if(a[i]==b){
k++;
}
}
if(k>1){
return true;
}
else{
return false;
}
}
int main()
{
const int size=20;
int a[size]={4,4};
int b=1;
if(findsame(a,b)){
std::cout<<"true";
}else{
std::cout<<"false";
}
}
Output:
false
PS: I have also tested code for the value of b = 4 and it prints true. Check and Run the code here: https://onlinegdb.com/S1LR5PtvD

Related

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.

Function checking values of type chars

I am new to programming and have an exercise in which I create a function to check whether an array of type char hold particular values.
Here is my function:
bool arrCheck(char n[],char pos1,char pos2,char pos3,int size)
{
int n1,n2,n3;
for (int i=0;i<size;i++)
{
if (n[i]==pos1)
{
n1=1;
}
if (n[i]==pos2)
{
n2=1;
}
if (n[i]==pos3)
{
n3=1;
}
}
if ((n1==1)&&(n2==1)&&(n3==1))
{
return true;
}
}
here is my test program:
int main()
{
char a[5]={'6','1','a','a','a'};
if (arrCheck(a,'1','6','9',5))
{
cout<<"true\n";
}
}
I thought the result is supposed to be false but all I got is true. What did I do wrong?
n1, n2 and n3 are default-initialized and they have indeterminate values at first. Initialize them before checking their values. Also do not forget to return something even when the condition is false.
Try this:
bool arrCheck(char n[],char pos1,char pos2,char pos3,int size)
{
int n1=0,n2=0,n3=0;
for (int i=0;i<size;i++)
{
if (n[i]==pos1)
{
n1=1;
}
if (n[i]==pos2)
{
n2=1;
}
if (n[i]==pos3)
{
n3=1;
}
}
return (n1==1)&&(n2==1)&&(n3==1);
}
Using boolto store boolean values and using const to mark that the contents of array won't be changed may be better .
bool arrCheck(const char n[],char pos1,char pos2,char pos3,int size)
{
bool n1=false,n2=false,n3=false;
for (int i=0;i<size;i++)
{
n1=n1||(n[i]==pos1);
n2=n2||(n[i]==pos2);
n3=n3||(n[i]==pos3);
}
return n1&&n2&&n3;
}
1) Use a bool variable instead of three int variable
2) Initialize it (You have not initialized the int variable and they have random garbage value)
3) Also add else condition to return false value (Your code is not returning false).
4)Also print false in main function using else condition.
Hope this helps you..!
THE CODE IS ALRIGHT. You just forgot to add some statements and this is causing the error (it might or might not have been silly on your part).
Your definition of the function arrCheck() is incomplete. It returns true if a certain condition is fulfilled but what if it isn't? In that case, you must return false. But in your code, false is never returned. So firstly, you've gotta add an else statement after the last if statement in the arrCheck() method to this:
if((n1==1)&&(n2==1)&&(n3==1)){
return true;
}
else{
return false; //this has to be added
}
It can now return false if such a case is encountered.
Also, you must display "false" in the main method if arrCheck() returns false. You are recommended to add an else statement after the if statement in the main() method. See the modification below:
if (arrCheck(a,'1','6','9',5))
{
cout<<"true\n";
}
else{
cout<<"false\n"; //it must show false;
}
Once you correct these, your code will produce the correct output.
P.S. This answer serves as an elaboration of the answer earlier submitted by #KUSHAGRA GUPTA.
int n1,n2,n3;
This line leads to undefined behaviour because you do not initialise the variables yet attempt to read from them later on even if not all of them have been assigned a value:
if ((n1==1)&&(n2==1)&&(n3==1))
Fix the undefined behaviour by initialising the variables to 0:
int n1 = 0;
int n2 = 0;
int n3 = 0;
There is another case of undefined behaviour when your function does not state what to return if the condition is not true. Fix this, too:
if ((n1==1)&&(n2==1)&&(n3==1))
{
return true;
}
else
{
return false;
}
Or simply:
return (n1==1)&&(n2==1)&&(n3==1);
change that line to like this.int n1= 0,n2= 0,n3 = 0;
because when uninitialized these variable have garbage values.
bool arrCheck(char n[],char pos1,char pos2,char pos3,int size)
{
int first = 0,second = 0, third = 0;
for (int i=0;i<size;i++) {
if (n[i]==pos1) {
first = 1;
} else if (n[i]==pos2) {
second = 1;
} else if (n[i]==pos3) {
third = 1;
}
}
if( first+ second + third == 3)
return true;
else
return false;
}

replace all negative value from array using recursion C

I want replace all negative value by zero(recursively). And I have use C and recursion. It's was my homework.
Desired output:
0 4 0 3
What I get:
0 4 -9 3
My code:
#include <stdio.h>
int zeros_value(int n, int tab[])
{
if (n==0) return 0;
if(tab[n-1] < 0){
tab[n-1]=0;
}
else{
return zero_value(n-1,tab);
}
}
int main(void)
{
int tab[4] = {0,4,-9,3};
int number = 0;
int i;
zero_value(4, tab);
for(i=0;i<4;i++)
printf("%d ", tab[i]);
return 0;
}
When you hit the first negative, the recursion doesn't continue anymore and the function returns. You don't really need to return any value from the function. You can rewrite it to make a void function.
#include <stdio.h>
void zero_value(int n, int tab[])
{
if (n==0) return;
if(tab[n-1] < 0) tab[n-1]=0;
zero_value(n-1,tab);
}
int main(void)
{
int tab[4] = {0,4,-9,3};
int number = 0;
int i;
zero_value(4, tab);
for(i=0;i<4;i++)
printf("%d ", tab[i]);
return 0;
}
I see the following problems with your code.
The function zero_values does not have a valid return statement when tab[n-1] is negative. You can see it more clearly if you change the function to:
int zeros_value(int n, int tab[])
{
if (n==0)
{
return 0;
}
if(tab[n-1] < 0)
{
tab[n-1]=0;
// No return here.
}
else
{
return zero_value(n-1,tab);
}
// No return here either.
}
Calling such functions leads undefined behavior.
The printf line in main is not right.
printf("%d%d%d%d", zeros_value(4,tab));
That line needs four arguments of type int after the format string to work correctly. Not providing enough arguments to printf is also cause for undefined behavior.
You can use solution provided in the answer by #usr to solve both problems.
If you have any valid reasons to return an int from zero_value, you need to change the implementation appropriately. It's not clear from your post what that return value is supposed to be.

SPOJ: What is the difference between these two answers for KURUK14

I have solved this problem and got AC. My problem is related to equivalence of following two approaches. The first code got accepted, while the second didn't.
As far as I can discern, both are completely equivalent for all the (valid) test cases any human can think of. Am I wrong? If so, what test case can differentiate them?
Code#1 (Accepted one):
#include <cstdio>
bool* M;
bool proc(int N){
for(int j=0;j<=N;j++){
M[j]=false;
}
for(int i=0;i<N;i++){
int a=0;
scanf("%d",&a);
if(a>=N)
return false;
else if(!M[a])
M[a]=true;
else if(!M[N-1-a])
M[N-1-a]=true;
}
bool f = true;
for(int k=0;k<N;k++)
{
f = f && M[k];
}
return f;
}
int main() {
M=new bool[1002];
int num=0;
scanf("%d",&num);
while(num){
int N=0;
scanf("%d",&N);
if(proc(N))
printf("YES\n");
else
printf("NO\n");
num--;
}
return 0;
}
Code #2 (WA):
#include <cstdio>
bool* M;
bool proc(int N){
for(int j=0;j<=N;j++){
M[j]=false;
}
for(int i=0;i<N;i++){
int a=0;
scanf("%d",&a);
if(a>=N)
return false;
else if(!M[a])
M[a]=true;
else if(!M[N-1-a])
M[N-1-a]=true;
else
return false;
}
return true;
}
int main() {
//Exactly same as code#1
}
The bug has nothing to do with the algorithm itself—it's very possible both the algorithms are correct. But the second implementation is wrong.
When you reach a test case which should return NO, you exit the function prematurely. Which means there are some numbers from the current test case left unread in the input, which of course confuses further reading thoroughly. This means the bug only manifests when T > 1.

How to break out of a while loop with a boolean?

I am trying to break out of several nested while loops and I am having trouble. I want this program to break out into the outer loop, which will run only a certain amount of times. I tried doing it with a boolean but my program terminates too early. It is an N-Queens problem where I am solving for 1x1, 2x2, 3x3,...nxn queens.
Here is my code:
bool ok(int *q, int col)
{
for(int i=0; i<col; i++)
if(q[col]==q[i] || (col-i)==abs(q[col]-q[i])) return false;
return true;
};
void print(int q[], int n, int cnt)
{
//static int count =0;
cout<<"There are "<<cnt<<" solutions for "<<n<<" queens." <<endl;
};
int main()
{
int n;
int *q;
cout<<"Please enter the size of the board:"<<endl;
cin>>n;
int static count = 0;
int c = 1;
int a = 1;
bool from_backtrack=false;
while(a!=n){
q= new int[a];
q[0]=0;
bool foundSolution=true;
while(foundSolution)
{
if (c==a){
a++;
}
while(c<a)
{
if(!from_backtrack)
q[c] = -1; //Start at the top
from_backtrack=false;
while(q[c]<a)
{
q[c]++;
if (q[c]==a)
{
c--;
if(c==-1) {
print(q, n, count);
foundSolution=false;
//system("PAUSE"); exit(1);
}
continue;
}
if( ok(q,c) ) break; //get out of the closest while loop
}
c++;
}
count++;
c--;
if(c==-1) {
print(q, n, count);
foundSolution=false;
//system("PAUSE"); exit(1);
}
from_backtrack=true;
}
delete[a] q;
a++;
}
system("PAUSE");
}
The most elegant way would be to wrap some of your inner loops in a function.
It will be easier to read and to control.
At my work, we employ MISRA guidelines which state "... only 1 break per while loop". This has caused me to rewrite my if and while loops:
bool can_continue = true;
if (can_continue)
{
status = Do_Something();
if (status != SUCCESS)
{
can_continue = false;
}
}
if (can_continue)
{
status = Do_Another_Thing();
can_continue = status == SUCCESS;
}
//.. and so on.
The idea is to set a flag to "false" if execution can't continue. Check it after any segment can cause execution to fail.
while( true ){
if( condition == true ){
goto bye;
}
}
:bye
Just don't submit this on your homework...
Think it is as crazy as useless.
However, suppose you want 3 iterations, you'll define an array of bool of 3 elements (all set to true). On each iteration you set the current element to false, until you reach the end of your array.