Monday, October 19, 2009

Functions... 101... for tech dummies... my notes

Trying to get a grasp on functions prior to continuing my attack on the assignment (see my last entry for that temporary hot mess.) Reading my textbook chapter on functions. My notes below...

What is a Function?

A subprogram that can act on data and return a value.

*main() is a function. When your program starts, main() is automatically called and run. There can be multiple functions within main().

*global functions -- functions not part of an object.

*each function has its own name. When that name shows up in the code, the function executes.

***well designed functions perform a single, specific, and easily understood task, identified by the function name.

*built-in functions: part of compiler package
*user-defined functions: defined / written by user (duh)

===================

Return Value: result of work done by a program or function

int MyFunction(); //will return an integer value

int myFunction(int someValue, float someFloat); //will take two values and return an int.

Parameter List: description of values you send into a function (the value/number types, int and variable name, or float and variable name (may be other options but these are all I know so far))

Arguments: values (numbers, etc) passed through a function

int theValueReturned = myFunction (5, 6.7);
myFunction is the function, values 5 and 6.7 are the arguments, and the type of arguments must match the declared parameter type -- (int someValue, float SomeFloat);

====================================

prototype: declaration of a function (calling the function to run within the program)

3 ways to declare a function:

-1 write your prototype into a file and use #include to include it in your program

-2 write the prototype into the file in which your function is used.

-3 define the function before it is called by any other function. The function acts as its own prototype using this method. (But don't do this because it requires functions to be in a particular order which ruins most of the point of using functions in the first place.)

Function prototype: a statement that consists of the function's return type and signature (the name and parameter list for the function)

- if you don't want your function to return a value you can write void in front of it (I don't understand why you'd want to do that, but i find out I'll let you know)

Function definition: function header and body. the header looks like the function prototype except the parameters must be named and no semicolon at the end is used. The body is the set of statements enclosed in braces.
=========================

According to my professor, the proper way to write a function is:

1) write function call
(call for the function you haven't written yet)

2) draw box with parameters and return type

3) write prototype AND comment

4) write the full function definition

========================================

Ok... now I'm going to try to tackle my assignment again now that I understand functions a little more.

Tuesday, October 13, 2009

Getting Started on my "Functions" Assignment

After class yesterday, I'm still quite confused about functions. So work on this assignment will be challenge.

Before I get into it, a HUGE shout out to my friends Sam & Brian who helped me figure out some of the final bugs in my last program. I got 5/5 on the assignment. (Yeay) -- my professor noted that my indentation was not accurate and I had one redundant note to the program, but she led that slide this time. Phew.

Ok, so this week's assignment, posted in the last entry, is about functions.

I am supposed to write a program that --

1) asks user how much she will put into savings account
2) asks user what the annual interest rate is
3) ask user how long she'll be leaving the money in the savings account
4) tell the user how much money they will have at the end of that period

Ok, sounds simple enough. I could do that WITHOUT functions, but that's not the assignment. So...

My program must define and use a function that performs this calculation.

According to the formula to do that given in class yesterday, I need to...

1) write function call for the function you haven't written yet
2) draw box with the parameters and return types
3) write prototype AND comment for what it's doing
4) write the full function definition

(half of that is still not English to me, so I'm going to take this one step at a time.)

Of course in the assignment, my teacher gave us the prototype (which is supposed to be STEP 3) so... I don't know if that's good or bad. The whole assignment instructions contradicts the professors order of doing this. Eeks.


OK, I'm just going to do this the way she said to in class... because this type of question is apparently going to be on the midterm.

1. Write a function call for the function you haven't written yet


First... what's a function call?
The way to use a function is with a "function call" expression, which consists of the function name followed by a list of "arguments" in parentheses. Another explaination: A function call is an expression containing the function name followed by the function call operator, (). If the function has been defined to receive parameters, the values that are to be sent into the function are listed inside the parentheses of the function call operator. The argument list can contain any number of expressions separated by commas. It can also be empty.
Say What?
Ok. So, what are parameters?

"Parameters provide a simple mechanism for defining and setting the valuesof inputs that are required by a form at startup. Form parameters are variables of type char,number,date that you define at design time." -- GeekInterview

Or, from my class notes: "parameter is a local variable that gets initialized with the function call"

(Still greek to me, but let's move on...)
ok. So. I think it goes:

functionName (function call operator: list parameters (variables) here)

For this assignment, then, that's...

Well, this is the prototype not the function call, so I'm confused, but anyway...

double futureInvestmentValue (double investmentAmount, double monthlyInternetRate, it years);

More later...


Sunday, October 11, 2009

Next week's assignment

What I'll be working on next...

Objectives
: Write a reusable C++ function
Write a reusable C++ class
Material from: Day 5, 6; String handouts starting on page 29.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Part 1)
Write a program that asks the user how much she will put into a savings account, what the annual interest rate is, and what period of time she plans to keep the money in the savings account. After these values are read in, report back to the user how much money she will have in her account at the end of the period.

The following formula calculates how an investmentAmount grows when left in a bank account for some years which compounds interest monthly at monthlyInterestRate:
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) years*12

