I have to write a program that outputs Pascal's triangle for a computer science class, and everything is correct on the output until it gets past row 14, wherein it starts outputting odd irrational numbers. Here's my code
#include <iostream>
#include "myFunctions.h"
using namespace std;
int main() {
int rows;
cout << "Please Enter The Number of Rows: ";
cin >> rows;
cout << rows << endl;
for (int i = 0; i < rows; i++) {
for (int j = 1; j < (rows - i + 1); j++) {
cout << " ";
}
for (int k = 0; k <= i; k++) {
if (k == 0) {
cout << "1" << " ";
} else {
cout << combination(i, k) << " ";
}
}
cout << "\n";
}
return 0;
}
And here's my functions file:
#ifndef MYFUNCTIONS_CPP_INCLUDED
#define MYFUNCTIONS_CPP_INCLUDED
#include "myFunctions.h"
double factorial (int n) {
assert(n >= 0);
int v = 1;
while (n > 0) {
v *= n;
n--;
}
return v;
}
double combination (int a, int b) {
return (factorial(a) / (factorial(a - b) * factorial(b)));
}
#endif // MYFUNCTIONS_CPP_INCLUDED
And, finally, here's my header file.
#ifndef MYFUNCTIONS_H_INCLUDED
#define MYFUNCTIONS_H_INCLUDED
#include <iostream>
#include <cassert>
//*******************************************************
// description: finds factorial of value *
// return: double *
// precondition: that the value is valid and an integer *
// postcondition: returns the factorial of value *
//*******************************************************
double factorial( int n );
//********************************************************
// description: finds combination of value *
// return: double *
// precondition: both values are integers and valid *
// postcondition: returns the combination of two values *
//********************************************************
double combination( int a, int b );
#endif // MYFUNCTIONS_H_INCLUDED
I'm assuming that I did the equations within functions incorrect, or something specific is happening in main once it hits 14. Any help is appreciated.
What's going on
ints in C++ have a maximum size. As mentioned in comments, depends on your platform but for the sake of this question, I'll assume it's 2^31-1 which corresponds to a 32-bit signed integer and is what I most commonly see.
The issue comes in when you get to factorials. They grow very quickly. 14!=87178291200 which is a whole lot bigger than the maximum size of a 32 bit int. There's no feasible way to keep the whole factorial in memory for an arbitrary n! because of how large they can get.
It's not that your code is broken, it's simply running up against the physical bounds of computing.
How can we fix it?
First off, you could cancel out factorials. Basically, since we can guarantee that a>=b, we know that a!/b! is just multiplying the numbers between a and b. We can do that with a loop. Then it's just a matter of dividing by (a-b)!, which we already know how to do. This would look like
int combination(int a, int b)
{
int tmp = 1;
for(int ii = b;ii<=a;ii++)
tmp*=ii;
tmp /= factorial(b);
return tmp;
}
More efficiently, we can switch to a different algorithm. Wikipedia recommends using an iterative method for pascal's triangle. That is, each element can be calculated from two elements in the row above it. As #Damien mentions in comments, if you're looking for the kth element in row n, then you can calculate that by
int Combination(int n,int k)
{
if (k == 0 or k>n or n <= 1)
return 1;
return Combination(n-1,k) + Combination(n-1,k-1);
}
#include<iostream>
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
int main() {
int n;
std::cout << "Enter a Number";
std::cin >> n;
int result = fastFibonacci(n);
std::cout << result << "\n";
return 0;
}
in this code when i enter input 0 or 1 get correct answer. But the problem is that when i replace int numbers[n+2]; with the commented part it start giving me wrong answer when input is 0 or 1. why? anyone please explain me.
In this function
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
there is used a variable length array with n + 2 elements declared in this line
int numbers[n+2]; // int numbers[n].
Variable length arrays is not a standard C++ feature. It can be implemented as own language extension of a C++ compiler.
Using the variable length array makes the function very unsafe because there can occur a stack overflow.
As within the function there is explicitly used two elements of the array
numbers[0] = 0;
numbers[1] = 1;
then the array shall have at least two elements even when the parameter has a value less than 2.
To calculate the n-th Fibonacci number there is no need to declare an array of such a size.
Apart from this the function argument shall have an unsigned integer type. Otherwise the function can invoke undefined behavior if the user passes a negative number.
Also for big values of n there can be an integer overflow for the type int.
The function can be implemented in various ways.
Here is one of possible its implementations.
#include <iostream>
#include <functional>
unsigned long long fibonacci( unsigned int n )
{
unsigned long long a[] = { 0, 1 };
while ( n-- )
{
a[1] += std::exchange( a[0], a[1] );
}
return a[0];
}
int main()
{
const unsigned int N = 10;
for ( unsigned int i = 0; i < N; i++ )
{
std::cout << i << ": " << fibonacci( i ) << '\n';
}
return 0;
}
The program output is
0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
int numbers[n+2]; is the declaration of an array of ints with space for n + 2 ints, this is a variable lenght array and is not part of C++ standard, though some compilers allow it it's not somenthing you should use.
If you need a variable lenght array use std::vector.
With int numbers[n+2]; if n is equal to 0 you still have space for 2 ints, if you have int numbers[n]; the array will have space for 0 ints, so the code will fail because you are trying to access memory that does not exist with numbers[0] and numbers[1].
There are several good ways to implement the Fibonacci sequence, in the site you can find many questions regarding this matter in several programming languages, here is one of them Fibonacci series in C++
Edit
So I've seen your comments about using a vector, for making the sequence you wouldn't need the vector just two variables to store the two numbers to add, to store the sequence in a vactor, you can do somenthing like:
#include <iostream>
#include <vector>
#include <iomanip>
//passing the vector by reference
void fastFibonacci(unsigned long long n, std::vector<unsigned long long>& sequence) {
unsigned long long first = 0;
unsigned long long second = 1;
sequence.push_back(first); //add first values to the vector
sequence.push_back(second); //add first values to the vector
for (unsigned long long i = 0, value = 0; i < n && value <= LLONG_MAX ; ++i) {
value = first + second;
first = second;
second = value;
sequence.push_back(value); //adding values to the vector
}
}
int main() {
unsigned long long limit; //number of values in the sequence
int num = 1;
std::vector<unsigned long long> sequence; //container for the sequence
std::cout << "Enter upper limit: ";
std::cin >> limit;
fastFibonacci(limit, sequence);
//print the sequence in a range based loop formatted with <iomanip> library
for(auto& i : sequence){
std::cout << std::setw(4) << std::left << num++ << " " << i << std::endl;
}
return 0;
}
If you want to print just one of the numbers in the sequence, just use, for instance:
std::cout << sequence[10];
Instead of the whole vector.
The code you post in the comment to the other answer won't work because the access to the vector is out of bounds in numbers[i] = numbers[i - 1] + numbers[i - 2];, if for instance i = 5, your vector only has 2 nodes but you are accessing the 6th node numbers[5].
I'm new to C++ and is trying to solve the beginner's problem of finding all prime numbers between 0 - nth number. I saw this code online and it works perfectly.
However, my question is what is the use of '+ 1' within the statement 'bool prime[n + 1];'? I have deleted it from the code and everything seems to work just fine. Is it necessary or is it redundant?
void SieveOfEratosthenes(int n) {
bool prime[n + 1];
memset(prime, true, sizeof (prime));
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p = 2; p <= n; p++)
if (prime[p])
cout << p << endl;
}
int main() {
int n = 1000;
cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
SieveOfEratosthenes(n);
return 0;
}
In C++ an array of size N have index start from 0 to N-1. so for your problem, for N index assign N+1 size array. so that define the primality to N number.
In C++ (and many other languages) an array of size n has an index for 0 to (n - 1). In this case, you will need to check each number, up to and including n. You therefore need a spot in the array for n, at index prime[n]. This index will only exist if you oversize the array by 1. Otherwise, the array will stop at prime[n - 1].
The reason this works even if you take out the - 1 is that C++ is not fussy about array bounds - once you have an array you can legally read or write at any index, whether or not that index is safe. Notice I said legally, not safely - this is potentially very dangerous behaviour.
I'm trying to make a recursive program that sums an array or a list of numbers.
Using visual studio 2013, C++ console application.
My 1st question is:
Now I know how many numbers I have and I know the size of my array. How can I program it the way that don't know the numbers in advance, like while it's calculating the numbers there are still new numbers adding up, with the least space usage?
My 2nd question is that:
How can i improve the program that still works recursively and its time and space usage be optimal?
Here is my code:
// summing a list of number.cpp
#include "stdafx.h"
#include "iostream"
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0, i = 0;
int sumarray(int i){
if (i < 9){
sum += array[i];
i++;
sumarray(i);
}
else
return sum;
}
int main(){
std::cout << "sum is ::: " << sumarray(i);
getchar();
}
I hope you'll stop writing functions that depend on global variables to work when they can be easily made to work only with the input they have been provided.
Here's a version that works for me.
#include <iostream>
int sumarray(int array[], int i)
{
if ( i <= 0 )
{
return 0;
}
return sumarray(array, i-1) + array[i-1];
}
int main()
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::cout << "sum is : " << sumarray(array, 0) << std::endl;
std::cout << "sum is : " << sumarray(array, 5) << std::endl;
std::cout << "sum is : " << sumarray(array, 10) << std::endl;
}
Output:
sum is : 0
sum is : 15
sum is : 55
If i >= 9, your function does a return sum;.
(that is fine and good)
Where does your function return if i < 9???
if (i < 9){
sum += array[i];
i++;
sumarray(i); // I see no return statement here!!
}
Basically, if you call sumarray(3), there is no return statement that gets hit.
In your program, there is a global variable called i.
There is also a local parameter to the function also called i.
The local variable shadows the global variable, so there is no clear purpose to the global i.
I'd do it like this:
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Pass in the current index, and the size of the array
int sumarray(int i, int sz)
{
if (sz == 0)
{
return 0;
}
return array[i] + sumarray(i+1, sz-1);
}
int main(){
std::cout << "sum is ::: " << sumarray(0, 10);
// Start at the beginning (index 0)
// Run for 10 elements.
getchar();
}
The first recursive call will be to sumarray(1,9); then to sumarray(2,8);... when finally sumarray(10,0) is called, it will return 0.
A function to sum the elements of an array would normally accept the array as an argument. In that case, as a practical matter it must also accept the size of the array. Something like this:
int sumarray(int a[], size_t size) {
A signature like that furthermore gives you access to better recursive approaches. In particular, you could recursively compute the sum of the first and second halves of the array, and return their sum:
size_t midpoint = size / 2;
return sumarray(a, midpoint) + summaray(a + midpoint, size - midpoint);
That's not a complete solution: you need a termination condition (when size is less than 2). Putting that in and finishing off the function are left as an exercise for you, since you'll learn better if you have to put some work into it yourself.
That approach limits the recursion depth and thus stack size (memory overhead) to be proportional to the logarithm of the array size, though it still involves total numbers of function calls and integer additions proportional to the array size. I don't think you can achieve better asymptotic space or time complexity with a recursive algorithm. (A non-recursive algorithm for this task requires only a fixed number of function calls and and a fixed amount of memory overhead, however.)
here is a working C++ code in Qt, which i wrote - Good Luck
I added some debug points outputs to make its understanding clearer
#include <QCoreApplication>
#include <QDebug>
int sum=0;
int sumrec(int *array,int n)
{
if (n>=0)
{
int element=*(array+n); // note *(array+n) -> moving the pointer
// *array+n -> this is adding n to the pointer data (wrong)
// what is array ?
qDebug() << " element value " << *(array+n) << " at n=" << n << " array address = " << array;
n--;
sum=sum+element;
qDebug() << "sum = " << sum;
sumrec(array,n);
return sum;
}
else
{
return 0;
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int A[10]={12,13,14,15,16,17,18,19,20,11};
int b=sumrec(&A[0],9);
qDebug() << "answer = " << b;
//return a.exec();
}
here is the output of the terminal
element value 11 at n= 9 array address = 0x7fff5fbffb78
sum = 11
element value 20 at n= 8 array address = 0x7fff5fbffb78
sum = 31
element value 19 at n= 7 array address = 0x7fff5fbffb78
sum = 50
element value 18 at n= 6 array address = 0x7fff5fbffb78
sum = 68
element value 17 at n= 5 array address = 0x7fff5fbffb78
sum = 85
element value 16 at n= 4 array address = 0x7fff5fbffb78
sum = 101
element value 15 at n= 3 array address = 0x7fff5fbffb78
sum = 116
element value 14 at n= 2 array address = 0x7fff5fbffb78
sum = 130
element value 13 at n= 1 array address = 0x7fff5fbffb78
sum = 143
element value 12 at n= 0 array address = 0x7fff5fbffb78
sum = 155
answer = 155
In C++ you have all the tools to do that in a very simple, readable and safe way. Check out the valarray container:
#include <iostream>
#include <valarray>
int main () {
std::valarray<int> array{1,2,3,4,5,6,7,8,9,10};
std::cout << array.sum() << '\n';
return 0;
}
I want to save an integer type value in array.
Here is a code.
int a,arr[5];
cout<<"Enter a Number ";
cin >> a;
Suppose user enter the value 73972 This value save in arr like this.
arr[0] = 7;
arr[1] = 3;
.. .. .. ..
.. .. .. ..
arr[4] = 2;
How can I do that.???
Iterate reversely on the array and each time divide the number by 10 and store the reminder on the array.
for(int i=4; i>=0; i--)
{
arr[i] = a % 10;
a /= 10;
}
Read a string and break it into digits.
First of all integer values can have more than 5 digits.
You can get the number of digits that an object of type int can contain by using expression
std::numeric limits<int>::digits10 + 1
class std::numeric_limits is declared in header <limits>
Also take into account that if a number contains less digits than the size of the array then you need some mark that will determine the end of the number in the array.
I would advice you to use a character array instead of an array of integers in which the terminating zero will determine the end of the number.
If you want to use an integer array then the code could look the following way
#include <iostream>
#include <algorithm>
#include <limits>
int main()
{
int arr[std::numeric_limits<int>::digits10 + 1];
int a;
std::cout << "Enter a Number ";
std::cin >> a;
int n = 0;
do
{
arr[n++] = a % 10;
} while ( a /= 10 );
std::reverse( arr, arr + n );
for ( int i = 0; i < n; i++ ) std::cout << arr[i] << ' ';
std::cout << std::endl;
}