Star Print Problem Using Swift For-Loop - Q.01

Star Print Problem Using Swift For-Loop.

I am a swift beginner.
The teacher gave me the questions.
I tried to work for it.
However, the teacher expect me to give another solutions.
Could anybody give me some suggestions?

//Question01

*
***
**
****
***
*****

// Write down a function with 2 arguments ("X", "Y")

func startPrintStarQ1(x: Int, y: Int) -> String {
    let finalResult = null
    
    // please start your implementation to present the Q1 result

    return finalResult
}

For Question01, I tried to do in this way.

for i in 1...2 {
    
    for _ in 1...i {
        print("*", terminator: "")
    }
    
    for k in 1..<i {
        print("*", terminator: "")
    }
    
    print("")
    
}

for a in 2...3 {
    
    for _ in 1...a {
        print("*", terminator: "")
    }
    
    for k in 2..<a {
        print("*", terminator: "")
    }
    
    print("")
    
}

for b in 2...3 {
    
    for _ in 1...b {
        print("*", terminator: "")
    }
    
    for k in 1..<b {
        print("*", terminator: "")
    }
    
    print("")
    
}

However, the teacher expect me to give another solutions.

I am trying to do the research.

Could anybody give me some suggestions?

Thank you.

You could use the (repeating: count:) String initialiser to streamline your code and make it more Swifty.

https://developer.apple.com/documentation/swift/string/3018521-init

1 Like

@JohnBlackburne

Thank you for your comments.

I also have Question02 here:

The teacher asked me to use For-Loop to print the stars,
and need to input “Y” to determine the rows of stars.

Actually, I can’t solve the problem for Question02.

May I ask you to give me some suggestions on Question02 ?

Thank you.