Recursion help in C++ - c++

The assignment is Design and Develop a C++ program to list the first N terms of the Fibonacci series.
The output should look like this:
N=2 1,1
N=2 1,1
N=3 1,1,2
N=4 1,1,2,3
N=5 1,2,3,5
N=6 ....
My problem is that I have written the recursive function below but I'm not sure how to format it so it outputs to screen in the manner above.
#include <iostream>
using namespace std;
//Function Prototype
int fib(int);
int main()
{
for (int x = 0; x < 15; x++)
cout << fib(x) << " ";
cin.get();
cin.get();
return 0;
}
//Definition of fib
int fib(int n)
{
//Return 1 when n is 0
if ( n <= 0 )
return 0;
else if (n == 1)
return 1;
else
return fib(n-1) + fib(n-2);
}
Could someone shed some light on how to get this accomplished?
Thank you.

if you don't care too much about efficiency, a double loop will do
for (int x = 2; x < 15; x++) {
cout << "N = " << x << " ";
for (int y = 2; y <= x; y++)
cout << fib(y) << " ";
cout << endl;
}

How to format?
You have a good start.
Try this as a next step...
for (int x = 0; x < 15; x++)
cout << x << "=" << fib(x) << " " << std::endl;
cin.get();
In my system, I can add to the cout line, compile, and review the output in < 10 seconds. Fast turn around and practice (for you) are your friends.

I would take a different approach. I'd save the already computed Fibonacci values so they are not computed them over and over again, like in a map, and than using that map to print the values.
std::map<int, int> fibs;
int fib(int const n)
{
auto p = fibs.find(n);
if(p != fibs.end())
return p->second;
int f = 1;
if (n > 1)
{
f = fib(n-1) + fib(n-2);
}
fibs[n] = f;
return f;
}
You can then loop through the computed values like this:
for(int n = 0; n < 10; ++n)
{
fib(n);
std::cout << "N=" << n << " ";
for(int i = 0; i <= n; ++i)
std::cout << fibs[i] << ",";
std::cout << std::endl;
}

Since it all does is print the fibonacci number, and the ones before, you just need to add them to your output ...
You can either have an aggregating string that you pass along, that will hold all the temp values, or just call another method that will have temp outputs. (mind you, it's not very efficient though :)
int fib_verbose(int n)
{
//Return 1 when n is 0
if ( n <= 0 )
return 0;
else if (n == 1) {
return 1;
}
else {
int smaller = fib(n-2);
int larger = fib(n-1);
cout << smaller << " " << larger << endl;
return smaller + larger;
}
}
You'll have to sort out the spaces, and formatting, but that's the gist.
Edit:
As per agbinfo comment: removed the 1 printing, and also storing the variables so we don't need to call them twice. (Still, for efficiency, look at Marius's answer :) ).

Here's an example that doesn't recompute values when calling fib for a single value. You can combine Marius's idea to compute the values once even on multiple runs.
The trick is that fib(unsigned&, unsigned) will return the previous fibonacci it has already computed.
#include <iostream>
using namespace std;
unsigned fib(unsigned& m, unsigned n)
{
if (n==0) {
return 0;
}
if (n==1) {
m = 0;
// cout << "0,"; // uncomment if sequence should start with a 0
return 1;
}
unsigned prev;
m = fib(prev, n-1);
cout << m << ",";
return m+prev;
}
unsigned fib(unsigned n) {
unsigned prev;
unsigned f = fib(prev, n);
cout << f;
return f;
}
int main() {
for (unsigned i=2; i<13; i++) {
cout << "N=" << i << " ";
fib(i);
cout << endl;
}
return 0;
}
Will printout:
N=2 1,1
N=3 1,1,2
N=4 1,1,2,3
N=5 1,1,2,3,5
N=6 1,1,2,3,5,8
N=7 1,1,2,3,5,8,13
N=8 1,1,2,3,5,8,13,21

