I was going through walkthoroughs as a practice for my final and i came across this question. Although i was able to do it correctly, I was not able to get the presence of a colon in one of the lines(line 35):

#include <iostream>
using namespace std;
class base{
    int *x;
    int sz;
public:
    base(int cnt) { x = new int [sz = cnt];
                    seed(2); }
    ~base(){ if(x) delete [] x; }
    void seed(int val){ for(int i = 0; i < sz; i++)
                            x[i] = val + i; }
    void seed(const int v[]){ for(int i = 0; i < sz; i++)
                            x[i] = v[i]; }
    int term(int n) const{
        int *p = new int [sz];
        int i, tmp;
        for(i = 0; i < sz; i++)
            p[i] = x[i];
        tmp = p[0];
        for(int k = 0; k < n;  k++){
            for(i = 1; i < sz; i++){
                tmp += p[i];
                p[i - 1] = p[i];
                }
            p[i - 1] = tmp;
            tmp = p[0];
            }
        delete [] p;
        return tmp;
        }
    };

ostream &operator<<(ostream &os, const base &x){
    for (int i = 0; i < 7; i++)
        os << (i > 0 ? ", " : " " ) << x.term(i); //<- colon in question
    return os;
    }

class deranged: public base{
public:
    deranged(int n, int m) : base(2) {
        int sval[2];
        sval[0] = n; sval[1] = m;
        seed(sval);
        }
    };

int main(){
    base x(3);
    deranged fib(4, 5);
    cout << x << '\n' << fib << '\n';
    return 0;
    }

Could somebody please enlighten me in what that line means. I complete my walkthrough by ignoring the " " following the colon and it was correct too.

In your case, if "i" is larger than zero, you send a ", " to the stream, otherwise you send a blank. So, ":" works like "else".

commented: Very helpful And clear +1

Indeed, this statement is like a an if statment its equivelent would look something like this.

string myIF(int a){
    if(a > 0){
        return ", ";
    }else{
        return " ";
    }
}

Hope that makes sense
Chris

commented: Superbly Explained!! +1

In your case, if "i" is larger than zero, you send a ", " to the stream, otherwise you send a blank. So, ":" works like "else".

Indeed, this statement is like a an if statment its equivelent would look something like this.

string myIF(int a){
    if(a > 0){
        return ", ";
    }else{
        return " ";
    }
}

Hope that makes sense
Chris

That is as clear as it could be!! Thanks guys!!

Mark as solved?

Mark as solved?

sorry forgot to mark it! thanks for reminding!

No problem :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.