Expressive Programming - Hello JavaScript | Programming Fundamentals: Learn to program with JavaScript (2016)

Hello JavaScript | Programming Fundamentals: Learn to program with JavaScript (2016)

Expressive Programming

In this Chapter we will take a look at some key concepts of programming. To avoid any confusion, we will not be covering any JavaScript. Instead, we are going to be focusing on some key concepts that you must first understand before moving on to JavaScript. This will give us the ability to focus on the fundamental concepts involved in programming rather than the details and nuance of JavaScript. Once you grasp these essential building blocks, learning a new language will become a simple exercise that you can complete in a matter of hours.

Programming Challenges: Practice makes perfect, at the end of this chapter you will find a series of challenges. You MUST complete all of these programming challenges before moving on to the next chapter. I want to stress the importance of practicing and using the programming tools and techniques covered in each of the sections.

Key Programming Concepts

Statements

In programming, a statement is a meaningful declarative sentence that is used to describe what a program will be doing.

Source Code

A text file containing valid programming statements.

Code Execution

ExecutionExecution

When your programs become larger than one statement, the statements are executed from left to right, top to bottom. In more complex programs you can stop execution, jump to another file, continue execution there, then return back to the file and continue on with the program.

Syntax

Syntax is the sets of rules that a programming language sets. The rules combine symbols and formatting to define the legal structure of a computer program.

For example, in the Spanish language, you have grammar that you must specifically follow, one example of this is when you add an “o” to a word to denote male, and an “a” to denote a female.

Example:

“Chica” : a girl or young woman.

“Chico” : a boy or young man.

Once you have a clear understanding of one programming language, you will be able to create programs that are valid for a specific language. Just like speaking English, you can take the knowledge you know over to another language such as Spanish.

Variables

Variables allow us to associate a value to a name. These values are stored in memory and are accessible through the name of the variable.

Example:

1 age = 21

The variable age holds the value 21. Throughout your program that value can change or remain the same.

Where Do Variables Live? Variables are stored in memory. You can think of computer memory as a collection of places for holding information. Computers have different type of memory: cache memory, video memory, and RAM (random access memory). Your programs will typically use free RAM memory.

memorymemory

Variable Scopes

A variable’s scope is a section of a program where that variable exists. You can have two types of variable scopes: local, or global.

ScopeScope

Operators

Operators are used for helping you work with variables. There are comparison operators, logical operators, assignment operators, and arithmetic operators.

Comparison Operators: A comparison operator is a binary operator (true or false value) that takes two operands whose values are compared.

Operator

Description

==

Equal to

!=

Not equal

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

Logical Operators: A programming symbol that is used as a logical operation.

Operator

Description

&&

and

|| ||

or

!

Not

Assignment Operators: In programming, the assignment operator ‘=’ is the operator used for assignment. The assignment operator assigns the value from the right side of the operator to the left side of the operator.

Operator

Description

=

assignment

New programmers tend to get confused with the assignment operator and the equality operator, remember that programming is NOT math.

assignmentassignment

Arithmetic Operators: Arithmetic operators are used when you need to operate with one or more values. Each of these operators is executed according to the order of operations in math.

Operator

Description

+

Addition

-

Subtraction

*

Multiplication

/

Division

Expressions

An expression is a group of variables and operators grouped together to evaluate to a value.

Example:

1 x = 3 + 5

Comments

Comments are used to make annotations to a specific part of a code.

Counters

Counters are a type of variable, just like variables they are stored and used based on a location in memory. Counters typically change their value through out a program to count a value.

Accumulators

Accumulators are a type of variable. Just like variables, they are stored and used based on a location in memory. Accumulators differ from counters by accumulating a value instead of counting that value.

For example, you can have an accumulator that finds the sum of an order and a counter to count the items they purchased.

Inputs

Most programs will need some type of input to operate on. Whether it’s setting up the initial value or asking a user for a specific input, your program will likely require some type of input.

Outputs

Anytime a computer reports back to a user with a result. There are many different types of outputs including, but not limited to, output to a file, a printer, the web, binary files, a screen, or another device.

Decisions

DecisionsDecisions

Most interesting programs will need to make a decision. What type of decision? A computer has the ability to make decisions based on a boolean expression. This can be based on a logical operator or an expression that evaluates to true or false.

Example of a decision statement

1 if <some condition is true>

2 Do this

3 else

4 Do this

With a conditional execution you can control the flow of the program.

Start

All programs must start at one point. The starting point of a program is where you decide your program will start executing.

