user3478972
user3478972

Reputation:

Two functions calling each other - C/C++

I'm writing a program that writes all safe chains made of plutonium and lead for given length. A chain is safe if there are no 2 plutoniums next to each other.This is the solution from my textbook:

All safe chains length n that end with lead are made by adding lead to all safe chains length n-1 that end with lead + all safe chains length n-1 that end with plutonium.

All safe chains length n that end with plutonium are made by adding plutonium to all safe chains length n-1 that end with lead.

I wrote code in C++ but it doesn't work because I have two functions that are calling each other so when I compile the program compiler says:

error: 'Plutonium' was not declared in this scope

This is my code:

void Lead(int k)
{
    if(k == 1)
    {
        x[1] = 'O';
        write();
    } else
    {
        x[k] = 'O';
        Lead(k-1);
        Plutonium(k-1);
    }
}

void Plutonium(int k)
{
    if(k == 1)
    {
        x[k] = 'P';
        write();
    } else
    {
        x[k] = 'P';
        Lead(k-1);
    }
}

I tried writing void Plutonium(); in declaration of function void Lead(); but it didn't work.

Is there a way to fix this or a different solution that won't leed to this problem?

Upvotes: 1

Views: 2394

Answers (5)

P.An
P.An

Reputation: 353

You need to use "forward declaration" on top of your code:

void Lead (int k);
void Plutonium (int k);

Upvotes: 1

QuestionC
QuestionC

Reputation: 10064

You need function prototypes.

void Lead (int k);
void Plutonium (int k);

/**
 * All of your code goes down here
 */

Upvotes: 1

maddin45
maddin45

Reputation: 747

You need to declare a function before you use it so that the compiler knows how the function looks like. Just add void Plutonium(int k); somewhere before your Lead function.

Upvotes: 1

rw.liang1
rw.liang1

Reputation: 418

Did you write function prototypes on top of your file?

void Lead(int k);
void Pultonium(int k);

Upvotes: 1

Matt
Matt

Reputation: 6050

This will work:

void Plutonium(int k);

void Lead(int k)
{
    if(k == 1)
    {
        x[1] = 'O';
        write();
    } else
    {
        x[k] = 'O';
        Lead(k-1);
        Plutonium(k-1);
    }
}

void Plutonium(int k)
{
    if(k == 1)
    {
        x[k] = 'P';
        write();
    } else
    {
        x[k] = 'P';
        Lead(k-1);
    }
}

Upvotes: 3

Related Questions