Search code examples
powershellstring-formatting

How to display output in the for loop horizontally?


I'm creating a program that display n number of prime number (e.g. The program will display first 6 prime numbers if the user inputted 6). And I want the display 1 row contains 5 numbers. I did googled it around to find the solution but failed to find it.

I have tried using if else statement to do it but not working

for ( $i = 3; $i -gt 0; ++$i ) #starting from 3
    {
        $sqrt = [math]::Sqrt($i)    #Optimize memory consumption
        for ( $j = 2; $j -le $sqrt; ++$j )    #Checked if it is divisible by any natural number
        {
            if ( $i % $j -eq 0 )    #if is prime number
            {
                $prime = 1    #set to false
                break    #stop taking into account
            }
        }
        if ( $prime -eq 0 )    #if not prime number
        {
            Write-Host ("$i")   #display prime number

            $count++    #set count to 1
            $turn++    #set turn to 1
        }
        $prime = 0    #is prime number
        if ( $count -eq $value )    #if until nth prime number
        {
            break    #stop taking into account
        }
        if ( $turn -eq 5 )
        {
           Write-Output(" ")
           $turn = 0
        }
    }

I'm expecting the result is like:
3 5 7 11 13

17 19 23 29 31

But it gave me the output like this:
3
5
7
11
13

17
19
23
29
31

Any suggestions / advice is welcomed. Thank you in advance.


Solution

  • Some general pointers:

    • Avoid mixing Write-Host and Write-Output calls for constructing your output - these cmdlets serve very different purposes.

      • Write-Output - whose explicit use is rarely necessary - outputs data, for later programmatic processing.

        • Any command or expression's output that is not captured in a variable, sent to another command via the pipeline, or redirected to a file is implicitly output, so that Write-Output $i can simply be written as $i.
      • Write-Host writes to the host (typically, the console) and provides feedback to the user in the form of status information or to aid in soliciting input - it writes to an output stream that is separate from the data (success output) stream, and as such you shouldn't use it to output data, because such output can (without extra effort) neither be captured in a variable nor sent to another command.

    • Avoid pseudo method syntax such as Write-Output(" ") when you call PowerShell commands (cmdlets / functions / scripts):

      • In PowerShell, commands are invoked like shell commands - Write-Output arg1 arg2 - not like C# methods - Write-Output(arg1, arg2); see Get-Help about_Parsing.
        To prevent accidental use of method syntax, use Set-StrictMode -Version 2 or higher, but note its other effects.

    If you want to output an array of objects on the same line, simply stringify it via an expandable string (interpolating string), "...", which creates a space-separated[1] list of its (stringified) elements:

    function get-Primes {
      param($n)
      1..$n # simulate output: simply return array 1, 2, 3, ...
    }
    
    # Get an array of numbers
    $primes = get-Primes 5
    
    # Output the array as a space-separated list, via an expandable string:
    "$primes"
    

    The above yields:

    1 2 3 4 5
    

    [1] The space char. is the default separator, but the $OFS preference variable can be used to specify a different char.