How to use functions in c++? - c++

I am supposed to get the following code to display something along the lines of: "The sum of 1 to 10 is 55." (The larger number can be any number that was just the example I got.) I was given this code to use.
#include <iostream>
using namespace std;
// Compute the sum of all of the numbers from 1 to n where n
// is a natural number
// use the formula: n(n+1)/2
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
int main()
{
int sum = 0;
int maxNumber;
// get the maxNumber for the function call
cout << "Enter a whole number greater than 0" << endl;
cin >> maxNumber;
// call compute sum
compute_sum(maxNumber); // Call to compute_sum function
// display the sum calculated by the compute_sum function
cout << "The sum of 1 to " << maxNumber;
cout << " is " << sum << endl;
return 0;
}
I do not understand how funcctions work at all and do not have any idea how I would go about getting this to work. The only thing I know about this (and this is from the teacher) is that the change required is not major. "Note: If you are making major changes to the main and compute_sum funtions you are probably
doing way too much work." I have tried changing the function to an int function with a return but I could not get it to work properly (most likely due to not knowing how functions work). So can someone please help me?

The part you're missing is the return type of the function, and then to actually return that value from the function.
At the moment you have
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
A function prototype in C looks pretty much like this
<return type> <name> (<parameters>)
{
// your logic here
return <your_own_variable> // Note: You can omit this if the return type is void (it means the function doesn't return anything)
}
You want to modify your function so you are returning the integer value you're calculating inside of it
int compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
return sum_to_limit;
}
So what happens is after main runs, when the the point of execution hits
compute_sum(maxNumber);
The program flow jumps to that function and executes the code inside of it. When the function finishes, it returns the value back to where it was originally called from. So you also need to add this to store the value returned
int result = compute_sum(maxNumber);
and then make sure to output that value to the user.
You can also make the computer_sum function a little more terse my not storing a temporary variable, you can just do this
int compute_sum(int limit) // compute_sum function
{
return limit * (limit + 1) / 2;
}
I hope that helps. There's a lot more going on behind the scenes but that's the basic idea. Good luck! :)

Related

Incremented variable "never used"?

I'm kind of inexperienced with C++, and I'm converting a program that I wrote in C to C++. I have a RollDice function that takes numbers that I read in from a text file and uses them to generate the number. This is the function in C:
void rollDice(Move *move, GameState *game_state) {
int diceNum1 = 0;
int diceNum2 = 0;
int randomNumber1 = 0;
int randomNumber2 = 0;
randomNumber1 = game_state->randomNums[game_state->current_roll]; //gets the random number from the array randomNum (which holds the numbers from the text file), at index "current_roll"
game_state->current_roll++; //increments so the next random number will be the next number in the array
diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
randomNumber2 = game_state->randomNums[game_state->current_roll];
game_state->current_roll++;
diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
move->dice_sum = diceNum1 + diceNum2;
printf("You rolled a %d!\n", move->dice_sum);
}
This works just how I want it to when I run it. Now, when converting my program to C++ I had to change things around. My parameters are now pass by reference and I made a vector to store the list of random numbers from the text file:
void rollDice(Move& move, GameState& game_state) {
std:: vector<int> randomNums = game_state.getRandomNums();
int current_roll = game_state.getCurrentRoll();
int diceNum1 = 0;
int diceNum2 = 0;
int randomNumber1 = 0;
int randomNumber2 = 0;
randomNumber1 = randomNums.at(current_roll);
current_roll++;
diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
randomNumber2 = randomNums.at(current_roll);
current_roll++; //this line is grayed out and says "this value is never used"
diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
move.dice_sum = diceNum1 + diceNum2;
std:: cout << "You rolled a " << move.dice_sum << "!\n";
}
My code is telling me that the second time I increment current_roll it is unused. This didn't happen for my C code, so why is it happening here and how can I fix it? I'm completely lost.
It's never used because you write to the variable, but never read from it. Having a variable that you never read is effectively meaningless.
Presumably your game_state.getCurrentRoll function returns an integer, when you store this, you store the value (rather than a reference to the value), thus incrementing it doesn't increment the current roll inside the game_state, instead you should add a function to your game_state called makeRoll for example which increments the game_states internal current_roll value.
This is different from your C code which increments the current_roll value directly using game_state->current_roll++ (alternatively you could make game_state.current_roll public and increment it the same way as in your C code).
From your comment I assume you have some class:
class GameState {
private:
int current_roll;
...
public:
int getCurrentRoll() {
return current_roll;
}
...
}
All you'd need to do is add another function to your class to increment the current_roll:
class GameState {
private:
int current_roll;
...
public:
int getCurrentRoll() {
return current_roll;
}
void makeRoll() {
current_roll++;
}
...
}
Then you can call it as normal.
Regarding your new issue in the comments regarding the error:
parameter type mismatch: Using 'unsigned long' for signed values of type 'int'.
This is because the signature of at is std::vector::at( size_type pos ); That is, it expects a value of type size_type which is an unsigned integer type, rather than int as you're using which is signed. This post may be helpful.

