Can a variable be used in different loops?

0

I know it's very basic, but I just started with programming. It would be about c #.

I want to count down from a number to 0 using 3 different loops that are in the same method (button1_Click). Can I use the and as a variable for the 3 loops?

private void button1_Click(object sender, EventArgs e)
    {
        int a = Int32.Parse(textBox1.Text);

        for (int y = a; y >= 0; y--)
        {
            richTextBox1.AppendText(y.ToString());
        }

        int y=a;
        while (y<=a && y>=0 ){
            richTextBox2.AppendText(y.ToString());
            y--;
        }

        do while{
            int y=a;
            richTextBox3.AppendText(y.ToString());
            y--;
        }(y<=a && y>=0);

    }

Because in int y = a; tells me "Error 1 You can not declare a local variable named 'y' in this scope, because it would give a different meaning to 'y', which is already used in a 'secondary' scope with another denotation"

Thank you very much in advance.

    
asked by Airsa97 12.11.2018 в 01:33
source

2 answers

3

The topic goes through the field in which you declare the variables, you must do it in a consistent way, you can not declare a variable in a local ambit and then want to do it in a global one

When you define the int y within the for , you define the variable locally to that block of code, but then when you define it for the while it wants to expand the scope making it global (that's why you define it from the outside)

If you have the same local and global variables you should always go for the most comprehensive scope, but you should be consistent, but use different variable names

private void button1_Click(object sender, EventArgs e)
{
    int a = Int32.Parse(textBox1.Text);

    int y = a;

    for (y = a; y >= 0; y--)
    {
        richTextBox1.AppendText(y.ToString());
    }

    y=a;
    while (y<=a && y>=0 ){
        richTextBox2.AppendText(y.ToString());
        y--;
    }

   y=a;
    do {
        richTextBox3.AppendText(y.ToString());
        y--;
    } while(y<=a && y>=0);

}
    
answered by 12.11.2018 в 01:58
0

To solve this error you can declare the variable Y before the for cycle. This way you can use it in the three subsequent cycles. Example:

private void button1_Click(object sender, EventArgs e)
    {
        int a = Int32.Parse(textBox1.Text);
        int y = 0;

        for ( y = a; y >= 0; y--)
        {
            richTextBox1.AppendText(y.ToString());
        }

        y=a;
        while (y<=a && y>=0 ){
            richTextBox2.AppendText(y.ToString());
            y--;
        }
        y=a;
        do while{
            richTextBox3.AppendText(y.ToString());
            y--;
        }(y<=a && y>=0);
    }
    
answered by 12.11.2018 в 06:47