RadarURL

조회 수 14182 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

가 크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

가 크게 작게 위로 아래로 댓글로 가기 인쇄

PSEUDOCODE STANDARD

Pseudocode is a kind of structured english for describing algorithms. It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax.  At the same time, the pseudocode needs to be complete.  It describe the entire logic of the algorithm so that implementation becomes a rote mechanical task of translating line by line into source code.

In general the vocabulary used in the pseudocode should be the vocabulary of the problem domain, not of the implementation domain.  The pseudocode is a narrative for someone who knows the requirements (problem domain) and is trying to learn how the solution is organized.  E.g.,

Extract the next word from the line (good)
set word to get next token (poor)

Append the file extension to the name (good)
name = name + extension (poor)

FOR all the characters in the name (good)
FOR character = first to last (ok)

Note that the logic must be decomposed to the level of a single loop or decision. Thus "Search the list and find the customer with highest balance" is too vague because it takes a loop AND a nested decision to implement it. It's okay to use "Find" or "Lookup" if there's a predefined function for it such as String.indexOf().

Each textbook and each individual designer may have their own personal style of pseudocode. Pseudocode is not a rigorous notation, since it is read by other people, not by the computer. There is no universal "standard" for the industry, but for instructional purposes it is helpful if we all follow a similar style. The format below is recommended for expressing your solutions in our class.

The "structured" part of pseudocode is a notation for representing six specific structured programming constructs: SEQUENCE, WHILE, IF-THEN-ELSE, REPEAT-UNTIL, FOR, and CASE. Each of these constructs can be embedded inside any other construct. These constructs represent the logic, or flow of control in an algorithm.

It has been proven that three basic constructs for flow of control are sufficient to implement any "proper" algorithm.

SEQUENCE is a linear progression where one task is performed sequentially after another.
WHILE is a loop (repetition) with a simple conditional test at its beginning.
IF-THEN-ELSE is a decision (selection) in which a choice is made between two alternative courses of action.


Although these constructs are sufficient, it is often useful to include three more constructs:
 

REPEAT-UNTIL is a loop with a simple conditional test at the bottom.
CASE is a multiway branch (decision) based on the value of an expression. CASE is a generalization of IF-THEN-ELSE.
FOR is a "counting" loop.

SEQUENCE

Sequential control is indicated by writing one action after another, each action on a line by itself, and all actions aligned with the same indent. The actions are performed in the sequence (top to bottom) that they are written.

Example (non-computer)

Brush teeth
Wash face
Comb hair
Smile in mirror

Example

READ height of rectangle
READ width of rectangle
COMPUTE area as height times width

Common Action Keywords

Several keywords are often used to indicate common input, output, and processing operations.
Input: READ, OBTAIN, GET
Output: PRINT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP

IF-THEN-ELSE

Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN, ELSE, and ENDIF. The general form is:

IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF

The ELSE keyword and "sequence 2" are optional. If the condition is true, sequence 1 is performed, otherwise sequence 2 is performed.

Example

IF HoursWorked > NormalMax THEN
Display overtime message
ELSE
Display regular time message
ENDIF

WHILE

The WHILE construct is used to specify a loop with a test at the top. The beginning and ending of the loop are indicated by two keywords WHILE and ENDWHILE. The general form is:

WHILE condition
sequence
ENDWHILE

The loop is entered only if the condition is true. The "sequence" is performed for each iteration. At the conclusion of each iteration, the condition is evaluated and the loop continues as long as the condition is true.

Example

WHILE Population < Limit
Compute Population as Population + Births - Deaths
ENDWHILE

Example

WHILE employee.type NOT EQUAL manager AND personCount < numEmployees
INCREMENT personCount
CALL employeeList.getPerson with personCount RETURNING employee
ENDWHILE

CASE

A CASE construct indicates a multiway branch based on conditions that are mutually exclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used to indicate the various alternatives. The general form is:

CASE expression OF
condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERS:
default sequence
ENDCASE

The OTHERS clause with its default sequence is optional. Conditions are normally numbers or characters

indicating the value of "expression", but they can be English statements or some other notation that specifies the condition under which the given sequence is to be performed. A certain sequence may be associated with more than one condition.

Example

        CASE  Title  OF
                Mr      : Print "Mister"
                Mrs     : Print "Missus"
                Miss    : Print "Miss"
                Ms      : Print "Mizz"
                Dr      : Print "Doctor"
        ENDCASE

Example

        CASE  grade  OF
                A       : points = 4
                B       : points = 3
                C       : points = 2
                D       : points = 1
                F       : points = 0
        ENDCASE