Why does the function always refer to one specific parameter?

In the following code:
int sum(int a=40, int b=20)
{
int result;
result = a + b;
return (result);
}
int main ()
{
int a = 100;
int b = 200;
int result;
result = sum(a, b);
cout << "Total value is :" << result << endl;
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
This produces:
Total value is : 300
Total value is : 120
Why does the:
sum(a)
add the (int a) in the 2nd block to the (int b) in the 1st block?
Im confused why the (b) value in the 1st block is used in (sum(a)), but the (a) value in the 1st block is ignored.
int sum(int a=40, int b=20) {
...
}
declares the parameters a to be 40 and b to be to 20, if not specified. This is a compiler service, so sum(a) becomes sum(a, 20) (b not specified). Similar to this, sum() becomes sum(40, 20). a and b in your method sum are default parameters.
In function sum you are using default arguments. That's why when you call
result = sum(a); // where a = 100 and the second parameter is ommited
in the function sum, the first parameter is take the value of this caller's a (= 100), and as the second parameter is absent from the caller's end, the default b (= 20) will be used as b. Hence the result is
100 + 20
= 120
As David Rodríguez suggested in the first comment, use different variables name (say sum (int x, int y)) for no ambiguity and better understanding.
In order to make it shorter:
int sum(int a=40, int b=20)
{
return a + b;
}
int main ()
{
int a = 100;
int b = 200;
cout << "Total value is :" << sum(a, b) << endl;
cout << "Total value is :" << sum(a) << endl;
return 0;
}
In the sum(a,b) both of the parameters have values => it does a+b => 100 + 200 which is 300.
In the sum(a) the second parameter is not set, the function use the default value (ie: 20) => a + 20 => 100 + 20 which is 120
The a & b you define in your main are not the one of the sum function
Well, you should read a bit about default parameters in C++. Where you are on it, I recommend you to research a bit about overloading, since they are somewhat related.
On the first call you do to the sum() function, you provide both parameter to the call, so the variables a and b ,that you declared, are used, hence you get 100+200=300. On the second call tho, you only provide one parameter, so the second one uses the default parameter value, i.e. a=100, b gets the default value (20), so you get 100+20=120.
When you write a function like
returntype Function_name(data_type some_value), then this is called default parameters.
For eg: if you write a function like,
int calculate_area(int lenght=20, int width=25)
Then when you call this function from main, you can either pass values to length and width like this,
int main() {
int a=50;
int b=60;
calculate_area(a,b);
}
Or you can call it like this...
int main() {
calculate_area();
}
See the difference, we are not passing any parameter, still it is a valid call to the function, because in this case.... the default values mentioned by you for length and width will be considered, which in this case is 20 & 25.
And about variables 'a' & 'b' in your code, looks like you are getting confused between name of the variables. Main() and Sum() are two different functions.
'a' of sum has nothing to do with 'a' of main. You will understand this when you will read how the variables are stored in stack and all.

Bernoulli numbers with Boost are different from Mathematica

In the latest Boost, there is a function to compute the Bernoulli number, but I miss what it does exactly.
For example, Mathematica, Python mpmath and www.bernoulli.org say that:
BernoulliB[1] == -1/2
but the boost version
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/special_functions/bernoulli.hpp>
boost::multiprecision::cpp_dec_float_100 x = bernoulli_b2n<boost::multiprecision::cpp_dec_float_100>(1);
returns 0.166667
Why this difference? Am I missing something?
All odd Bernoulli numbers are zero, apart of B1, which you know is -1/2. So,
boost::math::bernoulli_b2n returns the only even (2nth) Bernoulli numbers.
For example, to get B4 you need to actually pass 2:
std::cout
<< std::setprecision(std::numeric_limits<double>::digits10)
<< boost::math::bernoulli_b2n<double>(2) << std::endl;
and if you pass 1, you get B2.
See docs: http://www.boost.org/doc/libs/1_56_0/libs/math/doc/html/math_toolkit/number_series/bernoulli_numbers.html
Of course, you can make a simple wrapper, to imitate preferred syntax1:
double bernoulli(int n)
{
if (n == 1) return -1.0 / 2.0; // one
if (n % 2) return 0; // odd
return boost::math::bernoulli_b2n<double>(n / 2);
}
int main()
{
std::cout << std::setprecision(std::numeric_limits<double>::digits10);
for (int i = 0; i < 10; ++i)
{
std::cout << "B" << i << "\t" << bernoulli(i) << "\n";
}
}
or even a class with overloaded operator[] (for demanding persons ;) ):
class Bernoulli
{
public:
double operator[](int n)
{
return bernoulli(n);
}
};
or even make use of template magic and do all this checks at compile time (I will left it as an exercise for a reader ;) ).
1Please note, that this exact function body is not well verified and can contains mistakes. But I hope you've got the idea of how you can make a wrapper.