Stop

Stop is where you decide to terminate your program. At times, this stopping point can be decided by you, but other times it will be determined by parts of your code.

Loops

Loops represent the concept of repeating a process over and over again. Constructing loops is one of the core parts of a program. A loop’s condition must evaluate to true or false. If the loop’s condition is true, the loop will continue to execute until it becomes false. If a loop never evaluates to false, it will turn into an infinite loop that will continue forever. Since loops can fall into this problem of looping forever, there are certain keywords that can help you decide to keep looping or to stop.

Break A break can be used to terminate a loop.

Continue A continue is used to keep a loop iterating.

Computers love to be in loops, and later in your studies you will find out that loops compose a large part of all programs. Start getting comfortable with the idea of a loop.

LoopLoop

Naming Conventions

JavaScript does not have any specific rules for naming variables; however, other languages do. Naming conventions help your code stay fluent within the context of your program. This is important because you want to have consistency throughout your entire program. Below you will find general rules when naming your variables.

1. Variables tend to start with a letter.

2. Spaces are not allowed in variables

3. Special characters such as “!,-,@” are not allowed in the name

4. Digits are allowed but keep Rule number 1 in mind.

Example of valid names

1 user

2 total

3 output

4 results

Example of invalid names

1 Becky Johnson

2 output!

3 12Users

4 first-name

Variable names should clearly express how the variable is going to be used. For example, the following names are valid but not typically a good idea to use:

1 tuna = 32

2 TheResultsFromACalculationWithALongName = ((32 + x) / 5)

Debugging

Finding mistakes in your program can be a very difficult task, and at times you might feel like you just can’t solve the problem (Scientific Method is one your tools, don’t forget it). In many cases, finding the bug can become the job itself.

Data Types

Data types are a type of item that is defined by a programming language. Typically these are numbers, strings, objects, booleans, etc.

Arrays

ArraysArrays

An array is an ordered collection of data (either primitive or objects). Based on its place in the array, each data item has a numeric index through which you can access the corresponding value. In JavaScript, arrays are also objects that have their own properties.

Booleans

BooleansBooleans

Booleans are used to represent a true or false value.

Summary

The list of concepts in this section composes nearly every computer program. Having a good understanding of these concepts will serve you well in your programming career.

Flow Charts

Now that we have a clear understanding of the building blocks of programming, it’s time to use a tool to express those ideas. Flowcharts help us to do exactly that! Flowcharts are used in many professions and different symbols can have a different meaning depending on the context.

Flowcharts will help us to better plan our programs from a high level or a low level implementation, detail of an algorithm, workflow, or a process. This is a vital tool for any programmer. Not only will it help you better understand the problem and solution that you have, but it will also help you document and communicate it to other team members. You will be a much happier programmer once the life cycle of your project comes to an end and you have a flow chart explaining exactly what your program is doing.

What exactly are flowcharts? Even though you might not know it, we use flow charts in our day to day lives, from traffic stops to workflows in a factory. The main parts of flow charts are a set of shapes (rectangles, parallelograms, rhombuses, etc) that are connected by a set of arrows. We will be using the following shapes and definitions to model our programs.

Process: Denotes a process or an action to be taken.

ProcessProcess

Preparation: Stores a preparation measure before defining a process.

PreparationPreparation

Flow: Indicates the direction of a flow.

FlowFlow

Terminator: Represents the start, end, or return section.

TerminatorTerminator

Decision: Represents a decision being made.

DecisionDecision

I/O | Input or Output: Represents data input or output from a process.

DecisionDecision

Summary

Flowcharts are abstract entities that can be used in many different forms. Throughout the rest of the text, we will use these symbols to represent our programs. If you don’t yet know how to use these flowcharts, don’t worry. We will get plenty of examples once we start translating each one of them to actual JavaScript code.

Pseudo Code

Pseudo code is another form that can help us represent what a program is doing at a high-level. The main purpose of pseudo code is to have a human-readable representation of your program. Remember pseudo code is NOT a programming language. You will typically use pseudo code after you have diagramed your program using flowcharts. Pseudo code can be very different depending on who is writing it. The main goal of pseudo code is to clearly state your ideas.

Remember there is no formal predefined way to write pseudo code.

Process: In the example below, you can see that we are working with a three-variable program. The three variables are x,y,z and an addition operations is being executed on them.

1 x = 30

2 y = x + 1

3 z = x + y

4 <More Instructions>

5 <More Instructions>

6 <More Instructions>

