C++ ? operator with continue operator in for loop - c++

I have a method which looks like this:
bool Perfect(int num) {
int sum = 0;
for (int i = 1; i < num; i++)
{
num%i == 0 ? sum += i : continue;
}
return sum == num ? true : false;
}
I'm trying to combine here ? operator with continue operator...
So logically if the statement here is false in this line:
num%i == 0 ? sum += i : continue;
I will just skip the iteration or do nothing?
If I do it like this the compiler reports an error like:
expected an expression
And in case like this:
num%i == 0 ? sum += i
It says:
Expected a ':'
Is there any way to use continue with ? operator or just simply avoid false case somehow ???

bool Perfect(int num) {
int sum = 0;
for (int i = 1; i < num; i++)
{
if(num % i == 0)
sum += i;
}
return sum == num;
}
Use an if statement. No need of continue since you have no other statement after sum += i.

C++ and C have both statements and expressions (notice that an assignment or a function call is an expression, and that expressions are statements). They are different syntactic (and semantical) things.
You could have coded (but this is weird style as a statement reduced to a ?: conditional expression) inside your for loop:
(num%i == 0) ? (sum += i) : 0;
(when num%i is non-zero, that evaluates to 0 which has no significant side effect; BTW that last occurrence of 0 could be 1234 or any constant integral expression)
Some programming languages (notably Scheme, read SICP) have only expressions (and no statements).
The ternary ?: operator applies to expressions and gives an expression (so can't be used for statements).
Conditional statements use the if keyword. In your case it is much more readable (because you are using sum += i only for its side effect) and an if statement is here easier to understand.

You can't use a ternary operator in this way. You would normally use it for assigning a value to a variable based on an expression being true or false. Eg.
int j, i,
j = (i == 2) ? 5: 10;
If i is equal to 2 then j is given the value of 5 else if i is not equal to 2 then j is given the value of 10.

Related

Can an if statement be written in any other way?

Well, I was going through some code and found this piece of code and am confused at statement 1.
vector<int> v{1,2,3,2};
mp<int,int> m;
for(auto i : v) m[i]++;
int ans = v.size();
for(auto i : v){
ans = min(ans, m[i] + 1 - (v.front() == i) - (v.back() == i)); //statement 1
}
The logic behind statement 1 is that if v contains element i in the front or the end then subtract 1 from the occurrence of i in map. It somehow is working correctly but how? I haven't seen such type of implementation of if before. Can someone please help how statement 1 if considering (v.front() == i) and (v.back() == i) as an if statement without mentioning any if keyword.
The expression v.front() == i evaluates to a bool that's either true or false.
A bool can be implicitly converted to an int with the value 1 or 0.
This is the same as when doing if (v.front() == i). The expression v.front() == i is again a bool true or false.

Is there a more efficient way of checking if an element is inside given intervals?

Suppose I have a variable x (double) that lies between 0 and 100. If x is in any of the intervals (0+10*n,5+10*n), with n (int) =0,...,9, then I return n, otherwise I break. I was thinking of doing this
bool test = false;
int k;
for(int i=0; i<10; i++){
if((0+10*i)<x<(5+10*i)){
k = i;
test = true;
}
}
if(test) return k;
else break;
would this be correct? If so, is there any other way that avoids loops?
It depends which intervals you have in mind. Since your intervals have a pattern to them, you can use a mathematical formula instead of a loop:
if(((int)x % 10) < 5) return (int)(x / 10);
else break;
(The % here is the modulo operator.)
Since C++'s % operator doesn't work on doubles, you can either cast x to an integer (as shown), or use the fmod function (works for non-integer intervals).
you can use % operator to get it's mod. get x % 10 and check if result of mod between 0 and 5. it can be faster than that.

What does it mean part of this code "seperature | | i"?

I am new for "C++" so I don't understand the following part of code.
The "data" is the String just like "Hello World" and seperature equals to this char "|". So what does it mean this line "data.charAt(i) == separator || i == maxIndex"
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
This:
data.charAt(i) == separator || i == maxIndex
is an expression that is contextually convertible to bool. That expression is part of the if statement condition. The || operator is a logical operator OR. Simply speaking you have:
if (A OR B)
Where A in your case is data.charAt(i) == separator and B is i == maxIndex. We can think of A and B as operands.
Due to operator precedence the compiler knows what A and B are and how to cut the entire expression into smaller expressions that make up operands. Both expressions have the equality operator == in them. So thinking about separator || i as being an expression is wrong.
The logical operator || groups left to right which means A gets evaluated first and B might not get evaluated if A is true.

Ternary operator inside a return statement

I was writing a recursive function, and encountered a problem at the return statement.
int SumOfEvenNumbers(int v[], int i)
{
if ( i > v[0] )
return 0;
return SumOfEvenNumbers(v, i+1) + (v[i]%2==0)?v[i]:0;
}
The function is called like this:
SumOfEvenNumbers(vector_indexed_from_1, 1);
//v[0] is equal to the number of elements, excluding itself
What I expected the ternary if to return was either v[i] or 0 ( in case it is even ) but apparently after printing the result of every ternary if to the screen, the only values that result from the expression are 1 and 0.
int SumOfEvenNumbers(int v[], int i)
{
if ( i > v[0] )
return 0;
cout << (v[i]%2==0)?(v[i]):(0); // either a 1 or a 0
return SumOfEvenNumbers(v, i+1) + (v[i]%2==0)?v[i]:0;
}
The way I fixed this is by initializing a variable with the result of the expression and then adding that to the return value.
int SumOfEvenNumbers(int v[], int i)
{
if ( i > v[0] )
return 0;
int rv = (v[i]%2==0)?(v[i]):(0);
return SumOfEvenNumbers(v, i+1) + rv;
}
Could anyone explain what is happening? Is it possible to avoid declaring a variable in order to obtain the correct result?
The ternary conditional operator has lower precedence than operator+.
Your code was actually parsed as
(SumOfEvenNumbers(v, i+1) + (v[i]%2==0)) ? v[i] : 0;
To get what you want, use parentheses
SumOfEvenNumbers(v, i+1) + ((v[i]%2==0)) ? v[i] : 0);
See: http://en.cppreference.com/w/c/language/operator_precedence
Could anyone explain what is happening?
Take a look at operator precedence. Here ternary conditional happens to have very low priority. In SumOfEvenNumbers(v, i+1) + (v[i]%2==0)?v[i]:0 expression it is calculated after + given you unexpected result.
Is it possible to avoid declaring a variable in order to obtain the correct result?
I cases when you are not sure about order of operators it is safe to use brackets () to indicate the order explicitly. So SumOfEvenNumbers(v, i+1) + ((v[i]%2==0)?v[i]:0) will be calculated as expected.

Can someone explain this if statement for me?

I'm new to programming, can someone take two minutes to explain this statement for me? how can I write it like this :
if (condition) {...} else {...}
if (myFunction(i == 8? (j + 1): j, (j + 1) % 9))
{
return true;
}
The function is called with two arguments. First one uses a ternary operator to check if i (the index) is 8; if so, increment j, else leave j as is.
Second argument increments j by 1, it uses primary expression operator around j+1 because arithmetic + has lower precedence than modulus (%) http://www.swansontec.com/sopc.html. If j is 1 and we increment by 1, then 2 % 9 is 2, since the modulo operation returns the remainder. This assumes C style syntax.
int arg1 = i == 8 ? (j + 1) : j;
int arg2 = (j + 1) % 9;
if (myFunction(arg1,arg2))
{
return true;
}
else
{
return false;
}