Can you explain what this programs are doing? [closed] - c++

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
So I have to do trace tables for this but I don't understand everything from the code such as a==b; c-=--d; b+=a%10
int a=3,b=4, c=5,d=6;
if(a==b)c++;else c--;
while(d>2){
c-=--d; b-=a;
}
int a=3,b=0, c=7,d=5;
if(a=b)d++;else c--;
while(d>2){
c+=a;a+=--d;
}
int a=3,b=11, c=15,d=5;
if(a>b)d--;else c--;
for(;d>3;c/=a){
b=--d;
}
int a=31,b=14, c=95,d=56;
if(a<b)d++;else c--;
while(d>53){
b+=a%10;d--; a/=10;
}

c -= --d;
mean
c = c - (--d);
The same goes for
b += a%10
which mean
b = b + (a%10)
You can do the same with *, / and % operator
--d mean that d is decreased before the instruction get executed, ++d would mean d will be increased before the instruction got executed
if(a==b)c++;else c--;
is the same as the more readable
if (a==b)
{
c = c + 1;
}
else
{
c = c - 1;
}

int a=3,b=4, c=5,d=6;
if(a==b) c++;
else c--;
while(d>2){
c-=--d; b-=a;
}
The == operator means comparasion if a and b are the same. In this case a and b are different, so it goes to the else and decrements the c variable for 1.
The -- after c means that the value is decreased before the instruction gets executed.
So, that means c will become 4.
While d > 2, means it will loop as long as d > 2.
c -= --d; b-=a;
That means:
c = c - --d
b = b - a
So, that means the value of d will decrease by 1 each time the loop is executed and will keep looping until it's >2.
int a=3,b=0, c=7,d=5;
if(a=b)d++;
else c--;
while(d>2){
c+=a;a+=--d;
}
The = operator means to assign a value, so when it executed a=b, it will assign the value of b to a but since it's 0, which means false it will go to else and decrease the value of c by 1.
So c will become 6.
The while loop is similar to the first one.
int a=3,b=11, c=15,d=5;
if(a>b)d--;else c--;
for(;d>3;c/=a){
b=--d;
}
This one is quite simple if-statement. It checks whether a is bigger than b. If so, it executes d--, else c--.
As for the for-loop, it goes until d > 3 and it executes c /= a each time as well.
c /= a also can be written as c = c / a.
int a=31,b=14, c=95,d=56;
if(a<b)d++;else c--;
while(d>53){
b+=a%10;d--; a/=10;
}
The last one if statement is simple as well and similar to the above one.
The while loop will be executed until d > 53.
The command inside b+=a%10;d--; a/=10; can be also written as:
b = b + a % 10
d--
a = a / 10

a==b
This is an important Boolean condition that checks whether a is equal to b and returns true if it is and returns false if it is not. This can be changed (casted) to an int of value 1 or 0.
c-=--d;
I wouldn't prefer writing such code.
However c -= k statement is equivalent to c = c-k
and --d; is same as decrement d by 1.
The code does these two things in one statement. But order is important. Since -- comes before d, first this decrement is evaluated and then the -= operator is considered.
Similarly for +=
I would suggest looking up a good C++ learning resource such as www.cplusplus.com or www.learncpp.com

Related

if-else statement only works in a specific order and I don't know why [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I recently started learning how to program and one of the tasks I was assigned was to write an algorithm in c++ that would ask for three numbers, then pick out the smallest one. A segment of the code I wrote is as follows.
if (a <= b) { a = d; }
else { b = d; }
This is supposed to pick out the smallest of the first two numbers and then "link it" to d, but after a while of getting the wrong results I realized that regardless of the values of a and b it gives d a value of 0.
Turns out this only works if I write the same thing with the characters flipped, with the input variables coming last:
if (a <= b) { d = a; }
else { d = b; }
Why is that? Is there something about the syntax of c++ that I should know?
Seems like a strangely specific rule to have...
EDIT: I accidentally wrote {a = d} instead of {d = a} when writing this post, it should as I intended now.
Here's the rest of the code (it works, but only after flipping the characters as I said earlier)
#include <iostream>
using namespace std;
int main() {
int a,b,c,d,min;
cin >> a >> b >> c;
if (a<=b) {d = a;}
else {d = b;}
if (c<=d) {min = c;}
else {min = d;}
cout << min << endl;
}
In the first code fragment, you are not assigning to d at all. Assignment (=) operator assigns the rvalue (right hand side) to the lvalue (left hand side). This is very standard syntax.