Different IDE's different output?

I have the following problem : I write my code with the Qt IDE. I was informed that when people try to compile it with other IDE's (like codeblocks, or visual studio) The output they get is different and that there are maufunctions. Any ideas what can be causing this ? I will give you an example:
This is Newton's Method with a function who's root is 2.83something. I get the same, correct calulations each time I run it in Qt. I get "nan" in code blocks and something irrelevant as well in visual studio. I don't understand, do I have a mistake somewhere in my code ? What can be causing this ?
#include <iostream>
#include <cmath> // we need the abs() function for this program
using namespace std;
const double EPS = 1e-10; // the "small enough" constant. global variable, because it is good programming style
double newton_theorem(double x)
{
double old_x = x; // asign the value of the previous iteration
double f_x1 = old_x*old_x - 8; // create the top side of the f(x[n+1] equation
double f_x2 = 2 * old_x; // create the bottom side
double new_x = old_x - f_x1 / f_x2; // calculate f(x[n+1])
//cout << new_x << endl; // remove the // from this line to see the result after each iteration
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
newton_theorem(new_x);
}
}// newton_theorem
int main()
{
cout << "This program will find the root of the function f(x) = x * x - 8" << endl;
cout << "Please enter the value of X : ";
double x;
cin >> x;
double root = newton_theorem(x);
cout << "The approximate root of the function is: " << root << endl;
return 0;
}//main
Yes, you run into undefined behavior:
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
/*return*/ newton_theorem(new_x); // <<--- HERE!
}
Missing a return on the else branch.
We could try to explain why Qt works (its compiler automatically puts the result of newton_theorem in the return registry, or shares registries, or whatever), but the fact of the matter is anything can happen. Some compilers might behave the same on subsequent runs, some might crash all the time.

print number in reverse

