How to Write a Computer Algorithm

47,969

50

2

Published

Introduction: How to Write a Computer Algorithm

Description

This particular algorithm will find the highest and lowest numbers in a random list of integers.

Difficulty Level

Moderately experienced.
Note: For beginners, please see the next page entitled Detailed Orientation.

Completion Time

10-20 minutes.

Scope

This document is merely demonstrating the idea of this particular algorithm, and does not teach the real-world implementation of the code or binary file.

:: Have basic knowledge of how to use a computer.
:: Have basic knowledge & experience with Microsoft Visual Studio, or can receive minor assistance from someone who has experience.

Step 1: Detailed Orientation

:: It is recommended to use the Microsoft Visual StudioIDE (code editor). See the step entitled Tools Needed.

::C# (c sharp) code is used in in this document, however the same logic can be used in all programming languages that have the ability to manipulate data.

:: The words "program" and "algorithm" are used interchangeably in this document, and are functionally the same.

Algorithm Definition

A series of steps to accomplish a task in a computer program; a step-by-step procedure. Algorithmic uses include, but not limited to, calculation, data processing, and automated reasoning.*

Algorithmic Usage

Algorithms are commonly used in a software APi (a tool in a library of other APis that allow the programmer to quickly use other computer code without knowing how it works). An analogy is using typical household appliance like a microwave. We don't know how the microwave actually works in its entirety, but we can easily use it, and rely on predicable results: put food in, set the timer, food is now hot. An algorithm is like all the hardware, circuit boards, wires, and motor(s) working together to complete a task. Consider this algorithm as a tool or appliance for searching numbers, just as a microwave oven is a appliance for heating food. View the flowchart PDF document in the next step entitled Tools Needed.

Step 2: How to Read This Document

The instructions and lines of code provided are to be typed sequentially, one after the other. The order of the lines of code is critical for this program to run as intended. Rest assure towards the end of this document is a page named Completed Code providing a replica of the entire program from start to finish. There you may compare your own code to ensure accuracy.

You can click on the pictures to enlarge them for better viewing.

Step 3: ​Tools Needed

:: A computer or tablet able to run Microsoft Windows (not Apple).

:: Microsoft Windows operating system (version 7 or 8).

:: Software: Microsoft Visual Studio Express 2012 or 2013 (free download here)

:: Keyboard hardware or software.

:: Mouse (optional).

:: Flowchart diagram (recommended, PDF attached).

When you open Visual Studio you will notice it starts with a template for you. You will begin within the curly braces under Main( ).

Step 5: Code: Declare and Initialize Variables

Create an integer array with a size of 10 specifying the following list of numbers.

`int[] numbers = { 38, 44, 2, 66, 32, 21, 1, 9, 12, 8 };`

Create a variable that stores the length (size; capacity) of the integer array.

`int length = numbers.Length;`

Create two variables that will be used later to store the highest and lowest number found in this list.

```int lowest = 0;
int highest = 0;```

Step 6: Code: Important Note

Before the loop is used (the next step), be sure to assign the lowest variable to one of the actual numbers within the numbers array list of integers. The algorithm must start by comparing the values in the given array. To do so, use this line of code.

`lowest = numbers[0];`

Step 7: Code: Create a For-loop

Create a for-loop structure.  It will be used to iterate over each of the elements in the numbers array of integers. The for-loop needs to stop at one less than the maximum length of the numbers array of integers, so we will use the less-than operator to meet this requirement.

```for (int i = 0; i < length; i++)
{

}```

Step 8: Code: Inside the For-loop

Insert the following code between the curly braces { } of the for-loop.

Note: Notice we are using ternary statements. Alternatively you could use two if-statements as well. See below for alternative code.

Print the present number in the array to console so we can see what it is. Include a single space after the place holder {0}.

`Console.Write("{0} ", numbers[i]);`

If the current element's value is greater than what is presently stored in the variable named highest, assign that value to highest.

`highest = numbers[i] > highest ? numbers[i] : highest;`

If the current element's value is less than what is presently stored in the variable named lowest, assign that value to lowest.

`lowest = numbers[i] < lowest ? numbers[i] : lowest;`

Alternative Code: if-statements

