Select this to skip to main content [CSUSB] >> [CNS] >> [Comp Sci Dept] >> [R J Botting] >> [CSci202] >>
[Index] [Schedule] [Syllabi] [Text] [Labs] [Projects] [Resources] [Search] [Grading]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12]
Mon Oct 25 13:39:31 PDT 2004
. Sample Algorithms written in pseudo-code/structured English

Algorithm to print out a file called n.
Open the file with name n for input
if(the file couldn't be opened)
	report the error
	return
//end if

while( get the next character)
	output the next character
//end while

Close the file

End Algorithm

Can you translate the above algorithm into a program
in C++?

-------------------
Algorithm to print out a file called n
with double spacing of the lines.
Open the file with name n for input
if(the file couldn't be opened)
	report the error
	return
//end if

while( get the next line)
	output the next line
	output a blank line
//end while

Close the file

End Algorithm

Can you translate the above algorithm into a program
in C++?
------------------------
Newton's algorithm to calculate the square root of a
with error less than e.

if(a<0 or e<=0)
	report error and exit
//end if

set x=0.5*a.
set y= (x*x + a)/(2*x).
while( abs(x-y)>e )
	set x=y.
	set y= (x*x + a)/(2*x).
//end while

return y.

//end Newton's algorithm

Try the above algorithm out with a=50 and e=0.001.

Can you code the above algorithm as a C++ function with header
	double newt(double a, double e)
?
------------------------
Algorithm to multiply positive integers x and y by using addition and
subtraction only.
if( x or y < 0)
	report error
	exit
//end if

set integer z = 0.
for( integer i = 1 to y)
	set z = z + x.
//end for

return z.
//end algorithm

Does the above algorithm work?

Can you code it into C++?
Should you code it in C++?  Explain your answer!
------------------------
The Bubble Sort algorithm for sorting a vector or array
of numbers into increasing order.

Set n to the size of the number of numbers in the vector or array.
Repeat the following n times.
	for each number in turn, except the last one
		if the number is bigger than the next one
			swap the two numbers
		//end if
	//end for
//end repeat

//end bubble sort

Are there any improvements you could make to the above
algorithm?
------------------------
The selection sort algorithm

Find the biggest number and put it at the end of the vector or array
by swapping it.

repeat the above step with each part of the vector or array in turn.

//end algorithm

Can you write the above so it is easier to understand and code?