Pseudocode Pseudocode Guide for Pseudocode
Total Page:16
File Type:pdf, Size:1020Kb
Computers in Engineering Pseudocode Pseudocode and C Language z Pseudocode is an artificial and informal language Review that helps you develop algorithms. z Pseudocode is similar to everyday English; it is convenient and user friendly although it is not an actual computer programming language. z Pseudocode programs are not executed on computers. Rather, they merely help you "think out" a program before attempting to write it in a programming language such as C. z Pseudocode consists purely of characters, so you may conveniently type pseudocode programs into a computer using an editor program. Pseudocode Guide for Pseudocode 1. State your name z Carefully prepared pseudocode programs may be 2. State the date converted easily to corresponding C programs. 3. State the name of the subroutine. 4. Give a brief description of the function of the subroutine/program. z Pseudocode consists only of action statements- 5. State the names of the input variables, their types, and give a brief those that are executed when the program has been description for each. 6. Stat e th e names of th e ou tpu t var ia bles, the ir types, an d g ive a br ie f converted from pseudocode to C and is run in C. description for each. Definitions are not executable statements. They are 7. Give a list of instructions with enough detail that someone can translate the pseudocode into a computer language such as C, C++, Java, etc. messages to the compiler. Note, your pseudocode should paraphrase your algorithm and not look identical to C code. z Each variable should be listed and the purpose of 8. Your pseudocode should be indented just like when you write your each should be briefly mentioned at the beginning of program. You should use {} or if/else/endif (for/endfor, while/endwhile, etc.) syntax to denote the start and end of blocks of statements. the pseudocode program. Example Pseudocode Documentation 1. Programmer: Gary E. Christensen 2. Date: 8/20/06 3. Name: print_matrix z The main program and each subroutine must be 4. Function: Print matrix nicely to screen. documented. 5. Input: a[] = single subscripted int array of size arow * acol = matrix to be printed. 6. arow = int = number of rows of matrix a. 7. acol = int = number of columns of matrix a. 8. MAXSIZE = global constant that specifies the maximum size of the array /****************************************************************** 9. Output: matrix a[] printed to the screen. * * 10. Algorithm: * Programmer: <Your name goes here> * * Date: <Today's date> * 11. // Check for error conditions * Name: <function name goes here> * 12. if (arow <= 0) or (acol <= 0) then print error message and return endif * Function: <Description of what the function does goes here> * 13. if (arow * acol > MAXSIZE) then print error message and return endif * Algorithm: <Describe how the function works> * * Input: <Name each input variable to the function on a separate * 14. // Print the matrix * line and give a description of what it is> * 15. k = 0 * Output: <Name each output variable on a separate line and * 16. for i = 0 to arow - 1 * give a description of what it is> * 17. print bar '|' * * 18. for j = 0 to acol - 1 ******************************************************************/ 19. print a[k] right justified 20. k = k + 1 21. endfor 22. print bar '|' followed by a newline 23. endfor 1 Example Documentation If statement Use & to read integer into variable /***************************************************************** scanf(“%d”,&x); * * * Programmer: Gary Christensen * if ((x < 0)||(x>5)){ * Date: 2/17/04 * printf(“Please enter an integer between 0 and 5.\n”); * Name: quicksort * printf(“Try again\n”); * Function: This function sorts an array of integers from * scanf(“%d”,&x); * smallest to largest value. * } Logical OR Operator * Algorithm: This subroutine sorts a list of integers using * * recursion. The first element of the list is moved to * * its fina l pos ition in the lis t an d a su blis t o f num bers * if (score >= 60){ * less than this number and a sublist of numbers greater * printf(“You Passed\n); * than this number is created. Each sublist is then * * sorted by passing it to quicksort again. The * }else{ printf(“You Failed\n”); * termination condition for the recursion are as * Logical AND Operator * follows: A one element list is sorted by definition and * }; * is returned. * Logical NOT Equal Operator * Input: ListOfInts - a pointer to an array of integers to be * * sorted. * Logical Expressions * size - the number of integers in the list to be sorted. * * Output: ListOfInts - a pointer to an array of sorted integers * ((x <= 5)&&(x >= 0)) and (y != 5) are examples of logical * * expressions. *****************************************************************/ Relational Operators Compound Conditions == Equality (don’t confuse with the z Logical Operators: && Logical And assignment operator, =) || Logical Or != not equal ! Not (complement) >tth> greater than if ((score > 100) || (score < 0)){ < less than printf(“Score is invalid\n”); } >= greater than or equal if (!((score <= 100) && (score >= 0))){ <= less than or equal printf(“Score is invalid\n”); } If-else statement The Switch Statement . z Multiple-selection structure . if (score == 100) z Good for algorithms containing a printf(“Your grade is an A+\n); else if (score >= 95) series of decisions priiintf(“Your grade is an A\n”); else if (score >= 90) z – Every constant integral value tested printf(“Your grade is an A-\n”); else printf(“Your grade is lower than an A-\n”); z – Different actions for each value . z Consists of . z case labels and default case 2 Example program to count number of while (grade != ’\n’) { A, B, and C grades Counts both lower and upper switch(grade) { case A. /* Counting A, B, and C grades */ case ’a’: #include <stdio.h> case ’A’: ++aCount; int main() { break; /* denotes end of this case */ char grade; case ’B’: ++bCount; int aCount =0, bCount = 0, cCount=0; break; case ’C’: ++cCount; printf("Enter the letter grades A, B, or C. "); break; printf("Enter the ’return’ character to end.\n"); defau lt: /* catch all other char acter s */ scanf("%c",&grade); printf("Incorrect input.\n"); } /* end of switch */ scanf("%c",&grade); } /* end of while */ /* PRINT TOTALS HERE */ printf("Total of %d A’s, %d B’s %d C’s\n", aCount, bCount, cCount); (continued on next slide) return 0; } /* end main */ More about the switch Construct C Loop constructs z Permit an action to be repeated multiple times z case labels must evaluate to an integer constant z Three loop constructs z All of the labels must be unique (but can be in z while any order) z do/while z Statement-list can contain zero or more z for statements z Example (pseudo-code): z Control passes to next label unless there is a While there are more homework problems to do: break statement. work next problem and cross it off the list z break exits the enclosing switch endwhile While Loop Example While Loop Example Flowchart z Problem: Find the first power of 2 larger than 1000 z Pseudo-code: Initialize value to 2 while the value is less than 1000: Multiply the value by two endwhile product <= True product = 1000? product * 2 product = 2; False while (product <= 1000) { product = product * 2; } 3 Class Average Example Pseudo-code Algorithm Set total to zero z Problem statement: A class of ten students Set grade counter to one took a quiz. The grades (integers in the range 0 to 10) for this quiz are available to you. while (grade counter is less than or equal to ten): Determine the class average on the quiz. Input the next grade z class average = (sum of grades / total Add the grade into the total students) Add one to the grade counter z Main algorithm: endwhile input each of the grades Set the class average to the total divided by ten perform the averaging calculation Print the class average print the result Note: This is an example of a counter-controlled loop (loop is executed a fixed number of times, controlled by a counter) C Program For the Example Sentinel-controlled loops /* average program, counter controlled repetition */ #include <stdio.h> include stdio.h for printing and reading variables int main() { beginning of main program /* note meaningful variable names */ z Sentinel value: a special input value to int counter, grade, total, average; /* INITIALIZATION phase */ indicate the end of data entry total = 0; z Also called a flag value or signal value counter = 1; /* PROCESSING phase: loop for average calculations*/ z The user must enter the sentinel value to while (counter <= 10) { printf("Enter grade: "); indicate that all data items have been entered scanf("%d", &grade); z Used in cases of indefinite repetition total = total + grade; counter = counter + 1; z Number of data items to be processed is not } /* end while */ known before the loop begins executing /* TERMINATION phase */ average = total / 10; printf("Class average is %d\n", average); return 0; } Class Average Example Using a /* average program, sentinel-controlled repetition */ #include <stdio.h> new data type (double) Sentinel (Pseudo-code) int main(){ double average = 0.0; /* new data type */ initializers for int counter = 0; variable declarations Initialize total to zero int grade =0; int total = 0; Initialize counter to zero /* INITIALIZATION phase */ Input the first grade printf("Enter grade, -1 to end: "); scanf("%d", &grade); /*Loop to perform summation*/ while (the user has not yet entered the sentinel): while (grade != -1) { Add this grade into the running total total = total + grade; counter