반복문

조건이 해당되는 동안, 조건이 맞을 경우 반복해서 실행하는 제어구문

초기값, 조건, 증감 키워드 중요!

💡 for in

for [반복문 안에서 사용할 변수] in [객체]

var aaa = 0...9 //범위연산자를 사용

for i in aaa{ 
   print(i)
}

for i in (0..<9).reversed(){ //역순 출력도 가능
   print(i)
}

stride

for [반복문 안에서 사용할 변수] in stride(from:초기값,through:조건,by:증감)-->through 값까지

for [반복문 안에서 사용할 변수] in stride(from:초기값,to:조건,by:증감) -->to의 값 전까지만

c언어의 for문과도 비슷

for i in stride(from: 2, through: 20, by: 2){ // c언어 for와 비슷 조건 증감 초기값 모두 수식으로 가능
    print(i)
}
for i in stride(from: 2, to: 20, by: 2){ // stride와 비슷하지만 to의 값 전까지만 표현가능
    //i=100 스위프트에서 i는 상수라 대입이 불가능
    print(i)
}

연습문제

1부터 100까지의 합 구하기

var tot = 0
for i in 1...100{
    tot += i
    print("\(i) : \(tot)")
}
print("1~100의 합계 : \(tot)")
print("---------")

1부터 100까지의 짝수합 구하기

tot = 0
for i in stride(from: 1, through: 100, by: 2){
    tot += i
    print("\(i) : \(tot)")
}
print("1~100까지의 짝수 합계 : \(tot)")

💡 MulFor 이중for문


for h in 0...12{
    for m in 0..<60{
        print("\(h)\(m)분")
    }
    //print("\(h)시 \(m)분") 내부변수는 외부변수에 사용불가
}


for a in 1...9{
    print("--\(a)단--")
    for b in 1...9{
        print("\(a) x \(b) = \(a*b)")
    }
}

for a in 1...9{       
    for b in 2...9{
        print("\(a) * \(b) = \(a*b)", terminator: "\t")
    }
    print()
}

💡 while

조건식을 검사하고 조건식이 참이면 계속 코드를 실행, 거짓일 경우 while문을 종료

while[조건문]{
반복실행할 코드
}


var i = 0

while i < 5{// 조건
    print("while 문 실행 \(i)")
    i += 1 // 증감
}

print("break 종료------------")

for  i in 0...10{
    print("for 문 시작\(i)")
    
    if(i == 4){
       continue // break 제어문을 멈추고 탈출시킴
    }
    print("for 문 끝\(i)")
}
print("break 종료------------")

for  i in 0...10{
    print("for 문 시작\(i)")
    
    if(i == 4){
      print("for 문 끝\(i)") // continue: 다음 분기로 넘기기 인데 잘 안쓰고 조건문으로 탈출시킴
    }
    print("for 문 끝\(i)")
}
print("break 종료------------")

💡repeat-while

타 언어의 do-while을 Swift 언어에서는 repeat-while로 사용
반복문 내부의 코드를 먼저 우선 실행 한 다음 조건문을 검사한다.

i = 0
repeat{
    print("repeat-while \(i)")
    i += 1
}
while i<=0

print("while 문 종료--")

💡 for, while문의 차이점

for문 : 일정한 횟수동안 반복해야 할 때 사용 (객체 안에서 하나씩 꺼내서 처리할 경우)

while문 : 일정 조건이 유지되는 동안 사용

profile
iOS Developer

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN