0

I am new to c++ language. I am trying to solve a problem using function. I have to print the pentagon numbers untill the integer input, but when function returns the values, it only prints one value. I would love some help with it.

#include<iostream>
using namespace std;
int pent(int num){
    int p;
    for(int i=1;i<=num;i++){
        p=(i*(3*i-1)/2);
    }
    return p;
}

int main(){
    int num;
    cin>>num;
    int sender=pent(num);
    cout<<sender<<endl;
    return 0;
}
Simson
  • 3,373
  • 2
  • 24
  • 38
Fahim Hassan
  • 61
  • 1
  • 9
  • It prints only one value because you are returning only one value in that function. You propably want to store it in array, and then return the array. Or you can call the cout in your pent() func. – WutchZone Apr 09 '20 at 18:38

2 Answers2

2

Your function returns int, that is a single integer. To return more, you can use std::vector. As you probably are not familiar with it, I will give you some pointers...

The most simple constructor creates a vector with no entries:

std::vector<int> x;

You can reserve space for elements via reserve:

x.reserve(num);

The vector still has no elements, but it already allocated enough space to hold num elements. This is important, because when we will add elements the vector will grow and that potentially requires to copy all elements to a different place in memory. We can avoid such frequent reallocations by reserving enough space upfront.

To add elements to the vector you can use push_back:

x.push_back(42);

Eventually to print all elements of the vector we can use a range-based for loop:

for (auto element : x) std::cout << element << " ";

So you can rewrite your code like this:

#include <iostream>
#include <vector>

std::vector<int> pent(int num){
    std::vector<int> result;
    result.reserve(num);
    for(int i=1;i<=num;i++){
        result.push_back(i*(3*i-1)/2);
    }
    return result;
}

int main(){
    int num;
    std::cin >> num;
    auto sender = pent(num);
    for (auto number : sender) std::cout << number << " ";        
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

In your program, from your pent() function you are only returning last calculated value. In you ever time, you are overwriting you variable p.

So there is a way which @asmmo is suggesting, to print in pent() function. Or you can pass a vector to your pent() function and store values in that and print it in main function.

For your ref:

void pent(int num, vector<int> &arr) {
    int p;
    for (int i = 1; i <= num; i++) {
        arr[i-1] = (i*(3 * i - 1) / 2);
    }
}

int main() {
    int num;
    cin >> num;
    vector<int> arr(num);
    pent(num, arr);
    for (int i = 0; i < num; i++) {
        cout << arr[i] << endl;
    }
    return 0;
}
dj1986
  • 362
  • 2
  • 9