Your program must define and use a function that performs this calculation.
Here is the prototype, and you must write the comment telling what the function does:

double futureInvestmentValue(double investmentAmount,
double monthlyInterestRate, int years);

Prompts and messages must be in CORRECT ENGLISH. The main() is the only one that reads and prints. There are no cin or cout statements inside the function that returns the futureInvestmentValue().

Plan of Attack
1) Write a function with the following prototype:
double futureInvestmentValue(double investmentAmount,
double monthlyInterestRate, int years);

First thing to do is write a comment for this function.
Before proceeding to step 2, you must have your main() call
futureInvestmentValue(1000, 3.25/100/12, 1)
An annual interest rate of 3.25% is equivalent to a monthlyInterestRate of 3.25/100/12.
The function call above must return 1032.99.

2) Now change only your main() to read values for initial Investment and annual interest rate using cin and cout.
3) Use the following values in the run that you turn into me:
Deposit = 1000, Annual Interest Rate = 4%
4) Be careful of whether your interest rate is monthly, and whether it needs to be divided by 100.


Part 2)
Write a class that can be used to create very short form letters concerning an election. One object represents one form letter, so name your class FormLetter. Each FormLetter object might have different values for these String fields:

• the name of the person the letter is addressed to (to)
• the name of the candidate you want the addressee to vote for (candidate)
• the name of the person the letter is from (from)

If you were to create a new FormLetter object and set the following values for the fields:
to: Hildegard
candidate: The Terminator
from: Brunhilda

And then you were to print that object, your output would look like this:
_____________________________________________

Dear Hildegard,

I would like you to vote for The Terminator
because I think he is best for this state.

Sincerely,
Brunhilda
_____________________________________________

Therefore, class FormLetter needs three member variables: to, candidate, and from.
And class FormLetter needs two member functions: setValues() and printLetter(). Note that the member function called setValues() must have three parameters to accept the new values for the three member variables. The member function printLetter() needs no parameters, because all the data is already inside the object when printLetter() is called.

In order to test this class FormLetter, you must write a main() outside of the class. Every time you write one reusable class, you will always write a main() that will simply declare an object of the reusable class, and call its member functions on the object to see if they work.

So inside main():
1. declare a variable of class FormLetter
2. call setValues() with your chosen values to store inside the object
3. call printLetter() to see if the letter looks right.

In order to receive full credit for this assignment:
• You must go through the above TEST TWICE in the same main(), so that you can see whether the member function setValues() can change the values inside an existing FormLetter object, based on values sent from main().
• This program gets no data from the user's keyboard, all data is included as string literals in the main().

Final Insurance Rate Program

Finished the insurance fee program. I think it's accurate. It's not copy & pasting right but this shows where I fixed the errors I was confused about.


/* This program prints the annual insurance fee for a person based on their car value, age, and number of tickets they have received*/

#include

#include


using namespace std;


int main ()


