I don't understand how 'i' become 4 [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
how does the optput come as
3
3
4
I don't understand how 'i' become 4 for last
code:
int i = 2;
Console.WriteLine(++i);
Console.WriteLine(i++);
Console.WriteLine(i);

Because you first used the prefix increment operator and then used postfix.
int i = 2;
Console.WriteLine(++i); // i became 3 *before it was used*
Console.WriteLine(i++); // i first used, still 3, and then incremented becoming 4
Console.WriteLine(i); // i is still 4

In c# assigning a value to a variable also returns a value. Usually it is the value that is assigned
Here is an assignment, the current time is assigned to the now variable:
DateTime now = DateTime.Now;
This assignment also results in a returned value of the current time. It means you can legally write this:
DateTime now;
Console.WriteLine(now = DateTime.Now);
Not only will your now variable end up set to the current time, but the value of what was assigned is printed out, so the current time is printed
This is also an assignment:
int i = 2;
And so is this:
++i;
It is short for this:
i = i + 1;
Now because we know assignments return values we know it's legal to print out assignments:
Console.WriteLine(i = i + 1);
If i was 2, the sum on the right would be evaluated to give 3, then 3 would be assigned into i, and then also 3 is returned so 3 prints out in the console
i++ is more like a special case, where the value that i was BEFORE the assignment is made, is printed out. You can think of i++ as working like:
int i_before = i; //remember it
i = i + 1;
return i_before; //return the old value
So this:
Console.WriteLine(i++);
If i is 3 already, it will be incremented to 4, but 3 is returned and printed
The easy way to remember the difference between i++ and ++i is:
"in i++ the i is before the ++ so the value you get returned is what i was before it was incremented"
If you just use the increment as a statement on its own, it makes no difference which you use:
int i = 2;
i++;
++i;
Console.WriteLine(i); //4
It only matters which you use if you are relying on the "assignment returns a value" behavior
By the time the last line of your code comes around, i is 4 because it has been incremented twice, from 2

i starts out as 2.
On the first line, you (pre) increment it to 3, and then print it out.
On the second line, you print it out and then increment it (post increment), so it's now 4.
On the last line, you just print out the current value, which is 4, as noted above.

Related

Correct way to change value in List<int> / array [duplicate]

This question already has answers here:
i = i++ doesn't increment i. Why? [duplicate]
(4 answers)
Closed 1 year ago.
Suppose the List/array
List<int> a = new List<int>(){1,2,3,4,5};
int []a = new int[]{1,2,3,4,5};
And I want to change the value at index 2, whats the correct way?
a[2]++; or a[2] = a[2]++;
Please explain the answer.
The result of a[2] = a[2]++ will be a[2], in this case 3.
The postfix increment a[2]++ will change the value of a[2] after the line in which it appears has finished.
If you want to change the value, then a[2]++ or a[2] = ++a[2] are valid.
The correct way is the first one:
A[2]++;
The second one also works but it does more work than necessary. It is equivalent to the following code:
a[2] = a[2]; // useless
a[2]++;
The suffix ++ operator (as in x++) applies after the line in which it appears has finished executing. The prefix ++ operator (as in ++x) first modifies the element and then uses the value.
I suggest you read the documentation about the "increment operator":
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator-

For loop working in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am writing a program that finds the number of 1's in an array.. but the "scanning" inside the "for" loop takes place only once.
for (i = 0; i < 11; i++ )
{
k = Convert.ToInt32(Console.Read());
if (k==1)
{
ans++;
}
// Console.WriteLine("i == {0}", i);
}
Is this normal in C# or am I doing something wrong? I tried to search for this problem but cannot find any answers!
Do
Console.ReadLine()
instead of
Console.Read()
When you reach the first Console.Read() the inputstream is saved but only the first character is returned by the Read method. Subsequent calls to the Read method retrieve your input one character at a time from the inputstream.
Ex:
First iteration:
k = Console.Read(); //you input "abc1", k = a
Second iteration:
k = Console.Read(); // k = b
and so on.
When the last character in the inputstream is returned, the next call to Console.Read() will display the console again so you can input a new string and hit Enter.
Console.Read() docu
There's no array in your code, actually. Personally I'd rewrite this to:
string input = Console.ReadLine();
for (i = 0; i < input.Length; i++ )
{
int k = Convert.ToInt32(input.Substring(i, 1));
if (k==1)
{
ans++;
}
}
Which lets the user enter a string first and then does all the parsing. Of course, the user may enter more or less than exactly 11 characters in this code, so if you really need 11 numbers, I'd add extra messages and checks.
Also this code (as your original code) fail miserably if the user enters something non-numeric, so exception handling would be on the task list as well.
Try to use this code, I think it will answer your problem
string[] sample = { "1", "1", "3" };
var a = (from w in sample
where w == "1"
select w).ToList();
Console.Write(a.Count);

