Integer value assignment in c++ - c++

I'm pretty new to C++ and I have the following simple program:
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
cout << sum; // outputs 15
return 0;
}
I receive always the output 15, although I've changed the value of b to 6.
Thanks in advance for your answers!

Execution of your code is linear from top to bottom.
You modify b after you initialize sum. This modification doesn't automatically alter previously executed code.

int sum = a + b; writes the result of adding a and b into the new variable sum. It doesn't make sum an expression that always equals the result of the addition.

There are already answers, but I feel that something is missing...
When you make an assignment like
sum = a + b;
then the values of a and b are used to calculate the sum. This is the reason why a later change of one of the values does not change the sum.
However, since C++11 there actually is a way to make your code behave the way you expect:
#include <iostream>
int main() {
int a = 5,b = 10;
auto sum = [&](){return a + b;};
b = 6;
std::cout << sum();
return 0;
}
This will print :
11
This line
auto sum = [&](){return a + b;};
declares a lambda. I cannot give a selfcontained explanation of lambdas here, but only some handwavy hints. After this line, when you write sum() then a and b are used to calculate the sum. Because a and b are captured by reference (thats the meaning of the &), sum() uses the current values of a and b and not the ones they had when you declared the lambda. So the code above is more or less equivalent to
int sum(int a, int b){ return a+b;}
int main() {
int a = 5,b = 10;
b = 6;
std::cout << sum(a,b);
return 0;
}

You updated the b value but not assigned to sum variable.
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
sum = a + b;
cout << sum; // outputs 11
return 0;
}

Related

Trying to compute e^x when x_0 = 1

I am trying to compute the Taylor series expansion for e^x at x_0 = 1. I am having a very hard time understanding what it really is I am looking for. I am pretty sure I am trying to find a decimal approximation for when e^x when x_0 = 1 is. However, when I run this code when x_0 is = 0, I get the wrong output. Which leads me to believe that I am computing this incorrectly.
Here is my class e.hpp
#ifndef E_HPP
#define E_HPP
class E
{
public:
int factorial(int n);
double computeE();
private:
int fact = 1;
int x_0 = 1;
int x = 1;
int N = 10;
double e = 2.718;
double sum = 0.0;
};
Here is my e.cpp
#include "e.hpp"
#include <cmath>
#include <iostream>
int E::factorial(int n)
{
if(n == 0) return 1;
for(int i = 1; i <= n; ++i)
{
fact = fact * i;
}
return fact;
}
double E::computeE()
{
sum = std::pow(e,x_0);
for(int i = 1; i < N; ++i)
{
sum += ((std::pow(x-x_0,i))/factorial(i));
}
return e * sum;
}
In main.cpp
#include "e.hpp"
#include <iostream>
#include <cmath>
int main()
{
E a;
std::cout << "E calculated at x_0 = 1: " << a.computeE() << std::endl;
std::cout << "E Calculated with std::exp: " << std::exp(1) << std::endl;
}
Output:
E calculated at x_0 = 1: 7.38752
E calculated with std::exp: 2.71828
When I change to x_0 = 0.
E calculated at x_0 = 0: 7.03102
E calculated with std::exp: 2.71828
What am I doing wrong? Am I implementing the Taylor Series incorrectly? Is my logic incorrect somewhere?
Yeah, your logic is incorrect somewhere.
Like Dan says, you have to reset fact to 1 each time you calculate the factorial. You might even make it local to the factorial function.
In the return statement of computeE you are multiplying the sum by e, which you do not need to do. The sum is already the taylor approximation of e^x.
The taylor series for e^x about 0 is sum _i=0 ^i=infinity (x^i / i!), so x_0 should indeed be 0 in your program.
Technically your computeE computes the right value for sum when you have x_0=0, but it's kind of strange. The taylor series starts at i=0, but you start the loop with i=1. However, the first term of the taylor series is x^0 / 0! = 1 and you initialize sum to std::pow(e, x_0) = std::pow(e, 0) = 1 so it works out mathematically.
(Your computeE function also computed the right value for sum when you had x_0 = 1. You initialized sum to std::pow(e, 1) = e, and then the for loop didn't change its value at all because x - x_0 = 0.)
However, as I said, in either case you don't need to multiply it by e in the return statement.
I would change the computeE code to this:
double E::computeE()
{
sum = 0;
for(int i = 0; i < N; ++i)
{
sum += ((std::pow(x-x_0,i))/factorial(i));
cout << sum << endl;
}
return sum;
}
and set x_0 = 0.
"fact" must be reset to 1 each time you calculate factorial. It should be a local variable instead of a class variable.
When "fact" is a class varable, and you let "factorial" change it to, say 6, that means that it will have the vaule 6 when you call "factorial" a second time. And this will only get worse. Remove your declaration of "fact" and use this instead:
int E::factorial(int n)
{
int fact = 1;
if(n == 0) return 1;
for(int i = 1; i <= n; ++i)
{
fact = fact * i;
}
return fact;
}
Write less code.
Don't use factorial.
Here it is in Java. You should have no trouble converting this to C++:
/**
* #link https://stackoverflow.com/questions/46148579/trying-to-compute-ex-when-x-0-1
* #link https://en.wikipedia.org/wiki/Taylor_series
*/
public class TaylorSeries {
private static final int DEFAULT_NUM_TERMS = 50;
public static void main(String[] args) {
int xmax = (args.length > 0) ? Integer.valueOf(args[0]) : 10;
for (int i = 0; i < xmax; ++i) {
System.out.println(String.format("x: %10.5f series exp(x): %10.5f function exp(x): %10.5f", (double)i, exp(i), Math.exp(i)));
}
}
public static double exp(double x) {
return exp(DEFAULT_NUM_TERMS, x);
}
// This is the Taylor series for exp that you want to port to C++
public static double exp(int n, double x) {
double value = 1.0;
double term = 1.0;
for (int i = 1; i <= n; ++i) {
term *= x/i;
value += term;
}
return value;
}
}

Recursively counting a number of values that satisfies a condition and return that number

I need to count how many cubes of values between a and b (2 and 9 in this example) end with numbers between 2 and 5. Everything has to be done with recursion.
The output of this code is
part c = recc = 4
32767
0
It does not make sense to me. It calculates the value of n correctly, but then once asked to return it, returns either 0 or 32767, as if it was not defined.
Can anyone pinpoint the issue?
#include <iostream>
#include <string>
using namespace std;
void partb(int a, int b){
if(a<=b){
int p = (a*a*a)%10;
else if(p>=2 && p<=5){
cout<<a*a*a<<" ";
}
partb(a+1, b);
}
}
int recc(int n, int a, int b){
int p = (a*a*a)%10;
if(a>b){
cout<<"recc = " << n << endl;
return n;
}
else if(a<=b){
if(p>=2 && p<=5){
n++;
}
recc(n, a+1, b);
}
}
int partc(int a, int b){
int n = recc(0, a, b);
cout<<endl<< "part c = " << recc(0, a, b) << endl;
return n;
}
int main(){
int n=partc(2,9);
cout << n << endl;
return 0;
}
Not all control paths in your function return a value, so you were getting undefined behaviour when using the return value.
Now, this wasn't helped by the fact that the function itself is needlessly complicated. Let's rewrite it to use common practice for recursion:
int recc(int a, int b)
{
if (a > b) return 0;
int p = (a*a*a)%10;
int n = (p>=2 && p<=5) ? 1 : 0;
return n + recc(a+1, b);
}
Now your function is simpler. The recursion termination condition is right at the top. The function then decides whether a will contribute 1 or 0 to the count. And finally you return that value plus the count for a smaller range.
Notice how return n + recc(a+1, b); has broken the problem into a simple local solution combined with the recursive result of a reduced scope.
The invocation becomes simpler too, because you no longer have to pass in a redundant argument:
int partc(int a, int b)
{
int n = recc(a, b);
cout << endl << "part c = " << n << endl;
return n;
}

Calculate power with a recursive function on C++

I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}