im simple asking if this is ok. i was asked to do the following. Write a program that will continuously ask the user for positive integers (until the
user enters a negative integer at which the program will be terminated). Every
time the user inputs a positive integer the program will print out this integer in
reverse. Your program should have a function that accepts and integer and returns
an integer in reverse. To convert the integer to its reverse, your program will call
this function. at the end of each output i keep getting 0. please explain why. also if i use void main with the function i get garbage. please explain why. thanks in advance
this is my code....
#include<iostream>
#include<cstdlib>
using namespace std;
int reverseNum(int num){
for(int j=num; j>0; j--)
cout<<j<<" ";
cout<<endl;
return false;
}
int main(){
double enternum = 0;
do{
cout<<"Enter a positive number > 0, to begin countdown ";
cin >>enternum;
cout<<reverseNum(enternum);
cout<<endl;
}
while(enternum>0);
if(enternum<=0)
cout<<"Invalid entry, good bye.";
cout<<endl;
return 0;
}
because of this: return false; - I'll leave it to you to figure out the rest..
The function is supposed to reverse the integer and then return the result. For example, if the input is 123, then the function returns 321.
Your function outputs a count-down and returns 0 (=false).
To reverse a number, you can a) convert it to string, reverse the string, convert it back to integer; b) do it on integers directly with mathematical division / multiplication / addition / modulo operations.
In C++, you don't use void main().
A 0 because when you return false, the result of type bool is implicitly converted to an int and gets printed at the line cout<<reverseNum(enternum);
Also, In this line, double enternum = 0; you want an integer int.
From your text I thought the program was working as intended, but from reading the code I suppose it just counts down from the number. Was this what you wanted?
I'd have implemented it like this (and here the function returning an integer makes sense too):
int reverseNum(int num)
{
int reverse = 0;
[...] // Do the actual reversing
return reverse;
}
Your program should have a function that accepts and integer and returns an integer in reverse
your reverseNum function should return the reversed integer, not false. and it shouldn't print the number as well, it's the caller which supposed to print it.
if one does:
i = reverseNum(1234);
then i should contain 4321 as an integer (NOT string).
the reason you keep getting 0 is because false is equivalent to 0 as an integer.
You should read the C++ FAQ in its entirety. You should especially read this. You should also learn how to debug your code. If you stepped through your code in a debugger then all the answers that you have been given here will be obvious.
For good fun, I attempted a generic implementation that supports any integral or floating point type supported by your compiler.
Be warned, there are a number of issues:
reversing a floating point number is not well defined semantically (how to position the decimal separator? How do we handle exponential notation?)
floating point types are frequently inexact (at least common IEEE formats are) and hence scaling the input will introduce artificial fractional digits. I have not taken much effort to do proper rounding, so some numbers will reverse into strange things (e.g. 123.0 could reverse into 992.1 instead of 321.0 (untested for this input, try some yourself))
the implementation is laughably template-happy. Think of it as the instructional part of this playful answer.
Oh, uncomment the DEBUGTRACE definition to ... get debug tracing :)
See it live here [click]TM
#include <cmath>
#include <limits>
#include <iostream>
#define MAX_DECIMAL_FRACTION 5
#define DEBUGTRACE(x) // do { std::cerr << x; } while (false)
template <typename T, bool is_integer> struct reverse_impl;
template <typename T>
struct reverse_impl<T, true>
{
static T reverse(T input)
{
T output;
for (output = 0; input; input/=10)
output = (output * 10) + input % 10;
return output;
}
};
template <typename T>
struct reverse_impl<T, false>
{
static T reverse(T input)
{
if (std::abs(input) <= std::numeric_limits<T>::epsilon())
return T(0);
// scale input
int log10 = (int) (std::log(input)/std::log(T(10)));
input *= std::pow(10, MAX_DECIMAL_FRACTION);
input = std::floor(input);
input /= std::pow(10, log10+MAX_DECIMAL_FRACTION);
DEBUGTRACE("debug: scaled " << input << " digits: ");
int iteration = std::max(log10+MAX_DECIMAL_FRACTION, MAX_DECIMAL_FRACTION);
if (std::floor(input) < 1)
{
input *= 10;
iteration--;
}
T output;
for (output = T(0);
iteration-- && std::floor(input) >= 1;
input-=std::floor(input), input*=T(10))
{
output = (output / T(10)) + std::floor(input);
DEBUGTRACE(std::floor(input));
}
DEBUGTRACE(std::endl);
return output * std::pow(10, log10);
}
};
template <typename T>
T reverse(T input)
{
return reverse_impl<T, std::numeric_limits<T>::is_integer>::reverse(input);
}
int main()
{
std::cout << reverse(-123l) << std::endl;
std::cout << reverse(123ul) << std::endl;
std::cout << reverse(123456.0) << std::endl;
std::cout << reverse(0.027f) << std::endl;
return 0;
}
***//here is the simple solution to find reverse of a function***
#include<iostream.h>
#include<conio.h>
void main()
{
int n,a,c,d,b;
clrscr();
cout<<"enter five integers";
cin>>n;
a=n/10000;
n=n%10000;
b=n/1000;
n=n%1000;
c=n/100;
n=n%100;
d=n/10;
n=n%10;
cout<<"number in reverse order is"<<n<<d<<c<<b<<a;
getch();
}