Find maximum sum leaf to root path in a Binary Tree [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 9 years ago.
Improve this question
I have created a recursive function to calculate the max path of a binary tree. I got as feedback that it does not work, but according to me test it provide the correct result. Can someone help me please?
private long PathSum(int row, int column, Pyramid pyramid)
{
// Base case, stop recurse when first row is reached.
if (row == 0) return pyramid[row, column];
// Set level to the current cell and add to the end result.
long value = pyramid[row, column];
// Continue to the next row.
if (row != 0)
{
// Continue to the next left level.
long left = pyramid[row - 1, column];
// Continue to the next right level.
long right = pyramid[row - 1, column + 1];
// Get the highest of the left and right.
long highest = Math.Max(left, right);
// Get the index of the hightest path.
int nextColumn = highest == left ? column : column + 1;
// Recurse to the next level and add results together.
value += GetTotal(row – 1, nextColumn, pyramid);
}
// Return result to the caller.
return value;
}
You have a critical mistake in your algorithm: you only walk through the 'pyramid' once and select the based case based on the next result, without looking at underlying nodes.
To illustrate what you are doing, consider the following pyramid:
1
2 3
311 6 3
Assuming that you start at 1, the following will be executed:
Look at the max out of the underlying nodes (2 and 3).
Go down to the next node (3) and repeat.
Your algorithm will return 10 (1 + 3 + 6) while the maximum value in my example is 311 + 2 + 1, because it doesn't look ahead.
You require a strategy to look further than one step ahead in order to determine the best path.
Edit: look at Euler project #18 approach for more hints.
I think what you are describing is not a binary tree but a pyramid of numbers, and the problem is best solved using dynamic programming instead of tree traversal. Here is a sample code for dynamic programming. It is not compiled and I don't know C# by the way:
private long DP(int maxRow, Pyramid pyramid)
{
int maxColumn = maxRow;
Pyramid result;
clear_pyramid(result);
for (int j=0; i<maxColumn; i++) {
result[0, j] = pyramid[0, j];
}
for (int i=1; i<maxRow; i++) {
for (int j=0; j<maxColumn-i; j++) {
result[i,j] = Math.max(result[i-1,j], result[i-1,j+1]) + pyramid[i,j];
}
}
return result[maxRow-1, 0];
}

Showing different output from my acceptation

Hay I didn't know even If this question has asked before but my problem is as following.
In my c# console application I had declared a variable i with assigning a value as
int i = 0 and now I want increment i by 2, obviously I can use following cede.
int i = o;
i += 2;
Console.WriteLine(i);
Console.ReadLine();
//OUTPUT WILL BE 2
but this one is my alternate solution. As my lazy behavior I refuse to use this code and I had used following code.
int i = 0;
i += i++;
Console.WriteLine(i);
Console.ReadLine();
In above code I had accepted FIRST i++ will increment by one and than after it will again increment by i+=i but this thing is not happen.!!!
I doesn't know why this thing is happening may be I had done something wrong or some compilation problem.?????
Can any one suggest me why this happening????
I just want to know why code no 2 is not working? what is happening in there?
The i++ returns the value of i (0) and then adds 1. i++ is called post-increment.
What you are after is ++i, which will first increase by one and then return the increased number.
(see http://msdn.microsoft.com/en-us/library/aa691363(v=vs.71).aspx for details about increment operators)
i needs to start off with 1 to make this work.
int i = 1;
EDIT::
int i = 0;
i += i++;
Your code above expresses the following:
i + 0 then add one
if you use i += ++i; then you'll get i + 1 as it processed the increment beforehand.
What your code is doing:
"i++" is evaluated. The value of "i++" is the value of i before the increment happens.
As part of the evaluation of "i++", i is incremented by one. Now i has the value of 1;
The assignment is executed. i is assigned the value of "i++", which is the value of i before the increment - that is, 0.
That is, "i = i++" roughly translates to
int oldValue = i;
i = i + 1
//is the same thing as
i = oldValue;
The post-increment operator increments the value of your integer "i" after the execution of your i++
For your information:
i++ will increment the value of i, but return the pre-incremented value.
++i will increment the value of i, and then return the incremented value.
so the best way of doing the 2 step increment is like that:
i +=2

int[] arr={0}; int value = arr[arr[0]++]; Value = 1?

Today I came a cross an article by Eric Lippert where he was trying to clear the myth between the operators precedence and the order of evaluation. At the end there were two code snippets that got me confused, here is the first snippet:
int[] arr = {0};
int value = arr[arr[0]++];
Now when I think about the value of the variable value, I simply calculate it to be one. Here's how I thought it's working.
First declare arr as an array of int
with one item inside of it; this
item's value is 0.
Second get the value of arr[0] --0 in
this case.
Third get the value of arr[the value
of step 2] (which is still 0) --gets
arr[0] again --still 0.
Fourth assign the value of step 3
(0) to the variable value. --value =
0 now
Add to the value of step 2 1 --Now
arr[0] = 1.
Apparently this is wrong. I tried to search the c# specs for some explicit statement about when the increment is actually happening, but didn't find any.
The second snippet is from a comment of Eric's blog post on the topic:
int[] data = { 11, 22, 33 };
int i = 1;
data[i++] = data[i] + 5;
Now here's how I think this program will execute --after declaring the array and assigning 1 to i. [plz bear with me]
Get data[i] --1
Add to the value of step 1 the value
5 --6
Assign to data[i] (which is still 1)
the value of step 2 --data[i] = 6
Increment i -- i = 2
According to my understanding, this array now should contain the values {11, 27, 33}. However, when I looped to print the array values I got: {11, 38, 33}. This means that the post increment happened before dereferencing the array!
How come? Isn't this post increment supposed to be post? i.e. happen after everything else. What am I missing guys?
The postincrement operation occurs as part of evaluating the overall expression. It's a side effect which occurs after the value is evaluated but before any other expressions are evaluated.
In other words, for any expression E, E++ (if legal) represents something like (pseudo-code):
T tmp = E;
E += 1;
return tmp;
That's all part of evaluating E++, before anything else is evaluated.
See section 7.5.9 of the C# 3.0 spec for more details.
Additionally, for assignment operations where the LHS is classified as a variable (as in this case), the LHS is evaluated before the RHS is evaluated.
So in your example:
int[] data = { 11, 22, 33 };
int i = 1;
data[i++] = data[i] + 5;
is equivalent to:
int[] data = { 11, 22, 33 };
int i = 1;
// Work out what the LHS is going to mean...
int index = i;
i++;
// We're going to assign to data[index], i.e. data[1]. Now i=2.
// Now evaluate the RHS
int rhs = data[i] + 5; // rhs = data[2] + 5 == 38
// Now assign:
data[index] = rhs;
The relevant bit of the specification for this is section 7.16.1 (C# 3.0 spec).
For the first snippet, the sequence is:
Declare arr as you described:
Retrieve the value of arr[0], which is 0
Increment the value of arr[0] to 1.
Retrieve the value of arr[(result of #2)] which is arr[0], which (per #3) is 1.
Store that result in value.
value = 1
For the second snippet, the evaluation is still left-to-right.
Where are we storing the result? In data[i++], which is data[1], but now i = 2
What are we adding? data[i] + 5, which is now data[2] + 5, which is 38.
The missing piece is that "post" doesn't mean "after EVERYTHING else." It just means "immediately after I retrieve the current value of that variable." A post increment happening "in the middle of" a line of code is completely normal.
data[i++] // => data[1], then i is incremented to 2
data[1] = data[2] + 5 // => 33 + 5
I would expect the post-increment operator to increment the variable after its value is used.
In this case, the variable is incremented before the second reference to the variable.
If it would not be so, you could write
data[i++] = data[i++] + data[i++] + data[i++] + 5
If it would be like you say, then you could remove the increment operator because it doesn't do actually anything, in the instruction I reported.
You have to think of assignments in three steps:
Evaluate left hand side (=get address where the value should be stored)
Evaluate right hand side
Assign the value from step 2 to the memory location from step 1.
If you have something like
A().B = C()
Then A() will run first, then C() will run, and then the property setter B will run.
Essentially, you have to think of your statement as
StoreInArray(data, i++, data[i] + 5);
The cause might be that some compilers optimize i++ to be ++i. Most of the time, the end result is the same, but it seems to me to be one of those rare occasions when the compiler is wrong.
I have no access to Visual Studio right now to confirm this, but try disabling code optimization and see if the results will stay the same.

Categories