Function Problems

My compiler is showing the error: 'y' was not declared in this scope.
I can't seem to find the source. I also can't seem to find anyone else with a similar problem. Soooooo I'm here! Here's my code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>
using namespace std;

int factorial(int y);
   int n, x;
int main()
{

    cout << "Put in a number and I will show you it's factorial starting from 1." << endl;
    cin >> n;
    for(int i=1; i<=n; i++)
    {
        if(i==n)
        {
            cout << i << " = ";
            break;
        }
        cout << i << " * " << factorial(y);

    }
return 0;
}

int factorial(int y)
{
    for( x = 1; x <= n; x++)
    {
        y=x*(x+1);
    }
    if(x==n)
    {
        return y;
    }
}



closed account (z05DSL3A)
I can't seem to find the source.
It is on line 18.
Last edited on
'y' is the local variable in factorial function you can pass anything you want to it on line 18.
Sorry I know where it is. I just don't know why the error is showing up.
As I mentioned 'y' is the local variable in the function. You need to pass the value you want 'y' to be equal to on initialization. I would suggest you read up on functions and passing via parameters. http://www.cplusplus.com/doc/tutorial/functions/
http://www.learncpp.com/ --chapter 7
What exactly do you mean by ' pass the value you want 'y' to be equal to'?
The main function doesn't know what y is. Did you mean to send the value the user entered, which is in n?

I'm not sure that this code will give you the result you seem to intend with the cout statement on line 9.
I don't think you looked at either of those links if you are asking me what I meant... here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

void print(int x) //x is a local variable with a value that is passed to function
{
    std::cout << x << std::endl;
}

int main()
{
    int a = 10;
    print(a); //a is passed with a value of 10. So x is initialized to 10

    print(20); //20 is passed so x is initialized to 20

    return 0;
}
10
20
Topic archived. No new replies allowed.