简体   繁体   中英

Can't get C# for loop going in Visual Studio

I was given the following task in a C# Beginner's course:

Write a program that prints the first 10 members of the sequence: 2, -3, 4, -5, 6, -7, …

I wrote the following program, but it only prints the digit 2 to the Visual Studio console, nothing else.

Is it something wrong with the for loop or it's something else?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SandBox
{
    class Exercise
    {
        static void Main()
        {
            int printToConsole;
            for (int i = 2; i <= 10; i++)
            {
                if (i % 2 == 0)   
                    printToConsole = i;
                else
                    printToConsole = i * (-1);

                Console.WriteLine(printToConsole);
                Console.ReadKey();
            }    
        }
    }
}

You just need to delete ( or move outside of loop ) Console.ReadKey() like. It expects to put some key to pass from that line.

From documentation ;

The ReadKey method waits , that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed.

If you delete, it prints;

2
-3
4
-5
6
-7
8
-9
10

But this prints 9 element. If you want 10 element, you need to change your condition of for loop as i <= 11 .

Move the

Console.ReadKey()
outside of the loop :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM