C++ for with multiple control statements using comma operator - c++

How does comma operator if it is used in a 'for loop' for writing multiple control statements?
i tried
#include <iostream>
using namespace std;
int main() {
for (int x = 0, y = 0; x < 3, y < 4; ++x, ++y) {
cout << x << " " << y << endl;
}
return 0;
}
and it seems like only the last expression is evaluated. Ty

This is how comma operator works. Its 1st operand x < 3 is evaluated, then the result is discarded; then the 2nd operand y < 4 is evaluated and the value is returned as the return value of the comma operator. x < 3 has not any effects here.
You might want to use operator&& or operator|| for this case, e.g. x < 3 && y < 4 or x < 3 || y < 4 based on your intent.

Related

Solving a dp problem from codeforces - Cut Ribbon

I was trying to solve this problem and from the comments section in the editorial, I was directed to the following solution :
#include <bits/stdc++.h>
using namespace std;
#define MAX(a,b,c) max(a,max(b,c))
int n,a,b,c,dp[4001];
int f(int x)
{
if (x == 0) return 0;
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
}
int main()
{
cin >> n >> a >> b >> c;
memset(dp,0,sizeof(dp));
cout << f(n) << endl;
}
I wanted to know:
What is the need of the if statement that returns 0xACCE97ED for the test case:
4000 1 2 3. This test case dosen't work when that specific if statement is missing.
Why specifically 0xACCE97ED is being returned? Because when I tried to return any other number (say 9999), then the output is expected output + 9999.
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // -1395746835
Well looking at the dp function, it is basically maximizing values and this specific if statement is saying:
if x < 0
the length of the ribbon you cut is negative (which should be impossible)
or if x > 0 and x < a, b, c which means you can still cut X but all available sizes would result into having a ribbon of negative length
return 0xACCE97ED; return a random negative value which happens to spell out ACCEPTED because this state is invalid
And since the third if statement will try to get the max value, 0xACCE97ED will never be selected as the max value.
0xACCE97ED means "ACCEPTED" in the 1ee7 speech. nothing else specific about this value.
What is the need of the if statement that returns 0xACCE97ED for the test case: 4000 1 2 3
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
because the function f is recursive, in the next line it calls itself:
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
with a smaller values for x so presumable it will eventually make that if statement true and will return "accepted" (0xACCE97ED).

Can someone explain why a value gets incremented when "++" is used for comparison? [duplicate]

This question already has answers here:
How does the increment operator work in an if statement?
(7 answers)
Closed 4 years ago.
This may already be a question out there, but with the lack of specific key terms, it's a bit hard to search for. Just looking for more insight on this topic.
Right now, I'm working in C++ and wondering why my value is replaced with an incremented value when I compare using "++".
So here, we print 14 times (numbers 1-14).
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < i++) break;
cout << i << endl;
}
Here, we print 30 zeros.
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < i+1) break;
cout << i << endl;
}
And this just plain doesn't work. (I wanted to try because i++ = i=i+1).
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < i=i+1) break;
cout << i << endl;
}
Expression i++ has both a value and a side effect. The value is that of i, and the side effect is that i is incremented (after having taken its value as expression result).
Expression i+1, in contrast, does not have a side effect, it only has a value (which is the value of i plus 1) but leaves the value of i as it is.
That's why.
And this just plain doesn't work. (I wanted to try because i++ =
i=i+1).
The reason it doesn't work is because of operator precedence in this expression:
if (13 < i=i+1) break;
It is evaluated by compiler as
if ((13 < i)=(i+1)) break;
and assignment to bool fails. What you need is to add correct parentheses for it to work:
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < (i=i+1)) break;
cout << i << endl;
}
https://ideone.com/0NSNwU
1
2
3
4
5
6
7
8
9
10
11
12
13

C++ Matrix values of