REPEAT-UNTIL

This loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the top. Two keywords, REPEAT and UNTIL are used. The general form is:

REPEAT
sequence
UNTIL condition

The "sequence" in this type of loop is always performed at least once, because the test is peformed after the sequence is executed. At the conclusion of each iteration, the condition is evaluated, and the loop repeats if the condition is false. The loop terminates when the condition becomes true.
 

FOR

This loop is a specialized construct for iterating a specific number of times, often called a "counting" loop.  Two keywords, FOR and ENDFOR are used. The general form is:

FOR iteration bounds
sequence
ENDFOR

In cases where the loop constraints can be obviously inferred it is best to describe the loop using problem domain vocabulary.

Example

FOR each month of the year (good)
FOR month = 1 to 12 (ok)

FOR each employee in the list (good)
FOR empno = 1 to listsize (ok)


NESTED CONSTRUCTS

The constructs can be embedded within each other, and this is made clear by use of indenting. Nested constructs should be clearly indented from their surrounding constructs.

Example

SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
    INCREMENT total
END IF
UNTIL Temperature < zero
Print total

In the above example, the IF construct is nested within the REPEAT construct, and therefore is indented.
 
 

INVOKING SUBPROCEDURES

Use the CALL keyword. For example:

CALL AvgAge with StudentAges
CALL Swap with CurrentItem and TargetItem
CALL Account.debit with CheckAmount
CALL getBalance RETURNING aBalance
CALL SquareRoot with orbitHeight RETURNING nominalOrbit


EXCEPTION HANDLING

    BEGIN
        statements
    EXCEPTION
        WHEN exception type
            statements to handle exception
        WHEN another exception type
            statements to handle exception
    END



Sample Pseudocode

"Adequate"

FOR X = 1 to 10

    FOR Y = 1 to 10
        IF gameBoard[X][Y] = 0
            Do nothing
        ELSE
            CALL theCall(X, Y) (recursive method)
            increment counter                 
        END IF
    END FOR
END FOR

"Better"

Set moveCount to 1
FOR each row on the board
    FOR each column on the board
        IF gameBoard position (row, column) is occupied THEN
            CALL findAdjacentTiles with row, column
            INCREMENT moveCount
        END IF
    END FOR
END FOR

(Note: the logic is restructured to omit the "do nothing" clause)



"Not So Good"

FOR all the number at the back of the array
    SET Temp equal the addition of each number
    IF > 9 THEN
        get the remainder of the number divided by 10 to that index
        and carry the "1"
    Decrement one
Do it again for numbers before the decimal
 

"Good Enough (not perfect)"

SET Carry to 0
FOR each DigitPosition in Number from least significant to most significant

    COMPUTE Total as sum of FirstNum[DigitPosition] and SecondNum[DigitPosition] and Carry  

    IF Total > 10 THEN
        SET Carry to 1
        SUBTRACT 10 from Total
    ELSE
        SET Carry to 0
    END IF

    STORE Total in Result[DigitPosition]

END LOOP  

IF Carry = 1 THEN
    RAISE Overflow exception
END IF
 



 

"Pretty Good"  This example shows how pseudocode is written as comments in the source file. Note that the double slashes are indented.

public boolean moveRobot (Robot aRobot)
{
    //IF robot has no obstacle in front THEN
        // Call Move robot
        // Add the move command to the command history
        // RETURN true
    //ELSE
        // RETURN false without moving the robot
    //END IF
}

Example Java Implementation

  • source code statements are interleaved with pseudocode.
  • comments that correspond exactly to source code are removed during coding.

public boolean moveRobot (Robot aRobot)
{
    //IF robot has no obstacle in front THEN
    if (aRobot.isFrontClear())
    {
        // Call Move robot
        aRobot.move();
        // Add the move command to the command history
        cmdHistory.add(RobotAction.MOVE);
        return true;
    }
    else // don't move the robot
    {
        return false;
    }//END IF
}
 



Document History

Date Author Change
12/2/03
JD
Added Exception Handling and more examples
2/21/03 JD Added "problem domain vocabulary" paragraph.
Modified FOR loop explanation.

출처: www.csc.calpoly.edu/~jdalbey/SWE/pdl_std.html

 

출처 : http://bart7449.tistory.com/10

?

공부 게시판