{

int carValue, age, numberOfTickets;

cout << "Enter your car value: \n";

cin >> carValue;

cout << "Enter your age: \n";

cin >> age;

cout << "How many tickets have you received? \n";

cin >> numberOfTickets;

float baseRate;

baseRate = (carValue*.05);

float ageRate;

if (age<=24)

ageRate=(carValue*.0575);

else if ((age>=25) && (age<=29))

ageRate=(carValue*.055);

else

ageRate=baseRate;

switch (numberOfTickets)

{

case 0: cout << "Your annual insurance rate is " <<>"\n";

break;

case 1: cout << "Your annual insurance rate is " <<>1.10 << "\n";

break;

case 2: cout << "Your annual insurance rate is " <<>1.25 << "\n";

break;

case 3: cout << "Your annual insurance rate is " <<>1.50 << "\n";

break;

default: cout << "Hop on a bike and start peddling. You are so denied.";

}

return 0;

}




/* program output */




Running

Enter your car value:

10000

Enter your age:

35

How many tickets have you received?

1

Your annual insurance rate is 550


Running

Enter your car value:

15000

Enter your age:

29

How many tickets have you received?

2

Your annual insurance rate is 1031.25


Running

Enter your car value:

850

Enter your age:

19

How many tickets have you received?

3

Your annual insurance rate is 73.3125


Running

12500

Enter your age:

81

How many tickets have you received?

4

Hop on a bike and start peddling. You are so denied.

Building an Insurance Cost Calculator in C++

My assignment this week is to build an insurance rate calculator in C++ using the simplest program possible.

***disclaimer: I am learning C++ and there is a chance that what I have written below is incorrect. I will update with corrections when I get my assignment back.

=================

The assignment variables are as follows:

1) The base rate is 5 percent of the car value
2) If the person is younger than 24, add on 15% of the base rate to the total rate
3) If the person is between 25 and 29, add on 10% of the base rate to the total rate
4) If the person is older than 30, it's just the base rate
5) If the person has 1 ticket, add 10% to the age rate
6) If the person has 2 tickets, add 25% to age rate
7) If the person has 3 tickets, add 50% to age rate (sucks for them)
8) If the person has 4 tickets, deny them coverage (muhahahaha)

Ok, so that's it. Sounds simple, right? Well, maybe it is, but for someone without a programming background, this is tough.

Ok, so our teacher said to break it down piece by piece. Get it working, then simplify.

I'm also supposed to use "Switch," "If," and "Else" which I don't completely understand yet. Hopefully by the end of this post, I will get it.

============
Integer inputs needed to solve problem (cin >>)

Int CarValue
Int Age
Int NumberOfTickets

============
Other Integers

AgeRate
FinalRate

============

Breaking down the math...

BASE RATE

BaseRate=(CarValue*.05)

AGE RATE

If Age is <=24 AgeRate=BaseRate+(BaseRate*.15)
//if age is less than or equal to 24
AgeRate = CarValue*.05+(Car Value *.05 * .15)
AgeRate = Car Value * .05 + Car Value * .0075
AgeRate = Car Value * .0575

If Age is >=25 and <=29 AgeRate=BaseRate+(BaseRate*.10)
//if age is greater than or equal to 25 and less than or equal to 29
AgeRate = CarValue*.05 + (Car Value *.05 *.10)
AgeRate = Car Value * .05 +Car Value *.005
AgeRate = Car Value *.055

FINAL (TICKETS) RATE

If NumberOfTickets = 0
FinalRate = AgeRate

If NumberOfTickets = 1
AgeRate*1.10
If NumberOfTickets = 2
AgeRate*1.25

If NumberOfTickets = 3
AgeRate*1.50

If NumberOfTickets >=4
Denied. Sucka.

=====================

/* Ok, good, I think the math is right there. Now I just have to figure out how to write this program. This is the part where I get really lost. Let's see...*/

===============

Understanding If and Else and the "Logical Operators" (And, Or, Not)

Even though ultimately I want to write this program using Switch, I need to understand If and Else, which is what I'd use if I couldn't simplify with Switch.

//stolen from textbook

"The if statement enables you to test for a condition and branch to different parts of your code, depending on the result. The simplest form:

if (expression)
statement;

The expression in the parentheses can be any expression, but usually contains one of the relational expressions. If the expression has the value false, the statement is skipped. If it's true, it's executed.

if (bigNumber > smallNumber
bigNumber = smallNumber;

So...

{
if (age<=24);
ageRate=(carValue*.0575);
}

{
if ((age=>29) && (age=<24));
ageRate=(carValue*.055);

{
else
ageRate=baseRate;
}

// the logical operators: (And = && ) (Or= ||) ( Not= !)

==============

Let's Switch

Ok, so I'm not sure if I'm supposed to use Switch for just number of tickets, or if I should use it for the ageRate too. Hmm...

First, let me see if I can figure out "Switch."

Stolen from the textbook:

"Unlike if, which evaluates one value, switch statements enable you to branch on to any of several values. The general form of the switch statement is:

switch (expression)
{
case valueOne: statement;
break;
case valueTwo: statement;
break;
default: statement
break;
}

expression is any legal C++ expression, and the statements are any legal C++ statements. If one of the case values matches the expression, program execution jumps to those statements and continues to the end of switch block, unless a break statement is encountered." Also, if nothing matches, it goes to the optional default statement || no default exists and execution falls through switch commands and basically ignores them.

/* Now what's confusing me the most is figuring out where I define what the case is. Also, does it make sense to do Switch for ageRate or is that simple enough that it doesn't need switch? I guess I might be able to make the entire program written in one switch statement, but I'm not sure how I'd do that. Good thing I have all of Sunday afternoon and unlimited blog space to figure this out

Maybe the case name doesn't matter, you just have to label it.
*/

/*ugh*/

/*$*!@*/

/* 30 minutes later. Ok, I'm not getting this. I'm going to try a different approach, starting with the beginning of the program and asking for inputs, then seeing how I can apply switch to them */

#include
using namespace std;
int main(void)

{
int carValue;
cout << "Enter your car value: ";
cin >> carValue;
float baseRate = (carValue*.05)

switch (ageRate)
case

/*huh?*/

/*Google searching "complex switch C++"*/

/*FINALLY figured out what was confusing me... thanks to a devmaster.net thread ... "You can't use ranges in switch statements. Not supported by the language, sorry." Ooooh. So, I can't switch for AgeRate BUT I can for Tickets since that's just a number. OMG. No wonder I was confused. Let's see if this works.*/


#include
using namespace std;
int main(void)

{
int carValue;
int age;
int numberOfTickets

cout << "Enter your car value: ";
cin >> carValue;
cout << "Enter your age: ";
cin >> age;
cout >> "How many tickets have you received?";
cin >> numberOfTickets

float baseRate = (carValue*.05)

{
if (age<=24);
ageRate=(carValue*.0575);
}

{
if ((age=>29) && (age=<24));
ageRate=(carValue*.055);

{
else
ageRate=baseRate;
}


switch (finalRate)
{
case 0: cout >> "Your annual insurance rate is "ageRate<<"\n;
break;
case 1: cout >> "Your annual insurance rate is "ageRate*1.10<<"\n;
break;
case 2:cout >> "Your annual insurance rate is "ageRate*1.25<<"\n;
break;
case 3:cout >> "Your annual insurance rate is "ageRate*1.50<<"\n;
}


{
if numberOfTickets =>4;
cout >> "Hop on a bike. You are so denied.";
}

return 0;
}


/*this is probably incorrect but at the very least I have the start of a program that could feasibly work. Time to move it over to the compiler and see what happens. Holding breath.*/

=========================
If Debugging=Fun cout>>"Liar."

Running program in xcode for error search...

Well, that only had 14 errors and 4 warnings. :) Time to get down to the real work.

#include expects "FILENAME" or

ok, so I copied that top from some blog somewhere. I'm replacing with the top part I used in my last assignment that seemed to work fine.

Down to 12 errors but now at 6 warnings.

Expected initializer before 'cout' for cout << "Enter your care value: ";

I forgot a semicolon...

Now at 11 errors and 7 warnings, huh?

Unused variable: carValue

but I do use it. Or maybe it has to be within the same brackets. Getting rid of the ints I'm defining up top...

10 errors, 4 warnings...

Expected constructor, destructor, or type conversion before '>>' token

Moved the ints to the same place i'm asking for cins and the program seems to like that.

9 errors, 4 warnings...

No match for 'operator>>' in'std::cout>> "How many tickets have you received?"

arrows going wrong way, duh. also adding semicolon I'm missing on next line...

7 errors, 4 warnings

'carValue' was not declared

have a feeling this has to do with brackets

6 errors, 4 warnings...

no, wait... 9 errors, 4 warnings... what???

Expected unqualified-id before '{' token

... down to 4 warnings with the following code:


#include

#include


using namespace std;


int main ()


{

int carValue, age, numberOfTickets;

cout << "Enter your car value: \n";

cin >> carValue;

cout << "Enter your age: \n";

cin >> age;

cout << "How many tickets have you received? \n";

cin >> numberOfTickets;

float baseRate;

baseRate = (carValue*.05);

float ageRate;

if (age<=24)

ageRate=(carValue*.0575);

else if ((age<=24) && (age>=29))

ageRate=(carValue*.055);

else

ageRate=baseRate;

float finalRate

switch (finalRate)

{

case 0: cout << "Your annual insurance rate is ageRate \n";

break;

case 1: cout << "Your annual insurance rate is >> ageRate*1.10 \n";

break;

case 2:cout << "Your annual insurance rate is >> ageRate*1.25 \n";

break;

case 3:cout << "Your annual insurance rate is >> ageRate*1.50 \n";

break;

}

if (numberOfTickets >=4)

cout << "Hop on a bike. You are so denied.";

return 0;

}



================


/*more when i get this figured out*/




Learning C++

I put Javascript on hold and decided to learn C++ first. I'm convinced if I can figure out C++ my brain will understand programming overall and it will make learning other computer languages easier.

I'm taking two courses at the local community college: Intro to C++ and Intro to Data Management Systems. So far I really like the Intro to C++ course, but I'm not quite at the point where I feel comfortable with the language. Granted, I've only had 3 classes as of today. Last week we had to write a BMI calculator from scratch. It took me a while to figure out. She gave us the math formula, but we had to figure out the entire program in our compiler. Once I got the hang of int and float, it made a little more sense.

This week, though, our assignment is harder, and I'm struggling. We're doing Switch and If and Else. Our assignment is to build a insurance rate calculator. There are a bunch of different variables. In my next post, I'm going to work through the code until I figure it out.


Tuesday, September 8, 2009

linux

My boyfriend is IM'ing me through installing linux because he says I should use Linux, not Mac, if I want to even think of learning to program. Since all my nerd friends use Linux I am going to trust him on this one. Downloading via Ubuntu. Installation will be... interesting.

Trying to figure out the basics

Perhaps I should be tweeting my trials and tribulations instead of blogging. At the moment I've downloaded the MAMP software and can't figure out how to install it. I'm a total noob. Hopefully once I get going, as in, have all the stuff I need installed properly, these posts will be longer and more insightful.

I hate being a noob. It hurts my brain. But then again, learning is fun.

Getting back into this, for real this time...

Ok, ok. So I'm super ADD and I get massively distracted by life every time I sit down to teach myself how to program. I didn't even get past chapter 3 in my JavaScript book. I'm ashamed.

The good news is, I signed myself up for two computer sci classes at the community college for the fall. The professors are supposed to be awful (thanks ratemyprofessors.com for getting me real excited about these classes, not) BUT I'm hoping that a structured into to programming will, at the least, get me on the right track.

At the moment I'm signed up for Intro to C++ and Intro to Data Management Systems. The names of both those classes alone scare me to bits. But if programming is a language, it should be learnable, at least to the point where I can not be so deathly afraid of it and look at programmers as if they are gods with minds far beyond the intellect of normal folk like myself. Or, I'll be able to understand exactly WHY they are gods and I have a feeling it has nothing to do with knowing "how" to program, more like "how" to organize things with a language that anyone can learn.

Tonight, however, I'm staring at my Beginning PHP5, Apache, MySQL Web Development book and considering trying to get through a chapter or two. I'm under the weather and have the night to my lonesome, so might as well start learning something... even though PHP is going to be very different from C++, which I'll begin tackling in a few weeks.

I'm not even sure PHP5 is current anymore, but hopefully the book is still good. I have a bagillion random programming books that I've bought over the last 3 years or so. Time to put them to use. Really. I mean it this time.

Saturday, April 4, 2009

Getting Back into This

I'm back. And hoping to move on to the next lesson this weekend. I finally have some time to focus on learning to code. It's important to do, so I'm going to try to hold myself accountable for staying on top of studying.

Sunday, January 4, 2009

Interaction Design and Theatre

Although this blog is primarily dedicated to my technical trials and tribulations in all their dramatic and/or not-so-dramatic glory, on occasion I've decided to start blogging on related topics, such as tech news, business, and interactive design.

One of these topics, which I hope to learn a lot more about, is user interaction design. Coming from a background in theater, I always felt that my undergraduate training somehow indirectly prepared me for further study in HCI, but also thought I was likely imagining things (I do that often.)

Turns out I'm not the only one who has made the connection. In this really interesting discussion thread on IxDA, a few interaction designers chime in on the relationship between theatre and UI.

Seamus Bryne, a Senior User Experience Designer from Ireland writes:
"I find that some principles from stage direction to be very relevant and applicable to interface visual design. Concepts such as "selection" and "emphasis" and "levels" help me understand designing within space and therefore lend themselves very well to the informed placement of UI elements. After all, a screen has similar characteristics to the traditional proscenium stage."
My (hobby) work as a theater director definitely has employed elements of interactive design. Where the audience is looking at, and what of the script they are processing at any given time based on focus is a key element in any directorial project I take on. Sure, I don't have to get my audience to click a button, but if they aren't mentally clicking buttons as the show progresses, I haven't done my job as a director.

One thing that drives me nuts about directing theater is that as the director, you only have so much control over the actor and design, which are your page elements leading your audience through the script. As a director, I want ultimate control. Maybe in film direction I would get that, but in theater direction that control is lacking.

In programming, you do have control, at least, to set the page elements and adjust as needed based on research, in order to guide your audience through a psychological and physical process.

The most important part of the entire puzzle is the feedback from that audience, so you can make the appropriate changes to your educated guesses of what takes your audience from your point A to point B. In theater, design needs to be holistic - you can't design one scene or interaction without thinking of the rest of the play. You also need to consider your audience (will they be fidgety children, affluent seniors, teens who'd rather be texting on their iPhones, or all of the above?), where your audience will be sitting and how that will effect the audience/user experience, your budget, your "talent" (which in the case of programming is both the power/flexibility of the chosen language and the actual talent/ability of your development team), the physical design elements, and every last variable which contributes to the experience of a performance.

A visit to an interactive website is a performance. With the thrill of discovery (the same thrill that you have as an audience member in a play or film when something is revealed or things "click"), your audience members get excited and want to delve further into the product/story.

There are plenty of differences between theater and interactive design, of course, but I am fascinated by the similarities.

I do feel like I've finally found a place where I can both excel and grow, and my current position in community management is a great spot to start out and get to know how users interact, what they expect, and what they want out of their experiences interacting with a product.

Ultimately, I may want to pursue an MBA and focus more on overall product development (which honestly seems closer to the "theater director" role, with a crossover into stage management), but learning about user experience and programming is one of the many things I must do to begin my journey to wherever it is I may end up.

Constants: Beyond Stubborn

Think back to 8th or 9th grade Algebra I, and you'll remember that in addition to "variables" there are "constants." The constants always bored me, they made it impossible to be creative in math class. But in programming (and heck, in normal math too) they're important. Some things don't change, and it's easier to set a constant and reuse it over and over again.

If you ever want to change the value of that constant, you can do it in one place, instead of all throughout your code. The textbook example, which seems like a good one to use and remember, is a constant tax rate in the equation of figuring out how much tax is owed on a purchase. The tax rate doesn't change, so it's a constant, not a variable.

Constant's JavaScript keyword is longer than the one for variable (var)...

const: the JS keyword for constant

const CONSTANTNAME = CONSTANTVALUE;
Formatting Note:
Constants are written in ALL CAPS and Variables are written in MixedCase.
If your constant changes at some point down the road, you can always go back and change it in your script. It just can't change while the script is running.

***like variables, constants can be named just about anything, but their name must start with a letter, $, or _

Variables are Fun!

So the book finally got around explaining variables and "var" on page 44.

variable: a storage location in memory with a unique name.
var: the JavaScript keyword used to create a variable.

It looks like the way to create a variable is to write
var variablename ;
* every variable must be unique and meaningful, says the book. Unique, obviously, because if you have two different variables named the same thing that will cause an error. Meaningful, because, let's face it, you're not going to remember what xijoije means. Programming is very organized - you don't have the luxury of letting your code get messy before taking a day to clean it up. Practically any programming book will beat you over the head about formatting and naming standards, and for good reason.

... so you want your variable to have an initial value? Yea, me too. Good thing the next page tells me how to do this. Apparently that's called initializing a variable. (Creative lingo here, huh?) The good news is that the code to do this is fairly obvious. You just add a = initial value and viola, you're set.
var variableName = Initial value;
JavaScript makes some things easy for us programming noobs. I just found out that it will assign a value for your variable automatically based on what initial value you give it. So if you say it's initial value is 300, for instance, it will know that it's a number. Sometimes JavaScript can't guess or guesses wrong and you have to go in and tweak it... but they don't want to tell me how to do that yet.

data types

Reminder to self:

Basic Data Types in Javascript...

text: a sequence of characters (also known as a "string" in various programming languages)
number: in JavaScript, numbers can be integers or decimals.
boolean: true or false data. Anything that has two scenarios (on/off, yes/no, left/right, etc)

Chapter 1 Summary

In chapter one of Head First JavaScript I learned about alerts, events, and functions. I also learned some basic ingredients of interactivity - onclick and onload. I am unclear what "var" means (though I know it's important in the code) and am looking forward to learning this later in the text.

The next chapter is entitled "storing data" so it seems a little more important than how to annoy users with an automatic greeting on page load. I'll let you all know how it goes.

(edited to add: variable is explained on page 44)

Saturday, January 3, 2009

It's a slow start

I'm on page 26 in the Head First Javascript book, and trying to get a function to "get the user's name" to work. After trying to figure out their fill in the blank exercise (with what they call "magnets") I transferred the page to my server and it's not working. So now I have to figure out what I'm doing wrong.

I'm obviously doing something wrong...



Fixed it!

What was wrong...

("rockImg".src was missing the ) after Img"

and

the last ) should have been }

See it in action.



Friday, January 2, 2009

Javascript: Trial and Error Bug

Apparently alert's don't like when you're grammatically correct. My apostrophe was breaking the code. I changed the alert text from what the book told me, which led to my bug.

So now it says "I am the best pet rock youll ever have." The "youll" is killing the copywriter in me, but I'll leave it for now. At least it works.

ie:
< onload="alert('I am the best pet rock youll ever have');"> works, but,
< onload="alert('I am the best pet rock you'll ever have');"> doesn't.

[Maybe there's a way to add quotation marks in there to keep the string whole?]

Luckily, that was an easy bug to figure out. Though there must be a way around apostrophe's breaking alerts, right?

(follow up: you know that "there are no dumb questions" section of the book? Well, on the next page it explains that you can use apostrophes OR quotes in your string, you just have to use the other on the outside. So I guess you can't use both at the same time.)

(follow up 2: a coworker who's a Javascript expert, I'll call him DevGuy1, just informed me that you can get around this another way...using \' (which, apparently, is called "escaping a character.")

alert('I am the best pet rock you\'ll ever have');
[Sweet.]

Meet the iRock, Virtual Pet Superstar

Isn't he cute?
Head First JavaScript uses this, uh, "rock" to lead us through a series of exercises. This is the "iRock." He doesn't look happy, and it's not because he's a poorly-drawn version of a rock. It's because he's not able to interact with anyone. Aw, poor rock.

In this exercise of pages 18 - 20 in the book, I will learn a little bit about events, functions and greetings.

Here are some starter learnings that seem important...

"Events are notifications that you can respond to with JavaScript code." You can respond to an event like a click, or a page finishing loading. I bet you can even respond to when a user clicks on more than one object in a row, but they're not going to teach me that stuff yet. We're starting simple.

"Functions are reusable pieces of code that perform common tasks." In other words, I wish that I could write a function to do my laundry and make my bed. Unfortunately, I don't think that's going to be taught in this book.

(onload) = when a page loads
< onload="alert('I Am the Best Pet Rock You'll Ever Have!');">
(This is an evil event/alert that I will never use again, unless a tutorial makes me.)

(onclick) = when a user clicks

See how this exercise pans out at iRock: The Virtual Pet

Geek Aside #1: SuperHappyDevHouse *LOVE*

My goal in life (ok, in the next year) is to learn how to program so I can attend one of these Dev House events... they seem like a blast of productivity and inspiration!

Javascript: Your Browser Isn't Psychic

To start, the book says get used to putting JavaScript directly into an HTML page.

Let your browser know you're using JavaScript by putting the...
< script type="text/javascript" >
after < /title > in the head. Close it with a < /script >

One thing I really like about the Head Start book is that it has a section called "There are no dumb questions." Basically, they try to guess all of your questions and answer them after reading through a page/section. One interesting learning from this section on page 11 is that the < script > tag doesn't tell the browser you're going to input in JavaScript, it just says "hey there's script coming." You have to include the type="text/javascript" so your browser goes - "here comes JavaScript!"

Tutorial Errors

One thing I can't stand is when a tutorial (online or in print) features an error. Debugging is certainly a good skill to have as a programmer, but when you're just getting started a tutorial needs to be free of errors.

Page 9/10 in Headfirst Javascript features a neat starter exercise. On page 9, they show a page of code with a few sections circled, and prompt you to write what you think those things are (to prove that JavaScript really isn't all that scary and a lot of it is common sense). For instance...
function validateZIPCode (value) {
// Validate the ZIP code
// if (!isZIPCODE (value))
alert("Please enter a ZIP code in the form XXXXX.")
...means enter a zip code with five digits (page 10 fills me in on this answer.)

I guessed it meant "enter a zip code, and if it is a certain value, validate it." Close, but not quite.

Lower down the page, another section is circled...
onclick="findHouses(this.form);
Except, on page 10 there is no answer for what this means. The wrong section is highlighted, so I still don't know what onclick="findHouses(this.form);" means. I guess I will have to keep reading and learning to find out.

Javascript: Why Bother?

This is pretty much the first part of any Javascript tutorial / book out there, so while it's obvious, I thought I'd include a quick post to say...

HTML is for structure, CSS is for style, and Javascript is for interactivity (or at least basic interactivity.)

Javascript can do cool things like perform calculations, dynamically swap images on a page, and validate data. (Yea, that's why it's worth learning. It's important in making a web page that isn't totally 10 years ago.)

You should know some HTML and CSS before jumping into Javascript.

If you don't know CSS yet, I recommend checking out the free tutorials over at w3schools.

Thursday, January 1, 2009

Javascript, Part 1: Buying a Book

After reading through a few internet tutorials, I decided it would be best for me to buy a beginners book to at least get a few of the basic concepts of programming down. I looked at quite a few books and settled on Head First Javascript.




I chose this book for a variety of reasons. At first, I was put off but how picture-heavy it was. It looked like it was designed for a kindergartner, practically. But then I realized that being such a right-brained thinker, a tutorial like this could be extremely helpful... at least to get started. Most programming books are impossible to grok. This one seemed like a good place to start, at least. And reviews on Amazon say pretty much just that... "If you are taking a class in javascript or want to know how to make your web pages more interactive, this is a great introduction to javascript."

After reading through the intro, I now understand that all those silly pictures have a purpose in the Head First series. The book style is supposedly designed for "learning" based on education theory. They encourage all sorts of tricks that helps you understand and *remember* what you learn. One of those tricks is reading your work out loud, and doing the examples. So, I'm adding in my own twist and sharing what I learn with the interwebs. I'll start with chapter one.

Ready. Set. Hack.

This is the blog of one non-programmer girl attempting to learn how to program. My friend who DOES know how to program suggested I start a blog on my process so others can learn with me along the way, and if I ever actually know what I'm talking about I can provide help here as well.

(I am not going to be able to provide help on programming anytime soon.)

My plan is to start learning Javascript and move on from there. I have yet to decide if I want to take on Python or PHP next. Eventually, if all goes as planned, I'll move on to an advanced programming language like C++ or Java.

I am a slow learner and an ADD one at that, but hopefully my narcissistic motivation will aid in my progression on this subject.