Computers in Engineering Pseudocode

Pseudocode and Language z Pseudocode is an artificial and informal language Review that helps you develop . z Pseudocode is similar to everyday English; it is convenient and user friendly although it is not an actual computer . 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 out put vari abl es, th ei r t ypes, and gi ve a b ri e 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 . Note, your pseudocode should paraphrase your 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. : 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: * * Date: * 11. // Check for error conditions * Name: * 12. if (arow <= 0) or (acol <= 0) then print error message and return endif * Function: * 13. if (arow * acol > MAXSIZE) then print error message and return endif * Algorithm: * * Input: * 15. k = 0 * Output: * 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 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 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 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 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 = counter + 1; Add one to the grade counter printf("Enter grade, -1 to end: "); Input the next grade (possibly the sentinel) scanf ("%d", &grade); endwhile } type cast precision control /* TERMINATION PHASE */ for format specifier If the counter is not equal to zero: if (counter != 0) { Set the average to the total divided by the counter /* Casting to avoid integer division/truncation */ average = ((double) total) / counter; Print the average printf("Class average is %.2f\n", average); else } else { Print “No grades were entered” printf("No grades were entered\n"); endif } return 0; /* program ended successfully */

}

4 The for Loop Construct for loop versus while loop z Handles some of the counter-controlled repetition details z Example: for (expression_1; expression_2; expression_3) { for (counter = 0; counter < 10; counter++) { statement; } printf("%d\n", counter); } IS THE SAME AS: z for loop has three parts: expression_1; z initializer while (expression_2) { z condition statement; z update expression_3; z Any for loop could be re-written as a while loop (counter- } controlled repetition).

More for Loop Examples do/while Loop Construct

z Tests loop-continuation at the end of loop body How many times does each loop run? z Syntax: 1. for (j = 1; j <= 100; j++) do { 2. for (j = 100; j >= 1; j--) statement1; 3. for (j = 7; j <= 77; j += 7) statement2; 4. for (j = 20; j >= 2; j -= 2) } while (condition); 5. for (j = 2; j <= 20; j += 3) z Example: What does this print? 6. for (j = 99; j >= 0; j -= 11) int counter = 1; do { printf("%d", counter); counter++; } while (counter <= 10); /*Note semicolon*/

do/while Versus while Loop for & while statements #define NUM 5 Define global constants in Caps Only have to change one place main(){ no semi colon at end int i, a[NUM]={4, 2, 7, 3, 9};

False /* Print out the elements of array a[] */ Action for(i=0; i

True /* Read in integers into the array a[] */ i=0; Use & and () to read in data into Action condition? while (i

/* Print out elements of array a[] */ i=0; do { Use do-while structure to execute while/do do/while printf(“a[%d]=%d\n”,i,a[i]); command before checking i++; condition. }while(i

5