Program not computing subtraction properly - c++

I'm working on a math assignment, not anything that requires programming, but since I enjoy it I try to do it for some of the assignments just to see if I can. This one was writing an integer as a sum of Fibonacci numbers. Here's the code for it:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
vector<int> fib;
vector<int> sum;
int n = 0;
int total = 0;
cout << "Enter a number." << endl;
cin >> n;
total = n;
fib.push_back(1);
fib.push_back(1);
for(int i = 2; i <= n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = n; i >= 0; i--)
{
if(total - fib[i] >= 0)
{
sum.push_back(fib[i]);
total -= fib[i];
}
if(total == 0)
{
break;
}
if(total < 0)
{
cout << "Program Error. Exiting" << endl;
exit(1);
}
}
cout << "The sequence of the fewest Fibonacci numbers adding to " << n << " is:" << endl;
for(int i = 0; i < sum.size(); i++)
{
cout << sum[i] << endl;
}
return(0);
}
It seems to run fine until I try to put in the number 7.
When it gets to if(total - fib[i] >= 0) it works as its supposed to. total is supposed to get down to 2 and fib[i] also reaches 2 for some i. It calculates this fine and goes into the if statement. but then when it does total -= fib[i] it makes total = -1, thus breaking the code.
Any suggestions as how to fix this?
Edit: It's not just 7. I tried 100, and got extremely large (both positive and negative) numbers that I was too lazy to see if they actually added up to 100 since there were about 30 or so of them. I'm not sure where this would come from.
Edit2: The issue with the #100 is not that it doesn't work, but the value is too large for an int to hold, for anyone having similar situations.

Change
for(int i = 2; i <= n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
To
for (int i = 2; i <=n; i++) {
int tmp = fib[i-1] + fib[i-2];
fib.push_back(tmp);
}
vector<int> fib allocates 8 elements space by default, vector[8+] access will cause memory error, you should use push_back(), vector will auto reallocate space when it's full.

Before your line for(int i = 2; i <= n; i++) the size of your fib vector is only 2, because you didn't reserve any space for it, and you called push_back only twice.
This means, if you try to set any element of it after that, you will encounter undefined behavior. You accessed memory which doesn't belong to you.

Related

why my code is not giving the right fibonecci number in nth value

#include <iostream>
using namespace std;
int fibo(int);
int main()
{
int num;
cout << "Enter the nth position you want to find the fibonecci number\t ";
cin >> num;
cout << "The " << num << "th fibonecci number is " << fibo(num);
}
int fibo(int n)
{
int j = 0;
int arr[25];
for (int i = 0; i <= n; i++)
{
arr[i] = 0;
}
arr[1] = 0;
arr[2] = 1;
if (n == 1)
{
return arr[1];
}
else if (n == 2)
{
return arr[2];
}
else
{
for (j = 3; j <= n; j++)
{
arr[j] = arr[j - 1] + arr[j - 2];
cout << arr[j];
}
return arr[j];
}
}
when i am compiling the code its giving garbage value but i dont understand why please if you can try to help , here i am using fibonecci using memorizaion .
here i am taking an arrayarr[] for storing the value as a memory.
The garbage value that you are getting is because of the following reason:
You initialize elements a[0] to a[n] with 0, so elements from a[n+1] and afterwards are uninitialized (and hence might contain garbage value).
When you exit the for loop, the value of j is equal to n+1 and not n. So your function returns the garbage value of a[n+1].
You can easily fix this bug by just returning arr[--j] instead of a[j] after the for loop.
Also, you can now comment off the cout inside the for loop, otherwise it will further spoil your output.

How to fix this code of "1/0! + 1/1! + 1/2! +....+ 1/n!"

So, I am trying to write a program to compute the value of the series 1/0! + 1/1! + 1/2! + .. + 1/n!. I think this is a pretty easy question to solve. But, the 1/0! i.e. the 1st term of the series is where it is creating all the problems for me. Please help me out. Please pardon for the silly mistakes if I have made since I started learning C++ 2 months ago and I am trying to solve various problems ever since.
#include <iostream>
using namespace std;
int fact(int j)
{
int facto = 1;
if (j == 0) {
return facto;
}
else {
for (int i = 2; i <= j; i++) {
facto = facto * i;
}
return facto;
}
}
int main()
{
int n, p;
float sum = 0, k;
cout << "Enter the value of n: " << endl;
cin >> n;
for (int i = 0; i < n; i++) {
p = fact(i);
cout << p << endl;
k = 1 / p;
cout << k << endl;
sum = sum + k;
}
cout << "Sum is: " << sum << endl;
return 0;
}
I have 2 questions :
1) When I am giving 0 as input, I am getting 0(i.e. the value of sum) as output(but, I am expecting to get 1) and, when I am giving 1 as input, it is giving 1 as output(expecting 2 as output). Please help me in pointing out the loophole.
2) When I am giving 0 as input, it is not printing the values of 'p' and 'k' but any input greater than 0 is showing the values of 'p' and 'k' for each time it completes the loop. Why ??
Change the loop the following way
for(int i=0; i<=n; i++)
^^^^^
Or change the loop to do-while loop as for example
int i = 0;
do
{
//...
} while ( i++ < n );
Also this statement
k = 1/p ;
change like
k = 1.0f/p ;

Number of time the iterative function is called

Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}