Preparation: Preparation is simply initializing our variable to a set value.

1 name = 'Ferguson Jones'

Flow: In most programming language the flow of a program is from top to bottom. With pseudo code you would read it just like you would read a paragraph from left to right.

Indentation: Indentation is used to denote scope.

Decision

1 if <Condition is true>

2 <TRUE BRANCH>

3 else

4 <FALSE BRANCH>

Loops

1 while <Condition is TRUE>

2 <TRUE BRANCH>

3

4 for each <item in collection>

5 <item in collection>

Example of Pseudo Code to find the largest number

1 listOfNumbers = 1,2,3,4

2 for each number in listOfNumbers

3 if max is defined

4 if max < number

5 max = number

6 else

7 max = number

8 display max

Again, don’t get to hung up on the syntax of pseudo code. Use it as a tool to model your programs. Take, for example, the following program:

1 start the program

2 Find the last 10 people that entered the building

3 If no one has entered the building today

4 Terminate program

5 otherwise email each of the individuals and let them know about any cafeteria sp\

6 ecials

7 Terminate

From the pseudo code you can tell that this program will be emailing the cafeteria specials to the first 10 people that have entered the building. Pretty handy, right? It’s a simple program that almost anyone can read, and that’s the entire purpose of using pseudo code to model a solution to a problem.

Programming Challenge

The purpose of this section is to provide you some hands-on practice in order to learn to use flowcharts and pseudo code. The challenges are sorted from easiest to most difficult. Each of the challenges comes with the solution. Try your best to solve the challenges before taking a look at the solution.

Warning

If you decide to look at the solution before attempting to solve the problem yourself, you will NOT learn to program.

I don’t want you looking at the answer and say “Oh that’s easy, anyone can do that.” If you really think anyone can do it, I challenge you to get started with the problem set.

1. What symbol do you use to start and stop a program?

o View Solution

2. What symbol is used to gather an input? What about output?

o View Solution

3. What symbol do you use to represent a process?

o View Solution

4. How many outputs can a decision symbol have? What are they?

o View Solution

5. Draw a complete flowchart program to ask a user for a number, display the number on the screen and all the numbers from 1 up to the numbered entered by the user.

o View Solution

6. Draw a complete flowchart program to determine the sales tax of any items price at 8.2%.

o View Solution

7. Create a Flowchart or Pseudo Code to output the sum of all the numbers up to the number given. Example: User provides 4 as the input output would be 1+2+3+4=10

o View Solution

8. Create a Flowchart or Pseudo Code to output the power of a given number. Example: User provides 3 as the base and 2 as the power 3*3=9

o View Solution

9. Create a Flowchart or Pseudo Code to output the factorial of any given number. Example: User provides 3 which is 3*2*1=6

o View Solution

10.Create a Flowchart or Pseudo Code to sort a list of numbers in ascending order Example: User provides the 12,23,1,13,7,12 the result is 1,7,12,12,13,23

o View Solution

11.Create a Flowchart or Pseudo Code to sort a list of numbers in descending order Example: User provides the 12,23,1,13,7,12 the result is 23,13,12,12,7,1

o View Solution

12.Create a Flowchart or Pseudo Code to find the largest number and display it to the user. Example: User provides the 12,23,1,13,7,12 the result is 23

o View Solution

13.Create a Flowchart or Pseudo Code to find the smallest number and display it to the user. Example: User provides the 12,23,1,13,7,12 the result is 1

o View Solution

14.Create a Flowchart or Pseudo Code to display the fibonacci sequence. The Fibonacci sequence is a sequence of numbers that can be determined by simply adding the previous two numbers of the sequence together to generate the next number. Example: The fibonacci sequence1,1,2,3,5,8,13,21,34

o View Solution

15.Becky is an event manager. Her job is to plan, manage, create, and promote large events such as music festivals, conferences, ceremonies, parties, or conventions all across the world. She has a particular problem: she would like to know how many people attend an event, preferably by email, since all her events are free and don’t require anyone to sign in or pay any amount of money. She mentions this problem to you. You suggested to her that you could create an application that would count how many people entered the venue. She is ecstatic to hear that you could help her. Can you model a solution to Becky’s problem?

o View Solution

Now that you’re getting a taste of what programming is all about, I want to emphasize how important the following concepts are for any programmer.

1. You must thoroughly understand a problem before attempting to solve it.

2. You must be able to translate your proposed solution into a program the computer can understand.

In the next chapter we will be taking a closer look into the translation of our programs into JavaScript code.