Get input without for statement

If I have array of n elements. How can I get values from console, to put it in array, without for statement?

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Enter space separated array elements:")
	str, _ := reader.ReadString('\n')
	arr := strings.Split(str, " ")
	fmt.Println("The array is: ", arr)
}

Something like this can be used.

I have to say how many elements should be in array first:
first line -> numbers of elements in array (n)
next n lines -> value of elements of certain index

Is this a homework assignement?

If so, please refer to the coursematerials and lessons right before the assignement was made. It should cover all things necessary to solve the assignment.

Until the homework thing is clear, I do only see two possibilities: Either read in a loop or do it recursively. The latter is strongly discouraged in go, since no TCO is made and stack depth is limited to about 10k function calls AFAIR.

The options without for are recursion andif+ goto, both of which are the wrong solution for the problem. Iā€™m all for challenges to learn a language, but one that forces you into contortions that you should never do is silly, in my opinion.

As we now know the full rules, it should be roughly like this (go-like pseudo code):

numStr, _ := stdio.ReadLine()
numInt, _ := strconv.Atoi(strings.Trim(numStr))

line, _ := stdio.Readline()
entries := strings.Split(strings.Trim(line))

if len(entries) == numInt {
  fmt.Println("Everything is fine")
} else {
  fmt.Println("Nothing is fine")
}

@rohitmore, According to your code, how from ā€œarrā€ I can get first n amount of values? And it must be converted to integer.

You can use a subslice: arr[:n-1].

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.