Related

Function: smallest positive integer

#include <iostream>
using namespace std;
int enough(int goal)
{
int C { };
int i { };
if (goal > 1)
{
while (((C += i) <= goal) && ((goal - i) <= (i + 1)))
{
i += 1;
}
}
else
{
i = 1;
}
return i;
}
int main()
{
cout << enough(21);
return 0;
}
So the purpose of this function is for it to return the smallest positive integer that can be summed consecutively from 1 before the cumulative sum becomes greater than the parameter "goal".
So, for example:
cout << enough(9) << endl;
will print 4 because 1+2+3+4 > 9 but 1+2+3<9
cout << enough(21) << endl;
will print 6 'cause 1+2+ . . .+6 > 21 but 1+2+ . . . 5<21
cout << enough(-7) << endl;
will print 1 because 1 > -7 and 1 is the smallest positive integer
cout << enough(1) << endl;
will print 1 because 1 = 1 and 1 is the smallest positive integer
My logic at first was using just while ((C += i) <= goal), but that went wrong, for example, for the parameter 21, where you get C = 20, which passes the test and ends up in i being augmented by 1 (resulting in the return value i = 7, which is clearly wrong).
Therefore I decided to create a test which tested both C and i, but that went wrong because the code isn't considering goal - i and i + 1 as separate tests for the while circuit, but I believe it is actually altering the value of ints goal and i, which screws everything up.
Any ideas where I went wrong?
Your approach is unnecessarily verbose. There is a closed-form (i.e. O(1)) solution for this.
The sum S of the arithmetic progression 1, 2, ..., n is
S = n * (n + 1) / 2
Rearranging this (completing the square), rejecting the spurious root, and rounding appropriately to fit the requirements of the question yields the result
n = std::ceil((-1 + std::sqrt(1 + 8 * S)) / 2)
This will not work for negative n, and possibly 0 too depending on the specific (and unspecified) requirements.
Or if you must use an O(N) approach, then
int enough(int goal){
int i = 0;
for (int total = 0; (total += ++i, total) < goal; );
return i;
}
will do it, which returns 1 for goal <= 1.
You could perhaps try to simplify your original O(N) approach by only having one condition in your while-loop, i.e., no &&:
#include <iostream>
using namespace std;
int enough(int goal)
{
if (goal <= 0)
{
return 1;
}
int total{};
int i{};
while (total < goal)
{
total += ++i;
}
return i;
}
int main()
{
cout << "enough(9): " << enough(9) << endl;
cout << "enough(21): " << enough(21) << endl;
cout << "enough(-7): " << enough(-7) << endl;
cout << "enough(1): " << enough(1) << endl;
cout << "enough(0): " << enough(0) << endl;
return 0;
}
Output:
enough(9): 4
enough(21): 6
enough(-7): 1
enough(1): 1
enough(0): 1

How do i sum all numbers using loop?

