How do I replace an if with a bool?

May 31, 2017 at 3:22pm
So im a beginner in programming and i need help with replacing the if below with anything else.I tried to use bool but it didnt work.So if someone can help me thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main(){
	int i,a[4]={4,3,5,8},b[4]={3,7,8,4},c[4]={0,0,0,0},p=0;
	for(i=0;i<4;i++){
		b[i]=10-b[i];
}
	for(i=3;i>=0;i--){
		c[i]=(a[i]+b[i]-p)%10;
		p=(a[i]+b[i]-p);
		
		if(p<10)      // <---- This if
			p=1;
		else
			p=0;
}
		for(i=0;i<4;i++){
		cout<<c[i]<<" ";
		
}
Last edited on May 31, 2017 at 4:18pm
May 31, 2017 at 4:06pm
If you have to test that p is less than 10, you don't have many choices.

One option is the ternary operator:
 
  p = (p<10) ? 1 : 0;


PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
May 31, 2017 at 4:10pm
Booleans are not conditionals.

Booleans can STORE the RESULT of binary condition statements.

bool b = p < 10; //b is either true or false, OK

but you still need

if(b)
...
else
....

you can tighten the code with
p = p<10; //

which only works because P is 1 or 0. If you needed

if(p<10)
p = 3;
else
p = -17;

You could not do it.

May 31, 2017 at 4:12pm
p=int(p < 10);

That will perform an explicit conversion of a bool to an int. You can do the implicit p=(p<10); but it is less clear that you actually intended to convert the value. The compiler won't care, but the next programmer to maintain the code will.
May 31, 2017 at 6:18pm
That one cast isn't going to fix the totally unreadable gibberish of the original. I suppose every little bit helps :)
Jun 1, 2017 at 3:55pm
You're complaining about gibberish code on this forum? That's pretty much all I ever see.
Jun 1, 2017 at 5:04pm
No, I am not complaining, just observing.
Topic archived. No new replies allowed.