공부에 도움되는 글을 올려주세요.

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
공지 [공지] 공부 게시판 입니다. 처누 2003.08.18 2017092
2632 u-E(TestBed) 티소믈리에, 차 문화를 바꾸다 new 광휘의철편64 2026.10.06 0
2631 가상화 창원흥신소 서비스 안내 new 흔들리는골렘32 2026.10.06 0
2630 경제 동작노래방 010 2817 0845 모임 분위기에 맞는 노래방 안내 new 교활한철학자타조18 2026.10.06 1
2629 윈도우즈 유심&통장 [카,톡] sim256 (24시문의) 대포유심 대포통장판매 선불유심팝니다 대포유심팝니다 new 놀라운운석99 2026.10.06 1
2628 업무 강남세븐❤️OlO-8655-OO53❤️친절문의환영 #강남세븐 #역삼동세븐 #강남세븐데이즈 #강남풀싸롱 #역삼동풀싸롱 #선릉역풀싸롱 #역삼동룸싸롱 #역삼룸사롱 #역삼풀살롱 #강남미러초이스 #역삼미러초이스 new 괴랄한재규어89 2026.10.06 1
2627 건강 파주누수업체, 신속 해결의 모든 것 new 우중충한도적91 2026.10.06 2
2626 u-E(활성화) ㅇㅇ병원, 당신의 건강을 책임지는 현명한 선택 new 빛나는달고나24 2026.10.06 1
2625 u-E(표준화) 양산싱크대막힘 시원하게 뚫는 비법 new 예측불가토끼46 2026.10.06 1
2624 동식물 용인두피문신 고민? 만족 후기 보려면 new 절묘한솔개92 2026.10.06 6
2623 구글 애드센스 토보샵: 명품레플리카 쇼핑의 시작 new 얼어붙은흐름98 2026.10.06 3
2622 사무 소프트웨어 대전누수, 근본 원인 해결의 시작 new 적막한체이서42 2026.10.06 1
2621 사업 마인드 끝판왕 사이즈까지 장착 완료! 010---8293---0291---- 여기가 베트남인줄 마블 노래클럽 new 기운찬오소리38 2026.10.05 1
2620 건강 카-툑 gusim8003 [24시문의] 선불유심내구제/내구제대출/소액대출/급전/ 비대면대출 상조내구제 무직자대출 대출 new 어설픈오소리22 2026.10.05 1
2619 하드웨어 강남엘리트❤️OlO-8655-OO53❤️친절문의24시 강남하퍼1등실장 #강남엘리트 #강남엘리트위치 #강남엘리트하퍼 #하이퍼블릭엘리트 #강남엘리트예약문의 #선릉엘리트 #선릉역엘리트 #강남사라있네 new 괴랄한재규어89 2026.10.05 1
2618 블로그 청담동셔츠룸 010 2817 0845 일정과 인원에 맞춘 셔츠룸 문의 new 정열적인퀘이사14 2026.10.05 1
2617 카메라 최근 테헤란로 벤처 밸리의 핵심 리더들 사이에서 ‘클래스가 다른 정통 수질과 프라이빗 무드’로 소문 자자한 '선릉 룸싸롱' 기습 방문, 인공미를 거부하는 무결점 뉴페이스들과 심장을 마비시킨 사심 플러팅에 제대로 저격당하고 온 솔직 후기 new 희미한홍학99 2026.10.05 1
2616 u-E(활성화) 본식DVD, 웨딩영상 색감이 중요한 이유새 창 열림 new 힘겨운귤35 2026.10.05 2
2615 공지 대전, 인천, 세종 하수구 막힘 문제 해결 방법 정열적인코요테90 2026.10.05 4
2614 취미 <문경맥주> 구입 할 수 있는 곳은 새 창 열림 타오르는드래곤61 2026.10.05 1
2613 데이터베이스 강남건전지❤️OlO-8655-OO53❤️친절문의환영 #강남건전지 #강남유니콘 #선릉유니콘 #강남건전지위치 #선릉역건전지#대치동유니콘 #강남바커스 #선릉바커스 #선릉역바커스 #강남룸클럽 #선릉룸클럽 #강남베터리 #강남바데리 괴랄한재규어89 2026.10.05 1
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 132 Next
/ 132


즐겨찾기 (가족)

JAESOO's HOMEPAGE


장여은 홈페이지


장여희 홈페이지


장여원 홈페이지


즐겨찾기 (업무)

알리카페 홀릭

숭실대 컴퓨터 통신연구실 (서창진)

말레이시아 KL Sentral 한국인 GuestHouse


즐겨찾기 (취미)

어드민아이디

유에코 사랑회

아스가르드 좋은사람/나쁜사람

JServer.kr

제이서버 메타블로그

재수 티스토리


즐겨찾기 (강의, 커뮤니티)

재수 강의 홈페이지


한소리


VTMODE.COM


숭실대 인공지능학과


숭실대 통신연구실


베너