0% found this document useful (0 votes)
50 views

Lecture2 PDF

Pseudocode is an informal language similar to English that helps developers design algorithms before writing code. It consists of action statements and variable definitions to outline a program's logic. Well-documented pseudocode can easily be converted to a language like C. Each variable and the program or subroutine's purpose should be described at the beginning. Pseudocode uses syntax like indentation and brackets to denote code blocks and looks similar to code but avoids exact syntax for readability.

Uploaded by

Choragudi Raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Lecture2 PDF

Pseudocode is an informal language similar to English that helps developers design algorithms before writing code. It consists of action statements and variable definitions to outline a program's logic. Well-documented pseudocode can easily be converted to a language like C. Each variable and the program or subroutine's purpose should be described at the beginning. Pseudocode uses syntax like indentation and brackets to denote code blocks and looks similar to code but avoids exact syntax for readability.

Uploaded by

Choragudi Raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

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. St t the
State th names off the
th output
t t variables,
i bl their
th i types,
t and
d give
i a brief
bi 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
Function: Print matrix nicely to screen.
4.
5. Input: a[] = single subscripted int array of size arow * acol = matrix to be printed.
documented.
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. * }
* Algorithm: This subroutine sorts a list of integers using *
Logical OR Operator
* recursion. The first element of the list is moved to *
* it
its fi
final
l position
iti i
in th
the li
list
t and
d a sublist
bli t of
f numbers
b *
if (score >= 60){
* less than this number and a sublist of numbers greater *
* than this number is created. Each sublist is then *
printf(“You Passed\n);
* sorted by passing it to quicksort again. The * }else{
* termination condition for the recursion are as * printf(“You Failed\n”);
Logical AND Operator
* follows: A one element list is sorted by definition and * };
* is returned. *
* Input: ListOfInts - a pointer to an array of integers to be * Logical NOT Equal Operator
*
*
sorted.
size - the number of integers in the list to be sorted.
*
*
Logical Expressions
* 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)

> greater
t than
th if ((score > 100) || (score < 0)){
printf(“Score is invalid\n”);
< less than }
>= 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)
printf(“Your grade is an A+\n);
z Good for algorithms containing a
else if (score >= 95)
printf(“Your
i grade i
is an A\n”);
\
series of decisions
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"); defa lt /* catch all othe
default: other cha
characters
acte 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
product <= True product =
endwhile
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


/* average program, counter controlled repetition */
Sentinel-controlled loops
#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);
total = total + grade;
z Used in cases of indefinite repetition
counter = counter + 1; z Number of data items to be processed is not
} /* end while */
/* TERMINATION phase */
known before the loop begins executing
average = total / 10;
printf("Class average is %d\n", average);
return 0;
}

Class Average Example Using a /* average program, sentinel-controlled repetition */


Sentinel (Pseudo-code) #include <stdio.h>
int main(){ new data type (double)

double average = 0.0; /* new data type */ initializers for


int counter = 0; variable declarations
int grade =0;
Initialize total to zero 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);
} type cast precision control
endwhile /* 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:


z initializer
expression_1;
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)
3. 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[] */


for(i=0; i<NUM; i++){
condition? Action printf(“a[%d]=%d\n”,i,a[i]);
}
True /* Read in integers into the array a[] */
i=0;
condition? while (i<NUM) { Use & and () to read in data into
Action array
scanf(“%d”,&(a[i]));
True i++;
False }

/* Print out elements of array a[] */


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

You might also like