What parameters this formula takes when in "accumulate"?

This code is copied from another user question and I`m curious how accumulate works here.
I get the correct result from this code, but would like to know what parameters lcm takes when in "accumulate". The init as A and the sum of the range as b? Please help
#include <numeric>
int gcd(int a, int b)
{
for (;;)
{
if (a == 0) return b;
b %= a;
if (b == 0) return a;
a %= b;
}
}
int lcm(int a, int b)
{
int temp = gcd(a, b);
return temp ? (a / temp * b) : 0;
}
int main()
{
int arr[] = { 5, 7, 9, 12 };
int result = std::accumulate(arr, arr + 4, 1, lcm);
std::cout << result << '\n';
}
The first argument that lcm will take is the accumulated value so far (which starts at 1, the third argument of std::accumulate), and the second argument will be an element in arr. Next, whatever lcm returns is passed as the first argument and the next element in arr as the second.
See a reference for more details.
You could easily write a and b to the standard output inside lcm to see what's happening.

Appending a number to a number?

How cold I do the following:
say I have the number 10 and would like to append the number 317 to it. The resulting integer would be 10317. How can this be done. Also, once I have this number, how could I then for example remove the 17 off the end. Without using strings, and without obvious solving and adding.
Thanks
This will append both numbers
int append_a_and_b_as_int(int a, int b)
{
for(int tmp = b; tmp > 0; tmp % 10)
{
a *= 10;
}
return a + b;
}
This will get rid of the last n numbers
int remove_n_numbers_from_a(int n, int a)
{
for(int i = 0; i < n; i++)
{
a /= 10;
}
return a;
}
Appending :
int foo(int a, int b)
{
return a*pow(10, floor(log10(b))+1)+b;
}
Removing :
int bar(int a, int b)
{
return a/pow(10, floor(log10(b))+1);
}
For the first one:
int a = 10;
int b = 317;
int result = a * 1000 + b;
For the second:
int result2 = result / 100;
If this is something you need to do in your workplace I'd advise quitting.
You can treat your two numbers as numeric data and solve the question, or you can treat them as strings and use an append.