For Example, I have number 1 + 6 + 7 + 12 + 13 + 18+.....+ n (n is the input from users which represent the number of elements) the index of this number starts from 1 by this it means​ that if the index is an odd number (1,3,5...) I want to increment the element at that index by 5 and if the index is an even number I want to increment the element at that index by 1 until I reach the of n number of elements. What I want is to sum all those numbers.
Sorry, It may hard to understand because of my poor English So let me write some of my C code here:
using namespace std;
int i, n, result = 0;
cout << "Input number to sum: ";
cin >> n;
// Finding result
for (i = 0; i <= n; i++){
if (i % 2 == 0) {
result +=i;
} else {
result += i * 5;
}
}
// Make last number have equal sign "1+6+7+12 = 36"
for (i = 0; i <= n; i++){
if (i == n) {
cout << i..?? << "=";
} else {
cout << i..?? << "+";
}
}
// Print result out
cout << result;
return 0;
}
Combine the computation with the output (I usually preach the opposite, but in this case it actually simplifies matters).
for (int i = 0; i <= n; i++)
{
int value = i % 2 == 0 ? i + 1 : i + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
I agree with the molbdnilo that combining calculations and output in this case, simplify the code.
I don't agree with the algorithm, though, given OP's description.
In the following the calculations are repeated to output the result
#include <iostream>
int main()
{
int n;
std::cout << "Input number to sum: ";
std::cin >> n;
auto update = [] (int i) { return i % 2 == 0 ? 1 : 5; };
int result = 0;
int value = 0;
for (int i = 0; i < n; i++)
{
value += update(i);
result += value;
}
std::cout << '\n';
for (int i = 0, value = 0; i < n; i++)
{
value += update(i);
std::cout << (i > 0 ? " + " : "") << value;
}
std::cout << " = " << result;
}
Testable here.
I agree with molbdnilo's answer. However the algorithm some changes.
The index starts from 1 , so value check for i in for loop should be
for (int i = 0; i < n; i++)
while updating the values, increment should be done on value and not on i.
Here is my solution:
using namespace std;
int main()
{
int i, n, result, value = 0;
cout << "Input number to sum: ";
cin >> n;
for (i = 0; i < n; i++)
{
value = i % 2 == 0 ? value + 1 : value + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
return 0;
}
Testable here

C++ std deviation function?

Ok so, all the numbers being passed into this function as parameters, are returning correct values, I cant figure out why after i run this i get some ridiculous number as the standard deviation. i.e the number i get is (4.23947e10) or something along those lines, and the display function is skipping every other line.
float stdDev(int arrayList [], int count, float average)
{
int deviation;
int sum2 = 0;
for (int i = 0; i <= count; i++)
{
sum2 += pow((arrayList[i] - average), 2);
}
deviation = sqrt(sum2 / (count - 1));
return deviation;
}
void displayList(int heightlist [], int weightlist[], int count)
//displays list of integers based on lists
{
cout << "\tHeight(s)" << " " << "Weight(s)" << endl;
for (int i = 0; i <= count; i++)
{
cout << "\t[" << heightlist[i] << "]" << " " << "["<< weightlist[i] <<"]" << '\n';
i++;
}
}
I think you're going one too far:
for (int i = 0; i <= count; i++)
// ^^
Probably meant i < count.
Also:
int deviation;
int sum2 = 0;
You mean float deviation, sum2?

Need to fix a simple loop

Okay I need to write a function that takes an integer parameter and prints the sum of each number up to that point. For example, n = 10 would be 1+2+3+4+5+6+7+8+9+10.
int SumOneToN(int n)
{
int x = 0;
while (x <= n)
{
cout << x+(x+1) << " ";
x++;
}
cout << endl;
}
So what's going on here?
1. Set up the function as SumOneToN.
2. Initialize x to 0.
3. Create a while loop that states while x is less than our parameter, we take x, add it to x+1 (so that we get our current x value added to the next one), print it, then we add to x for the loop to go again until we meet the parameter.
That's how I thought it should work, anyways. What actually returns is:
1 3 5 7.. etc
I'm not sure where I went wrong?
Try this :
int SumOneToN(int n)
{
int x = 1, sum=0;
while (x <= n)
{
sum=sum+x;
cout << sum << " ";
x++;
}
cout << endl;
return sum;
}
Why not use some maths an not have the loop in the first place?
i.e.
int SumToOne(int n) {
return (n * (n + 1))/2;
}
int SumOneToN(int n)
{
int sum=0;
for(int x=1;x<=n;x++)
{
sum+=x;
cout << sum << " ";
}
cout << endl;
return sum;
}
Write the "+" sign in the inverted commas and cout x; once before the while loop. If you want to do it by SUM than you have to introduce another variable and the above solutions are fair enough.
#include <iostream>
using namespace std;
int SumOneToN(int n)
{
int x = 1;
cout << x ;
x++;
while (x <= n)
{
cout << " + " << x ;
x++;
}
cout << endl;
}
int main()
{
int x;
cin >>x;
SumOneToN(x);
return 0;
}
You can try this:
int SumOneToN(int n){
int sum=n,x=1;
while(x<n){
cout<<x<<"+";
sum+=x;
x++;
}
cout<<x;
return sum;
}
Note: This wont print an additional '+' after last number.
Hey you are using same variable for Sum & as looping variable
try this code
int add(int n)
{
int sum=0;
for(int i=1;i<=10;i++)
sum=sum+i;
return sum;
}

How to refactor this simple code to avoid code duplication?

I am solving the following simple problem(on one of OnlineJugde sites which is in Russian, so I won't give a link here:). It is easier to state the problem via an example than definition.
Input:
10 // this is N, the number of the integers to follow
1 1 1 2 2 3 3 1 4 4
Output:
3 times 1.
2 times 2.
2 times 3.
1 times 1.
2 times 4.
Constraints:
All the numbers in the input(including N) are positive integer less than 10000.
Here is the code I got Accepted with:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
while(n --> 0) // do n times
{
cin >> currentNumber;
if(currentNumber != prevNumber)
{
if(currentCount != 0) //we don't print this first time
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else //if(currentNumber == prevNumber)
{
++currentCount;
}
}
cout << currentCount << " times " << prevNumber << "." << endl;
}
Now here's my problem. A little voice inside me keeps telling me that I am doing this line two times:
cout << currentCount << " times " << prevNumber << "." << endl;
I told that voice inside me that it might be possible to avoid printing separately in the end. It told me that there would then be perhaps way too many if's and else's for such a simple problem. Now, I don't want to make the code shorter. Nor do I want do minimize the number of if's and else's. But I do want to get rid of the special printing in the end of the loop without making the code more complicated.
I really believe this simple problem can be solved with simpler code than mine is. Hope I was clear and the question won't be deemed as not constructive :)
Thanks in advance.
i came up with this. no code duplication, but slightly less readable. Using vector just for convenience of testing
EDIT my answer assumes you know the numbers ahead of time and not processing them on the fly
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(3);
numbers.push_back(1);
numbers.push_back(4);
numbers.push_back(4);
for (int i=0; i<numbers.size(); i++)
{
int count = 1;
for (int j=i+1; j<numbers.size() && numbers[i] == numbers[j]; i++, j++)
{
count++;
}
cout << count << " times " << numbers[i] << "." << endl;
}
My version: reading the first value as a special case instead.
#include <iostream>
int main()
{
int n;
std::cin >> n;
int value;
std::cin >> value;
--n;
while (n >= 0) {
int count = 1;
int previous = value;
while (n --> 0 && std::cin >> value && value == previous) {
++count;
}
std::cout << count << " times " << previous << ".\n";
}
}
Run your loop one longer (>= 0 instead of > 0), and in the last round, instead of reading currentNumber from cin, do currentNumber = lastNumber + 1 (so that it's guaranteed to differ).
slightly more CREATIVE answer, this one does not make assumption about input being all known before the start of the loop. This prints the total every time, but makes use of \r carriage return but not line feed. A new line is inserted when a different number is detected.
int prev_number = -1;
int current_number;
int count = 0;
for (int i=0; i<numbers.size(); i++)
{
current_number = numbers[i];
if (current_number != prev_number)
{
count = 0;
cout << endl;
}
count++;
prev_number = current_number;
cout << count << " times " << numbers[i] << "." << "\r";
}
only problem is that the cursor is left on the last line. you may need to append cout << endl;
I think this will work:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
int i = 0;
while(i <= n)
{
if(i != n) cin >> currentNumber;
if(currentNumber != prevNumber || i == n)
{
if(currentCount != 0)
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else
{
++currentCount;
}
i++;
}
}
I would use a for loop, but I wanted to stay as close to the original as possible.