본문 바로가기
PL

[PL] CH8. Statement-Level Control Structures (2)

by 녕인뉸 2022. 5. 10.

1. 여러가지 언어에서의 for문

 (1) python

#!/usr/bin/python
for letter in 'Python': # First Example
	print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
	print 'Current fruit :', fruit

print "Good bye!"

#!/usr/bin/python Good bye!
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
	print 'Current fruit :', fruits[index]
print "Good bye!"

#!/usr/bin/python
for num in range(10,20): #to iterate between 10 to 20
	for i in range(2,num):
		if num%i == 0: #to determine the first factor
			j=num/i #to calculate the second factor
			print '%d equals %d * %d' % (num,i,j)
			break #to move to the next number, the #first FOR
	else: # else part of the loop
		print num, 'is a prime number'
            
        #else문은 loop가 리스트를 더이상 반복할 수 없을 때 수행
        #또는 for문이 정상적으로 종료했을 경우, 수행

 

2. Logically controlled loops : 반복 제어는 Boolean을 바탕으로 함

(1) 디자인 문제

 - 제어가 pretest ? posttest?

 - logically controlled loop가 특별한 형태의 couting loop 또는 분리된 수행문이어야 하는지?

 

 - 예시

  : 몇몇 imperative languages (파스칼, C..)는 pretest, posttest의 logically controlled loop를 모두 포함

  : C

    -pretest

//while (expression) statement

scanf (“%d”, &indat) ;
while (indat >= 0) {
    sum = sum + indat ;
    scanf(“%d”, &indat) ;
}

   - posttest

//do statement while (expression)
//body가 최소 한번 수행

do {
    indat = indat / 10;
    digits = digits + 1;
} while (indat>0);

3. User-located Loop Control Mechanisms : 사용자가 지정한 곳에서 빠져나올 수 있음 -> multiple exit

(1) 디자인 문제

 - conditional mechanism이 exit의 필수적인 부분이어야 하는지?

 - 메카니즘이 controlled loop에 나타나야 하는지 또는 다른 제어없이 하나에만 나타나야 하는지?

 

(2) 예시

 - Ada

 

 - C

 

//multiple exit

while (sum < 1000) {
    getnext(value) ;
    if (value < 0) continue ; // 나머지 코드 skip
    sum = sum + value ;
}

while (sum < 1000) {
    getnext(value) ;
    if (value < 0) break ; //반복문 종료
    sum = sum + value ;
}

 

4. Iteration based on Data Structure

(1) Iteration based on data Structure

 - 반복문은 data structure에서 elements의 수에 의해 제어됨

 - 예시

   : java -> for문은 Iteratable 인터페이스를 수행하는 배열의 값이나 collection의 objects를 통해 반복을 단순화

           -> ex. 

문자열의 myList라는 ArrayList collection이 있을 때, 다음의 명령문은 모든 elements를 반복하면서 각각을 myElement로 세팅

 

  : C#

 

StrList의 각 원소들을 순서대로 돌아가면서 반복문 수행

 

5. Unconditional Branching : 수행 제어를 프로그램의 특정 위치로 전송

(1) 문제점

 - goto 같은 경우, 수행 흐름을 제어하는 가장 강력한 명령문이지만, 사용시 위험할 수도 있음

 - readability는 명령문의 수행 순서와 코드의 순서가 같을 때 가장 좋음 (top -> bottom)

 - 자바와 같은 몇몇 언어는 goto문 없이 제작됨

 - goto문이 제거된 언어들은 이를 대체하기 위한 추가적인 제어문을 가지고 있음 (반복문 또는 subgrogram exit 형태)

 

(2) Label

 - ALGOL 60, C : identifier

 - FORTRAN, Pascal : unsigned integer

 - PL/1 : 변수

 

(3) branches의 제한

 - 파스칼

  : 파스칼 라벨은 변수인 것처럼 선언돼야함, 하지만 parameter로 pass할 수 없고, 저장 수정 안됨

  : goto는 compound문의 수행이 이미 시작됐고 종료하지 않는 한, control 구조체의 compound문에서 명령문을 타깃으로 가지지 않음

 

 6. Guarded Commands (Dijkstra)

(1) Dijkstra's selection construct

- 모든 Boolean 표현식은 수행하는 동안 contruct에 도달할 때마다 평가됨

 만약 하나 이상의 표현식이 참이면, 참인 표현식 중 하나가 random으로 골라서 수행됨

 참인 것이 없으면 프로그램을 종료시키는 run-time error가 발생함

 -> 프로그래머가 모든 가능성을 고려하고 나열하도록 함 (exhaustive listing)

 

- Ada

if i = 0 -> sum := sum + i
[] i > j -> sum := sum + j
[] j > i -> sum := sum + i
fi

 if (i=0) and (j=1) 일 때, 1, 3 조건식을 만족하므로 이 중 하나를 랜덤하게 선택하여 수행 (결과는 같음)

 

(2) Dijkstra's loop structure

모두 F가 될 때까지 반복문을 수행

선택은 random, 결과는 같음

 

 

 

+) concurrent vs. parallel processing

 

concurrent processing : 디스크에 있던 프로그램이 메모리로 올라가서 프로세스가 되는데 이 프로세스는 cpu 안에서 프로세스가 time-sharing하면서 조금씩 수행하는데 우리에겐 동시에 수행하는 것처럼 보여짐

 

parallel processing : concurrent processing을 할 때 메모리가 올려진 프로세스들이 진짜 cpu를 하나씩 할당해서 처리