```for (int i = 0; i < length; i++)
{
Console.Write("{0} ", numbers[i]);

if (numbers[i] > highest)
highest = numbers[i];

if (numbers[i] < lowest)
lowest = numbers[i];
}
```

This loop will repeat 10 times to evaluate each of the 10 integers in the numbers array. With each iteration, the variables highest and lowest will potentially be re-assigned with the true highest integer and the true lowest integer in the array. You may begin to notice the efficiency of the for-loop structure.

Step 9: Code: Printing the Results to the Console

Finally, we want to see the results on the console what the values of the variables highest and lowest are.

Note: Type the following code outside the curly braces of the for-loop.

```Console.WriteLine("\n\nHighest = {0}", highest);
Console.WriteLine("\nLowest = {0}", lowest);
```

For this learning exercise only, it is recommended to use a pause after printing the above so the program remains open when finished. This will allow you to see the results instead of exiting on its own. To pause, simply use the following line of code as the last line below all of the other code. You will notice the black console window will remain open after your program is finished running.

`Console.ReadLine();`

Note: This pause is not required; it is only recommended for this learning exercise so you can see the results. Normally such a pause is never used in a real-word implementation.

Step 10: Visual Studio: Completed Code

This is how your program should look like after completing the steps above. The first image is the code within the Visual Studio application. This image should look very similar to what you see on your computer.

Notice the format with indents and line spacing. This is good style in writing code so it is easy to read, follow, and debug. It is also useful when someone else looks at your code so they recognize distinct parts throughout your code.

Step 11: Visual Studio: Compile the Program

Press the F6 key on the keyboard.

Notice in the lower-left corner of Visual Studio you should now see "Build Successful." This means your program compiled without any errors, and is likely to run successfully.

Troubleshooting: If you have any errors or warnings, they will appear in a horizontal window at the bottom of Visual Studio. If so, double-click on each error or warning and it will bring you to the line of code that has a problem. Just take a look at the picture in the previous step, and ensure the code is exactly the same.

Tip: Ensure you have each curly brace { } and semicolon placed as pictured. If you miss even a single curly brace or a tiny semicolon, you could see very many errors! When you see a long list of errors like that, it usually is an indication of one or more curly brace(s) missing, semicolon(s) missing, or an extra character may exist where it should not.  See the second picture in this step and notice the yellow highlighted offending code.  Notice Visual Studio will create colored squiggles that underline the offending code.  Sometimes the squiggles are blue or green, also.

When the code is corrected, there will be no errors or warnings displayed in the bottom window of Visual Studio. Press the F6 key again and confirm "Build Successful" in the bottom-left corner of Visual Studio.

Step 12: Visual Studio: Run the Program

Press the F5 key on the keyboard to execute your code.

You should now see a black window appear (a console window), and you should see the results printed on the screen. See the attached picture.

Verify the results are correct by looking at the list of numbers. Is that truly the highest and lowest numbers from the list? If not, carefully inspect your code and think through your logic in the ternary statement (or if you used the if-else code block instead).

Tip: Refer to the flowchart PDF document in the Tools Needed section for troubleshooting logic. A flowchart provides your with an orderly flow of logic that should align with the code you have written.

Congratulations on completing your new algorithm!

Step 13: Resources

You may visit the following web sites to continue adventuring into the world of programming, and to expand your skill set from what you have learned here. They are just a few resources that may help with further understanding and clarification.

:: http://computer.howstuffworks.com/question717.htm

:: http://www.msdn.com/

::http://www.lynda.com/

::http://www.visualstudio.com/

::C# language

Step 14: Credits

Picture on the Introduction page freely acquired from:

http://openclipart.org

Recommendations

• 3D CAM and CNC Class

495 Enrolled

• Casting Contest

We have a be nice policy.

Questions

Nice, thanks!

Code efficiency? I don't think so.

You are accessing numbers[i] four times in each loop. That's four times getting the base of the array, multiplying i by the size of an array entry, adding both and accessing memory to fetch the value of the i'ths entry. Get the value it inside a local variable int number = number[i] and use this. or, even better, use the foreach loop:

int highest = int.MinValue;
int lowest = int.MaxValue;
foreach (int number in numbers)
{

Console.Write("{0} ", number);

if (number > highest)

highest = number;

if (numbers < lowest)

lowest = number;

}

Don't get me wrong, your way works, but it is not the way that should be taught to learners.