when I compile this, I get
j is: 28 k is: 50
V H
What I do not understand is, why is the j++ and k++ 28 and 50 and not 27 and 48, respectively? I don't understand why it adds 3+, and not 1+.
The condition (txt[j] == txt[k]) is true for 3 values, '-', 'I', and '-'. So you add three to 25, and add 3 to 47. The before/after increment is only different on the line it happens.
If you had:
int x = 10;
int y = 10;
cout << x++;
cout << ++y;
you would see that x's value would be 10 at the time it was printed, and y's value would be 11.
if you then just printed them again without changing them a second time they should both be 11.
===========================
With your values it works like this:
Txt [25] is letter '-' in the string. It's like the 4th '-' in. Text[47] is also the letter '-', it's like the 8th '-' in the string. The condition of the loop says to continue running the increment opperators on these two indexes while they are the same value. So they are the same, both get incremented. Now we look at letters 26, and 48. These are both 'I', which is the same again. So we increment a third time, 27, and 49 Are both '-' again, so we increment again. Now 28 is at 'V' (the start of 'VAAR'), and 50 is at 'H' the start of 'HOST'. 'H' is not equal to 'V' so we stop looping here.
You're starting your compare at "-I-V" and "-I-H". So there are three characters that match.
Preincrement ++k and postincrement j++ both increment the variables. The difference in how they behave as right hand side arguments, e.g. int z = ++k; vs int z = k++;. The former increments k and assigns its new value to z. The latter assigns the current value of k to z and then increments k;
Related
I am extremely new to the coding world. I just have a basic question regarding this function that squares integers from 0-9. I understand most of what's going on until I get to
std::cout << i << " " << square << "\n";
i = i + 1;
I'm not too sure how that ends up causing the output to square the results in order from 0-9. Can someone explain the reasoning behind this line of code? Here is the code for this function.
#include <iostream>
int main() {
int i = 0;
int square = 0;
while ( i <= 9) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
return 0;
}
This code:
std::cout << i << " " << square << "\n";
i = i + 1;
Doesn't square anything. It is merely outputting the current square that has already been calculated, and then increments i for the next loop iteration.
The actual squaring happens here:
square = i*i;
So, the code starts at i=0, calculates square=0*0 and displays it, then sets i=1, calculates square=1*1 and displays it, then sets i=2, calculates square=2*2 and displays it, and so on until i exceeds 9, then the loop stops.
Lets start from beginning and what is happening, I will ignore first several lines and start at:
int i = 0;
int square = 0;
You see when you say int i; your compiler says I need to allocate bucket of memory to hold value for i. When you say i = 0 zero is put into that memory bucket. That is what is happening for square as well.
Now to loop
while ( i <= 9 ) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
So, lets ignore
square = i*i;
std::cout << i << " " << square << "\n";
for now we will come to it later.
So
while ( i <= 9 ) {
i = i + 1;
}
goes into the loop and gets value from i's bucket, adds 1 and puts new value into the i's bucket. So in first loop it will be i = 0 + 1, put 1 into i bucket. Second, i = 1 + 1 put 2 in, third i = 2 + 1 put 3.
So lets go back to square and its bucket.
square = i*i;
So first time we go into the loop i = 0 and square = 0 * 0 so compiler puts 0 into square's memory bucket. Next time it hits square i has been incremented to 1 so square = 1 * 1, thus compiler puts 1 into the bucket. Third time i is 2 so square = 2 * 2, and compiler puts 4 into the bucket. And so on till it i <= 9. When i hits 10 loop is not executed.
In comments you have stated that you do not know the difference between a math equation and an assignment statement. You are not alone.
I will try to explain, as an addition to existing answers, to provide a different angle.
First, two examples of math equations:
x = 1 +1
y+1 = x*2
To illustrate their meaning, let me point our that you first can determine that x is 2 and in a second step that y is 3.
Now examples of assignment statements.
x = 1 +1;
y = x*2;
The minor difference is the ; at the end, tipping you off that it is a program code line.
Here the first one looks pretty much the same as the first equation example. But for a C compiler this is different. It is a command, requesting that the program, when executing this line, assigns the value 2 to the variable x.
The second assingment statement I made similar to the second equation example, but importantly different, because the left side of = is not an expression, not something to calculate. The equation-turned-statement
y +1 = x*2;
does not work, the compiler will complain that it cannot assign a value (no problem with doing a little calculation on the right side) to an expression. It cannot assign the value 4 to the expression y+1.
This helps with your problem, because you need to understand that both lines
i = i + 1;
square = i*i;
are statements which, when executed (and only then) cause a change to the value of the variable in that line.
Your program starts off with the value 0 in the variable i. At some point it executes the first of the statements above, causing the value of i to change from 0 to 1. Later, when the same line is executed again, the value of i changes from 1 to 2. So the values of i change, loop iteration by loop iteration, to 2,3,4,5,6,7,8,9
The second assignment line causes the value of square to become the value of i, whatever it is during that loop iteration and multiplied by itself. I.e. it gets to be 4,9,16,25,36....
Outputting the value of square each time in the loop gets you the squares.
Since you state that you basically understand loops, I just mention that the loop ends when i is not lower or equal to 9 any more.
Now from the other point of view.
If you try to solve the equation
i = i + 1
for i, you should hear your math teacher groaning.
You can subtract i from both sides and get
0 = 1
The solution is "Don't try.", it is not an equation.
std::cout << i << " " << square << "\n"; prints every
number i next to its square, which is previously computed
(square = i*i;).
i = i + 1; increments i to compute the next square. It stops when i reaches 10.
The output will look like this:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
So we have a while loop here, which run while i <= 9. The square of any number i is i * i.
while(i <=9){ //check the condition and then enter the body
//body
}
But we need a condition to get out of the loop, otherwise our program will enter into an infinite loop.
To ensure, we will exit from the loop we increase the value of i by 1.
so at first when i = 0 square = 0 * 0 = 0,now we increase the value of i i.e now i becomes one which still satisfies the condition to stay inside the loop , again it will calculate square = 1 * 1 until and unless the value of i remains less than or equal to 9.
Once the condition fails, the execution comes out of the loop.
I can't understand how to count number of 1's in binary representation.
I have my code, and I hope someone can explain it for me.
Code:
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
Why while ? For example if i have 1011, it wouldn't stop at 0?
Why nr += x%2 ?
Why x/=2 ?!
First:
nr += x % 2;
Imagine x in binary:
...1001101
The Modulo operator returns the remainder from a / b.
Now the last bit of x is either a 0, in which case 2 will always go into x with 0 remainder, or a 1, in which case it returns a 1.
As you can see x % 2 will return (if the last bit is a one) a one, thus incrementing nr by one, or not, in which case nr is unchanged.
x /= 2;
This divides x by two, and because it is a integer, drops the remainder. What this means is is the binary was
....10
It will find out how many times 2 would go into it, in this case 1. It effectively drops the last digit of the binary number because in base 2 (binary) the number of times 2 goes into a number is just the same as 'shifting' everything down a space (This is a poor explanation, please ask if you need elaboration). This effectively 'iterates' through the binary number, allowing the line about to check the next bit.
This will iterate until the binary is just 1 and then half that, drop the remainder and x will equal 0,
while (x != 0)
in which case exit the loop, you have checked every bit.
Also:
'count`is possibly not the most descriptive name for a function, consider naming it something more descriptive of its purpose.
nr will always be a integer greater or equal to zero, so you should probably have the return type unsigned int
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
This program basically gives the numbers of set bits in a given integer.
For instance, lets start with the example integer 11 ( binary representation - 1011).
First flow will enter the while loop and check for the number, if it is equal to zero.
while(11 != 0)
Since 11 is not equal to zero it enter the while loop and nr is assigned the value 1 (11%2 = 1).nr += 11%2;
Then it executes the second line inside the loop (x = x/2). This line of code assigns the value 5 (11/2 = 5 ) to x.
Once done with the body of the while loop, it then again checks if x ie 5 is equal to zero.
while( 5 != 0).
Since it is not the case,the flow goes inside the while loop for the second time and nr is assigned the value 2 ( 1+ 5%2).
After that the value of x is divided by 2 (x/2, 5/2 = 2 )and it assigns 2 to x.
Similarly in the next loop, while (2 != 0 ), nr adds (2 + 2%2), since 2%2 is 0, value of nr remains 2 and value of x is decreased to 1 (2/2) in the next line.
1 is not eqaul to 0 so it enters the while loop for the third time.
In the third execution of the while loop nr value is increased to 3 (2 + 1%2).
After that value of x is reduced to 0 ( x = 1/2 which is 0).
Since it fails the check (while x != 0), the flow comes out of the loop.
At the end the value of nr (Which is the number of bits set in a given integer) is returned to the calling function.
Best way to understand the flow of a program is executing the program through a debugger. I strongly suggest you to execute the program once through a debugger.It will help you to understand the flow completely.
I was not really clear with the post increment operator that I always used with for loops.
My latest and newly acquired understanding of post increment operator is the following:
int a = 5
int b = a++ //a will increment and return back its old value 5
so b = 5
Armed with this new knowledge i decided to understand/apply it to the places where i commonly used the post increment operator as in a for loop . Now it seems like I am lost
since I am ending up with the wrong output theoretically
Consider the following code
for(int i=0 ; i< 3 ; i++)
{
std::cout << i;
}
First loop
i starts with 0 which is less than 3 so ( increment by 1 however since its i++ it returns old value 0)
so cout should display 1 // But it displays 0
Second Loop
i is now 1 which is less than 3 so i++ is applied - Now i is 2 and returns back 1
so cout should display 2 //But it display 1
Third Loop
i is now 2 which is less than 3 so i++ is applied - Now i is 3 and returns back 2
so cout should display 3 //But it display 2
Fourth Loop
i is now 3 which is not less than 3 so loop exits
Could anyone please clear my understanding and point me in the right direction.
The output should be 0,1,2 where am i going wrong ?
What you're missing is when each of those sections of the for statement happen:
for (int i = 0 ; i < 3 ; i++)
// 111111111 22222 333
The first bit happens once before any iterations are done.
The second expression is evaluated before each potential iteration and, if false, no further iterations are done.
The third bit is done at the end of each iteration, before returning to evaluate the second bit.
Now re-read that last bullet point carefully. The i++ is done at the end of an iteration, after the cout << i. And, immediately after that, the continuation condition is checked (the second part).
So the loop is effectively the same as:
{ // Outer braces just to limit scope of i, same as for loop.
int i = 0;
while (i < 3) {
cout << i;
i++;
}
}
That's why you get 0 1 2.
The semicolons in a for loop delimit three different expressions. The value of the third expression is irrelevant to the behavior of the loop. You could replace i++ with ++i and your loop would behave the same; either way, i is incremented by 1.
To observe the behavior of the increment operators, consider the following loops:
for(int i = 0 ; i++ < 3 ; ) cout << i;
/* ^^^ Nothing here! */
Note that the third expression is empty. The output is 123—0 is skipped because the test, including increment, occurs before every iteration of the loop.
How does the postincremented loop behave compared to a similar one with the preincrement operator?
for(int i = 0 ; ++i < 3 ; ) cout << i;
Now the output is 12—3 is not printed because the conditional test sees the value 3 as soon as it is incremented to that, so the loop exits.
You just need to know that the statement int i = 0 is executed first , i.e , i takes first the value 0 , checks if the condition is true and then what the loop body is executed .
Then , i is incremented.
This is a piece of code I found in my textbook for using recursion to evaluate prefix expressions. I'm having trouble understanding this code and the process in which it goes through.
char *a; int i;
int eval()
{ int x = 0;
while (a[i] == ' ') i++;
if (a[i] == '+')
{ i++; return eval() + eval(); }
if (a[i] == '*')
{ i++; return eval() * eval(); }
while ((a[i] >= '0') && (a[i] <= '9'))
x = 10*x + (a[i++] - '0');
return x;
}
I guess I'm confused primarily with the return statements and how it eventually leads to solving a prefix expression. Thanks in advance!
The best way to understand recursive examples is to work through an example :
char* a = "+11 4"
first off, i is initialized to 0 because there is no default initializer. i is also global, so updates to it will affect all calls of eval().
i = 0, a[i] = '+'
there are no leading spaces, so the first while loop condition fails. The first if statement succeeds, i is incremented to 1 and eval() + eval() is executed. We'll evaluate these one at a time, and then come back after we have our results.
i = 1, a[1] = '1'
Again, no leading spaces, so the first while loop fails. The first and second if statements fail. In the last while loop, '1' is between 0 and 9(based on ascii value), so x becomes 0 + a[1] - '0', or 0 + 1 = 1. Important here is that i is incremented after a[i] is read, then i is incremented. The next iteration of the while loop adds to x. Here x = 10 * 1 + a[2] - '0', or 10 + 1 = 11. With the correct value of x, we can exit eval() and return the result of the first operand, again here 11.
i = 2, a[2] = '4'
As in the previous step, the only statement executed in this call of eval() is the last while loop. x = 0 + a[2] - '0', or 0 + 4 = 4. So we return 4.
At this point the control flow returns back to the original call to eval(), and now we have both values for the operands. We simply perform the addition to get 11 + 4 = 15, then return the result.
Every time eval() is called, it computes the value of the immediate next expression starting at position i, and returns that value.
Within eval:
The first while loop is just to ignore all the spaces.
Then there are 3 cases:
(a) Evaluate expressions starting with a + (i.e. An expression of the form A+B which is "+ A B" in prefix
(b) Evaluate expressions starting with a * (i.e. A*B = "* A B")
(c) Evaluate integer values (i.e. Any consecutive sequence of digits)
The while loop at the end takes care of case (c).
The code for case (a) is similar to that for case (b). Think about case (a):
If we encounter a + sign, it means we need to add the next two "things" we find in the sequence. The "things" might be numbers, or may themselves be expressions to be evaluated (such as X+Y or X*Y).
In order to get what these "things" are, the function eval() is called with an updated value of i. Each call to eval() will fetch the value of the immediate next expression, and update position i.
Thus, 2 successive calls to eval() obtain the values of the 2 following expressions.
We then apply the + operator to the 2 values, and return the result.
It will help to work through an example such as "+ * 2 3 * 4 5", which is prefix notation for (2*3)+(4*5).
So this piece of code can only eat +, *, spaces and numbers. It is supposed to eat one command which can be one of:
- + <op1> <op2>
- * <op1> <op2>
<number>
It gets a pointer to a string, and a reading position which is incremented as the program goes along that string.
char *a; int i;
int eval()
{ int x = 0;
while (a[i] == ' ') i++; // it eats all spaces
if (a[i] == '+')
/* if the program encounters '+', two operands are expected next.
The reading position i already points just before the place
from which you have to start reading the next operand
(which is what first eval() call will do).
After the first eval() is finished,
the reading position is moved to the begin of the second operand,
which will be read during the second eval() call. */
{ i++; return eval() + eval(); }
if (a[i] == '*') // exactly the same, but for '*' operation.
{ i++; return eval() * eval(); }
while ((a[i] >= '0') && (a[i] <= '9')) // here it eats all digit until something else is encountered.
x = 10*x + (a[i++] - '0'); // every time the new digit is read, it multiplies the previously obtained number by 10 and adds the new digit.
return x;
// base case: returning the number. Note that the reading position already moved past it.
}
The example you are given uses a couple of global variables. They persist outside of the function's scope and must be initialized before calling the function.
i should be initialized to 0 so that you start at the beginning of the string, and the prefix expression is the string in a.
the operator is your prefix and so should be your first non-blank character, if you start with a number (string of numbers) you are done, that is the result.
example: a = " + 15 450"
eval() finds '+' at i = 1
calls eval()
which finds '1' at i = 3 and then '5'
calculates x = 1 x 10 + 5
returns 15
calls eval()
which finds '4' at i = 6 and then '5' and then '0'
calclulates x = ((4 x 10) + 5) x 10) + 0
returns 450
calculates the '+' operator of 15 and 450
returns 465
The returns are either a value found or the result of an operator and the succeeding results found. So recursively, the function successively looks through the input string and performs the operations until either the string ends or an invalid character is found.
Rather than breaking up code into chunks and so on, i'll try and just explain the concept it as simple as possible.
The eval function always skips spaces so that it points to either a number character ('0'->'9'), an addition ('+') or a multiply ('*') at the current place in the expression string.
If it encounters a number, it proceeds to continue to eat the number digits, until it reaches a non-number digit returning the total result in integer format.
If it encounters operator ('+' and '*') it requires two integers, so eval calls itself twice to get the next two numbers from the expression string and returns that result as an integer.
One hair in the soup may be evaluation order, cf. https://www.securecoding.cert.org/confluence/display/seccode/EXP10-C.+Do+not+depend+on+the+order+of+evaluation+of+subexpressions+or+the+order+in+which+side+effects+take+place.
It is not specified which eval in "eval() + eval()" is, well, evaluated first. That's ok for commutative operators but will fail for - or /, because eval() as a side effect advances the global position counter so that the (in time) second eval gets the (in space) second expression. But that may well be the (in space) first eval.
I think the fix is easy; assign to a temp and compute with that:
if (a[i] == '-')
{ i++; int tmp = eval(); return tmp - eval(); }
This will be my last question for the evening and a while. I have worked my way through a 100 mark Java assessment and I am now stuck on my final two points. If anyone could help me out, it would be greatly appreciated. I am tired, feeling like a grade-A nub and just want it over with!
Study the two instance methods below and then select only the options that are correct.
public char[] methodA()
{
char[] alphas = {'s', 't', 'e', 'a', 'm'};
char temp = alphas[0];
int i = 0;
while (i < alphas.length - 1)//1
{
alphas[i] = alphas[i+1]; //2
i++;
}
alphas[alphas.length-1]=temp;
return alphas;
}
public char methodB()
{
char [] alphas = {'s','a','u','s','a','g','e'};
char first = alphas[0];
for (int i= 1; i < alphas.length; i++) //3
{
if (alphas[i] < first) //4
{
first = alphas[i];
}
}
return first;
}
The assignment statement labelled //2 will put a copy of the char
element one to the right of the current element in alphas into the
current element in alphas.
The for loop header labelled //3 will be evaluated 7 times.
The if statement labelled //4 will update the value held by the
variable first if the value held in the current element in alphas
comes before the current value of first.
The boolean condition in the line labelled //1 will evaluate to
false repeatedly until i takes the value 4.
The returned value on invoking methodA is a char array containing
the values 't', 'e', 'a', 'm' and 's'.
The returned value from invoking methodB is the character 'u'.
I believe 1 to be true. Not sure why.
I think 2 is false as the for loop is evaluated 6x, not 7.
Not sure on 3 or 4.
5 I got to be true
6 I got to be false.
If anyone can help I owe them a beer, a cookie and a cuddle!!
It is true because alphas[i] = alphas[i+1] essentially will take element at position i and and replace it with the next element in the array at i + 1 (or another way to say it, its adjacent element).
I believe this is false, the keyword here is evaluated. A loop will evaluate to the stopping point, check the exiting condition, then kick out. So it will finish evaluating 1, 2, 3, 4, 5, 6, 7 <--- evaluates the value and kicks
This will be true. the expression if (alphas[i] < first) is asking if the value stored in first is greater than the value in alphas[i] or inversely ... if alphas[i] is less than first. This is essentially performing a max/min algorithm because the final number in first will be the smallest value in the alphas array. In this case, the letters will be evaluated based upon their ascii values.
This is false. The expression will evaluate to true until 4. If this were not the case then the question 1 would not be true because it would simply throw an IndexOutOfBoundsException.
This is true, because it is taking the adjacent char and placing it in the current position, then the line alphas[alphas.length-1]=temp puts the first char into the last position. More specifically, after the while your array will look like this: { t, e, a, m, m } then after the last line it will complete the set with { t, e, a, m, s }
The last one is false. Like I mentioned in question 3, it is essentially performing a min search. the character u has a greater valued ascii value than any other letter in the sequence. a is the lowest letter in the set.
Great job on making an attempt.
1 is true (a[i+1] is to the right of a[i], so a[i] = a[i+1] copies the value on the right to the current)
2 is true because the loop condition is evaluated 7 times -- 6 times as true causing the body to be executed 6 times, and then 1 time as false to break the loop.
3 sounds true, a value like 'b' is considered to "come before" a value like 'd' (comparing numeric ascii codes)
4 is true because the condition 4 < (5 - 1) is false
5 is true as you think
6 is false - should return 'a'
please skip the cuddle!