Visual studio doesn't take array: int magicSquare[n][n]?

I wrote my code and I'm ready to submit it but the teacher will be testing it on Visual studio 2015. Every time I test it, it gives me an error that this int magicSquare[n][n] is wrong and that n can't be read.
How do i revise this part to make visual studio read this array from n ?
My code:
#include <iostream>
using namespace std;
// This function is to create the requested magic squares
int main()
{
int n;
//asking for n
cout << "Please enter an odd number" << endl;
cin >> n;
//checking in case n doesnt follow rules
if (n < 3 || n % 2 == 0)
{
cout << "Invalid Entry, Please re-enter an odd number that is 3 or larger " << endl;
}
else
{
// A function to generate odd sized magic squares
int magicSquare[n][n];
// Setting every slot to 0
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
magicSquare[j][i] = 0;
}
}
// Initializing position to 1
int j = n / 2;
int i = n - 1;
// Setting each value to generate the magic square
for (int num = 1; num <= n * n; )
{
if (j == -1 && i == n)
{
i = n - 2;
j = 0;
}
else
{
//send to next number
// moving it to the right side
if (i == n)
i = 0;
//send to next number again
// moving it to the upper side
if (j < 0)
j = n - 1;
}
//second condition
if (magicSquare[j][i])
{
i -= 2;
j++;
continue;
}
else
//add the number
magicSquare[j][i] = num++;
//first condition
i++; j--;
}
//displaying sum of col/row
cout << "The sum of each row/col: " << n * (n*n + 1) / 2 << endl;
//Dispplaying magic square
for (j = 0; j<n; j++)
{
for (i = 0; i<n; i++)
cout << " " << magicSquare[i][j];
cout << "\n";
}
}
cout << endl;
//re running program
return main();
}
The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables.'n' must be a constant value.
In C++, arrays that are declared that way must use an n that is known at compile time. There are various ways to construct a matrix in C++. Perhaps the simplest is to define a vector of vectors.
Change
int magicSquare[n][n];
to
std::vector<std::vector<int>> magicSquare(n);
for (auto &row : magicSquare) row.resize(n);

Create randomly sized (within a certain range) arrays over many iterations

I am trying to create many arrays consisting of random numbers and of random size between the range of, say, 1 and 20 elements. My code works SOMETIMES.
I am using a random number between my desired range to determine the array size. If the first iteration produces an array size of value 10, say, then for some reason my code does not want to create any arrays of size larger than 10. Various arrays will be created (and the list of those arrays will be outputed) until a certain iteration produces a random number larger than 10. Then I get this error:
Array index out of range numbers->[11] valid upto numbers[9]
"numbers" is the name of the array. Here is the relevant portion of my code:
srand(time(0));
int j, flag = 0;
int temp;
int rand=1;
for(int t=0; t<50; t++)
{
int length = rand()% 20 + 1;
cout<<"length is " << length << endl;
int numbers[length];
for(int i = 0; i < length; i++)
{
numbers[i]=rand();
cout << numbers[i] << endl;
}
for(j=0; (j<=length); j++)
{
for (int i=0; i<(length-1); i++)
{
if(numbers[i+1]<numbers[i])
{
temp=numbers[i];
numbers[i]=numbers[i+1];
numbers[i+1]=temp;
flag++;
}
}
}
cout << "Number of Swaps : " << flag << endl;
}
As #Bob__ wrote, allocating variable length arrays is not C++ standard. It might work sometimes on specific compilers, but it may break on others.
But there are good alternatives. You can allocate dynamic memory with new. For instance:
int *array = new int[size];
array[0] = 3;
array[1] = 5;
cout << array[1];
delete [] array;
Don't forget to delete the memory with delete afterwards.
Or you could use vector<int>. It's a STL-container, that was made for exactly this purpose.
#include <vector>
using namespace std;
...
vector<int> vec(size);
vec[0] = 3;
vec[1] = 5;
cout << vec[1];
Variable Length Arrays are not in C++ standard, but only offered as extension by some compilers. I wouldn't trust them and you don't really need anything like that in your code.
You can declare your array outside the outer for loop as you know its max lenght:
#define MAXL 20
int numbers[MAXL];
for ...
int length = rand() % MAXL + 1;
...
Besides, if you are implementing a bubble sort I think that the condition of the inner i loop should be i < length - j
rand is used in two contexts. As a variable int rand and as a function std::rand(). I'd suggest to delete any using namespace std; but since the variable is not needed anyways you could as well delete int rand = 1;. Note that rand() is a C function. You may use it but IMHO std::rand() is more pure C++.
int numbers[length]; will not compile because length is a non-constant. Use std::vector<int> numbers(length); instead.
And that's about it.
#include <iostream>
#include <vector>
#include <time.h>
int main()
{
std::srand(time(0));
int j, flag = 0;
int temp;
for (int t = 0; t < 50; t++)
{
int length = std::rand() % 20 + 1;
std::cout << "length is " << length << std::endl;
std::vector<int> numbers(length);;
for (int i = 0; i < length; i++)
{
numbers[i] = std::rand();
std::cout << numbers[i] << std::endl;
}
for (j = 0; (j <= length); j++)
{
for (int i = 0; i < (length - 1); i++)
{
if (numbers[i + 1] < numbers[i])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
flag++;
}
}
}
std::cout << "Number of Swaps : " << flag << std::endl;
}
}