I want to create a matrix of 5 lines and 5 columns which contains values from 1 to 9. The following programs displays numbers from 1 to 25 instead, when I input 5 to the program..
#include <iostream>
using namespace std;
int a[20][20], n, x = 0;
int main()
{
cout << "n=";
cin >> n;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
a[i][j] = x+1;
x = x+1;
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
I'm a c++ beginner, so maybe it's simple to do but i don't know how to make it show values from 1 to 9. This is the matrix I except:
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7
There are some issues in your code.
C arrays or STL containers?
First off, a your matrix may only hold matrices as big as 20x20. Your program will silently fail if you enter n bigger than 20, because you will access memory out of bounds; which causes an undefined behavior (see other common UB cases here).
You may want to use a dynamic size array - A good way to achieve this is to use std::vector. Unfortunately, this isn't as comfortable to use as a C-style array with two dimensions - you can achieve the same access syntax using a std::vector<std::vector<int>>, but this is not very efficient (see this answer if you are interested why) nor quite comfortable.
The Boost C++ library provides a multidimensional array library. Once you get experienced enough, you may find an use in it.
<= or <? 0-index or 1-indexed?
Many programming languages today uses 0-indexing for arrays. This means the first element of the array is located at index 0, not 1. Some languages, such as Lua, doesn't do this.
This means you should iterate i and j from 0 to n. This also means n is excluded, so you should use <, not <=.
Filling the matrix with numbers from 1 to 9
Your code doesn't do anything so you get numbers from 1 to 9 - it only fills the matrix with numbers from 1 to n * n. You could change this using an if clause to set x every time it goes above 9:
if (x > 9) { x = 0; } // x = 0 because it will be 1 on the next iteration
That being said, there is more convenient, as #PMar's answer says. The modulo operator % will do the task as well.
a[i][j] = (x % 9) + 1;
x = (x % 9) + 1;
This way, you will get every number from 1 to 9.
Now, you can also do another cleanup: Why are you calculating x's next value, and only then setting it? You could assign the new x value before the assignment to your matrix's cell. This allows having clearer code, with less copy pasting, which implies better maintainability.
x = (x % 9) + 1;
a[i][j] = x;
Another code quality consideration
I cannot say if your original code source was indented like your question (before it was edited), but you should really indent your code, for the future you and other people that will have to read your code. It allows for much better readability.
Same goes for different parts of your code : Add some space! It only can get more readable if you make a clear distinction between even just expressions.
You need to use the modulus operator (%). If you want the values in the matrix to be as you have computed them, but only need to change the display, you would output the matrix values as follows:
cout << (a[i][j] % 10) << " ";
If you want the one-digit values to be in the matrix itself, you would instead change the increment on 'x' to the following:
x = (x+1) % 10;}
#include <iostream>
int main()
{
int a[5][5];
int x = 1;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if(x > 9)
x = 1;
a[i][j] = x;
x++;
}
}
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if(a[i][j] < 10)
std::cout << " ";
std::cout << a[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
return 0;
}

Operators evaluation

This code evaluates to true:
#include <iostream>
int main(){
int x = 9;
int j = x-1;
if(x - j+1 > 1)
std::cout << "Ehhhh???\n";
}
But this one to false:
#include <iostream>
int main(){
int x = 9;
int j = x-1;
if(x - (j+1) > 1)
std::cout << "Ehhhh???\n";
}
plus and minus operators has higher precedence than "<", I'm also using only one data type so there should be bo overflow. Why results are different?
This is really just a matter what value the 1 gets added to. Addition and subtraction have left to right associativity so we start from the left and work our way right.
x - j + 1
(9 - 8) + 1
1 + 1
2
Where as
x - (j + 1)
9 - (8 + 1)
9 - 9
0
Forces the addition to be attached to j instead of x-j so the second case is rightly false.
Since the precedence of arithmetic + and - is the same but the associativity is from left to right, the one without the parenthesis will first do the subtraction then the addition, i.e.:
x - j+1 ==2 //here the operation is performed from left to right,subtraction first then addition
x - (j+1)==0 //here the one inside the parenthesis will be done first,i.e addition first then subtraction
Mathematically you have 2 different expressions:
x - j + 1 is equal to x - ( j - 1 )
and
x - ( j + 1 ) is equal to x - j - 1

If-statemenet condition [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a trouble understanding what does this code do :
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (x++ && y++)
y += 2;
cout << x + y << endl;
return 0;
}
The output is 1 by C++. But I think it should be 2?
Why? Because in the () of if statement, I think there should only check if it's true/false, so it doesn't increment/decrement any of the integers. And since that's true by default, it increases y for 2? And output should be 0+2 = 2, but it outputs only 1?
if (x++ && y++) will not do y++ because the condition to the left of the logical and operator (&&) is false since x++ will return 0 and increment x by 1.
Since false && expression will yield false for any expression, there is no need to evaluate the rest of it.
Hence, you end up with x = 1 and y = 0.
This is called Short-circuit Evaluation.
The post ++ operator has high priority and && operator is allowed to short circuit evaluation.
What happens in if (x++ && y++) is that first it evaluates x++. The result is 0 and increments x. Since 0 is false && will short circuit the evaluation of y++ (will not be executed). Also the if will evaluate to false and will not execute the y+=2.
So now you have x=1 and y=0.
So the result is 1.
it will first execute x++ and the compiler knows that because of that the expression x++ && y++ will be false and will ignore y++
as a result after that x = 1 and y = 0;
it is the same as writing if(false && do_something()) , in this case do_something() will never be called.
I advice you to take a look at the operator precedence chart : http://en.cppreference.com/w/cpp/language/operator_precedence
//in a statement, x++ will evaluate x then increment it by 1.
//in a statement, ++x will increment x by 1 then evaluate it.
If you have hard time to understand it then try the below code to better understand :
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (++x && ++y) // in your case, with the previous code, it gives (0 && 0)
// instead of if statement you can try the following : cout << x++; then cout << ++x;
// and notice the difference
y += 2;
cout << x + y << endl;
return 0;
}