Mathematic equation solved recursively in C++ [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 6 years ago.
Improve this question
I have a task to make a code which will write 100 first numbers of an equation (or a function, I don't know what this is)
A(n) = (A(n-1))^2 -n*A(n-2) where A(1) = 1 and A(2) = 1
It has to be solved recursively. I have written this code so far
#include <iostream>
using namespace std;
int rekurzija(int n){
if(n=1){
return 1;
}
if(n=2){
return 1;
}
if(n>2){
return rekurzija(n-1)*rekurzija(n-1)-n*rekurzija(n-2);
}
}
int main(){
for(int n=1;n<101;n=n+1){
cout << rekurzija(n) << endl;
}
}
The problem is that the program returns 1 hundred times instead of 1,1,-2,0,...(instead of actually solving this function). What is wrong in this code?
You are using simple assignment operator = instead of Is equals to relational operator == in your rekurzija() function for if conditions
if(n = 1) //here `n = 1`is an assignment statement
{
//something...
}
What happens if you use = instead of ==?
The if condition will always evaluate to be true if the assigned value in the assignment statement is non-zero number.
Note: An assignment to zero evaluates to be false i.e, for if(n = 0), the if block will not be entered. You don't have any such if blocks in your code.
So your first if is always evaluated to be true because you are assigning a non-zero value i.e, 1 and thus your function always returns 1. that's the reason why you get 100 1's as your answer.
So, instead try changing all the if conditions to something like:
if(n == 1)
{
//something...
}
This would check if n is equals to 1 or not. If n is equal to 1 then the if block is entered, else it would not enter the if block and the next if condition is checked.
Note: Just remember this while using the = and == operators
= is for assignment
== is for comparison
When you compare things in C++ you need to do it like:
if (a == b)
and not
if (a = b)
The latter will assign b to a and return the value of a.

Inifinite loop makes variable come out as 0

I have this piece of code in my school book.
#include<iostream>
using namespace std;
int main() {
int x=10,c=1;
while (c < 5) {
x += x*c;
c *= 2;
c++;
c -= 2;
cout << "X=" << x<<'\n';
}
system("pause");
return 0;
}
As you can see it's an infinite loop, when logically traced, it should show 20,40,80 and so on.
However it always shows 0.
when adding system("pause") after each loop cycle it shows the correct values, but when left as shown above (infinitely looping) it shows zero.
Any ideas of the reason?
c is always 1 no matter what. The loop becomes infinite. Eventually, X becomes 0 due to integer overflow.
c = 1
c *= 2; c = 2
c++; c = 3
c -= 2; c = 1 <-- infinite
Here is my answer for your questions:
Why do you get infinitely looping?
awesomeyi did answer you above, because the condition of the while loop is always true, so it is never ended.
Why does X always equal to 0?
Please pay your attention on X varable, its value will be increased after ending one loop x += x*c. Because you are in the infinitely loop, x's value will be increased forever until greater than the limited value of an integer variable. Then, the value will be set as zero. Please see my output when running your code.
Removing the pause doesn't cause it to always show zero. It just prints output so quickly that zeroes are all you see at the bottom. Add the pause back in and click through about 30-40 iterations and see if it helps you understand what is happening.

How does that recursive function work?

Might be a very basic question but I just got stuck with it. I am trying to run the following recursive function:
//If a is 0 then return b, if b is 0 then return a,
//otherwise return myRec(a/2, 2*b) + myRec(2*a, b/2)
but it just gets stuck in infinite loop. Can anybody help me to run that code and explain how exactly that function works? I built various recursive functions with no problems but this one just drilled a hole in my head.
Thanks.
Here is what I tried to do:
#include<iostream>
int myRec(int a, int b){
if (a==0){
return b;
}
if (b==0){
return a;
}
else return myRec(a/2, 2*b) + myRec(2*a, b/2);
}
int main()
{
if (46 == myRec(100, 100)) {
std::cout << "It works!";
}
}
Well, let us mentally trace it a bit:
Starting with a, b (a >= 2 and b >= 2)
myRec(a/2, 2*b) + something
something + myRec(2*a', b'/2)
Substituting for a/2 for a' and 2*b for b', we get myRec(2*(a/2), (b*2)/2), which is exactly where we started.
Therefore we will never get anywhere.
(Note that I have left out some rounding here, but you should easily see that with this kind of rounding you will only round down a to the nearest even number, at which point it will be forever alternating between that number and half that number)
I think you are missing on some case logic. I last program in C ages ago so correct my syntax if wrong. Assuming numbers less than 1 will be converted to zero automatically...
#include<iostream>
int myRec(int a, int b){
// Recurse only if both a and b are not zero
if (a!=0 && b!=0) {
return myRec(a/2, 2*b) + myRec(2*a, b/2);
}
// Otherwise check for any zero for a or b.
else {
if (a==0){
return b;
}
if (b==0){
return a;
}
}
}
UPDATE:
I have almost forgot how C works on return...
int myRec(int a, int b){
if (a==0){
return b;
}
if (b==0){
return a;
}
return myRec(a/2, 2*b) + myRec(2*a, b/2);
}
VBA equivalent with some changes for displaying variable states
Private Function myRec(a As Integer, b As Integer, s As String) As Integer
Debug.Print s & vbTab & a & vbTab & b
If a = 0 Then
myRec = b
End If
If b = 0 Then
myRec = a
End If
If a <> 0 And b <> 0 Then
myRec = myRec(a / 2, 2 * b, s & "L") + myRec(2 * a, b / 2, s & "R")
End If
End Function
Sub test()
Debug.Print myRec(100, 100, "T")
End Sub
Running the test in Excel gives this (a fraction of it as it overstacks Excel):
T: Top | L: Left branch in myRec | R: Right branch in myRec
The root cause will be the sum of the return which triggers more recursive calls.
Repeating of the original values of a and b on each branch from level 2 of the recursive tree...
So MyRec(2,2) = MyRec(1,4) + MyRec(4,1)
And MyRec(1,4) = MyRec(.5,8) + MyRec(2,2)
So MyRec(2,2) = MyRec(.5,8) + MyRec(2,2) + MyRec(4,1)
Oops.
(The .5's will actually be zeroes. But it doesn't matter. The point is that the function won't terminate for a large range of possible inputs.)
Expanding on gha.st's answer, consider the function's return value as a sum of expressions without having to worry about any code.
Firstly, we start with myRec(a,b). Let's just express that as (a,b) to make this easier to read.
As I go down each line, each expression is equivalent, disregarding the cases where a=0 or b=0.
(a,b) =
(a/2, 2b) + (2a, b/2) =
(a/4, 4b) + (a, b) + (a, b) + (4a, b/4)
Now, we see that at a non-terminating point in the expression, calculating (a,b) requires first calculating (a,b).
Recursion on a problem like this works because the arguments typically tend toward a 'base case' at which the recursion stops. A great example is sorting a list; you can recursively sort halves of the list until a list given as input has <= 2 elements, which is trivial without recursion. This is called mergesort.
However, your myRec function does not have a base case, since for non-zero a or b, the same arguments must be passed into the function at some point. That's like trying to sort a list, in which half of the list has as many elements as the entire list.
Try replacing the recursion call with:
return myRec(a/2, b/3) + myRec(a/3, b/2);

Confusing outcome of C conditional operator [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
int a=1,b=2,c=3;
int x=1;
int y=10;
a = x ? b : c;
cout<< a; // Outputs 2 (the value of b)
a = y ? b : c;
cout<< a; // Outputs 2 (the value of b)
Now, look at the following.
a=0;
x=0;
a = x ? b : c;
cout<< a; // Outputs 3 (the value of c !!!!)
Why this unusual behaviour ?? Only when a and x are both 0, the expression evaluates to false , otherwise, always it is true. Please explain.
Because x is 0.
Recall that the ternary operator, if written condition ? a : b returns a if condition is true and b otherwise. You are using it with numbers, and any number except 0 is considered true as a boolean.
x ? b : c in your case is 0 ? 2 : 3, and since 0 is false, it evaluates to 3. That 3 then gets assigned to your a variable and printed - nothing unusual going on here.
This looks perfectly fine. The expression a = x ? b : c is equivalent to
if (x)
a = b;
else
a = c;
x will evaluate to true for any nonzero value, so if you assign 0 to x prior to executing the expression, the value of c will be assigned to a, and if you assign 1 to x prior to executing the expression, the value of b will be assigned to a. The prior value of a is immaterial here.
The reason is that in C and C++ any non-zero value is evaluated as "true".
The value of 'a' only depends on the value of 'x' and 'y'. Since initially 'x' and 'y' are both greater than 0, the condition evaluates to true and you get the value of 'b' in 'a'.
In the second case, 'x' is zero which evaluates the condition to false which causes 'a' to have the value of 'c'.
a = x ? b : c;
is the same as
if(x != 0) {
a = b;
} else {
a = c;
}
Therefore if you set x = 0 you will get a = c.