text:
Introduction to Programming/About Programming

Introduction to computer programming language

What is a program?

 * Reading assignment: learn about the binary system

A computer is a tool for solving problems with data.

A program is a sequence of instructions that tell a computer how to do a task. When a computer follows the instructions in a program, we say that it executes that program. You can think of a program like a recipe that tells you how to make a peanut butter sandwich. In this model, you are the computer, making a sandwich is the task, and the recipe is the program that tells you how to execute the task.

 * Activity: Come up with a sequence of instructions to tell someone how to make a peanut butter sandwich. Don't leave any steps out, or put them in the wrong order.

Was that easy? Did you remember all the steps? Maybe you forgot to tell me to use a knife to spread the peanut butter. Now I've got peanut butter all over my hands! Of course, you say, a person wouldn't be that dumb. But a computer is that dumb. A computer will only do what you tell it to do. This might make programming frustrating at first, but it's relieving in a way: if you do everything right, you know exactly what the computer is going to do, because you told it.

Of course, computers don't understand recipes written on paper. Computers are machines, and at the most basic level, they are a collection of switches—where 1 represents "on" and 0 represents "off". Everything that a computer does is implemented in this most basic of all numbering systems—binary. If you really wanted to tell a computer what to do directly, you'd have to talk to it in binary, giving it coded sequences of 1s and 0s that tell it which instructions to execute. However, this is nearly impossible. In practice, we use a programming language.

with algorithm and flowchart for solving problem:

What is a programming language?
A programming language is, as the name would suggest, a language developed to express programs. All computers have a native programming language that they understand, commonly referred to as machine code. However, machine code is a difficult language for us to follow: amongst a number of difficulties, it is typically expressed in the binary number system, and it is unique to a particular computer architecture (thus two different computers could potentially use two different versions of machine code). Other programming languages, such as Assembly, BASIC, Java and C++ exist to provide a better interface between us, as the programmers, and the computer, by allowing programs to be expressed in a language that is easier for us to understand and potentially common to a number of computer architectures, but which can still be translated into machine code. In order for this to happen, a computer must either compile or interpret programs written in one of these languages before they can be executed.

Compilation vs Interpretation
A compiled program has to be modified into machine code before it is used. The binary is then permanently stored. As an analogy, think of a novel that was written in one language and then translated into another. For example, the Harry Potter novels were written in British English, and were then subsequently translated into 67 other languages, including Hindi, Latvian, and Latin. In much the same way, a computer program can be compiled (or "translated") into machine code, and it may potentially be compiled into different architectures (or "dialects") of machine code to suit different computers. Each translation will be a unique version of the program, in the same way that each translated book is a unique version of the original novel. To take the analogy further, if I was fortunate enough to have written the first Harry Potter novel, it may be the case that I wouldn't understand the language into which it is translated. Thus I could be given the Latvian version of the novel, and I could reasonably surmise that it tells the same story as the British English one, but I would be unable to read it. In the same sense, the version of my program that has been compiled into machine code might be impossible for me to read: it is said to be "machine-readable", in that the computer can understand it, but it is far from easily readable for humans.

An interpreted program is stored in a human-readable form. When the program is executed, an interpreter modifies the human-readable content as it is run. This is analogous to the role that a human interpreter performs. For example, rather than translating the British English version of Harry Potter into Latvian and then providing the Latvian version to someone who understands the language, (as per compilation), we could hire a translator who knows both British English and Latvian. The translator may choose to read each line from the British English novel, translate each line (one at a time) into Latvian, and, as each line is translated, relate it to the listener. The computer interpreter performs the same function: it reads an instruction in one programming language, translates it into machine code, and then executes the machine code version. Once that instruction is out of the way, it moves along to the next, performing exactly the same task, in much the same way that the interpreter of the Harry Potter novel would move on to the next line once the first has been related. Unlike compiled programs, at no point is a complete, discrete, machine code version of the program produced: at any point in time only a small number of instructions exist as machine code versions, and these will be removed from the computer's memory when they are no longer required.

There are advantages for both types of software development. As a generalization, compiled programs are faster to run but slower to develop. Compiled programs often run faster because the computer only needs to execute the previously translated instructions. In interpreted languages, every time the program is run the computer also needs to translate each of the instructions. This translation causes a delay, slowing the execution of the program. On the other hand, interpreted languages are often written in a smaller time frame, because the languages are simpler and the whole program does not need to be compiled each time a new feature is bug tested.

Features of both approaches are discussed in more detail later.

Levels of programming language
Programming languages are described in levels. Low-level programming is close to machine code, high-level programming is closer to natural languages. At the most basic level (or "lowest level") is assembly language. This language is just a direct translation of the binary instructions the computer executes—each assembly language instruction directly relates to one in machine code. Thus just as every kind of processor architecture has its own machine code, each processor architecture also has its own assembly language.

Here's how to add two numbers in MIPS assembly:

LUI R1, #1 LUI R2, #2 DADD R3, R1, R2

This just did the calculation 1 + 2 = 3. Very roughly, the first two lines load the numbers "1" and "2" into the computer's memory, and the third instruction tells the computer to add the values together and store the result.

As you can see from the example, assembly language is quite dissimilar to natural languages. Higher level languages both get closer to natural languages and provide more efficient methods of expressing the instructions—thus to implement a given feature for a program in assembly language almost always requires more code than implementing the same feature in a higher level language such as C or C++. Assembly language gives the programmer the ultimate in flexibility and performance, at the expense of complexity and development time.

 * Reading Assignment: Assembly language (Wikipedia article)

High-level languages look more like natural language with mathematical operations thrown in. These languages require more translation before the computer will understand them, but they are much easier to write. Here's what the same program might look like in a high-level language:

x = 1 + 2;

The variation between different programming languages can be quite extensive. Traditionally, the first program a programmer writes in a new language is Hello World—a simple program that outputs the phrase "Hello world!" (or a variation thereof) to the user. As will be clear from the following examples, even this seemingly simple task can be expressed in many different ways depending on which language is being used. For example:

In C:

int main { printf("Hello World!\n"); return 0; }
 * 1) include

In BASIC:

10 PRINT "Hello world!" 20 END

In Java:

public class HelloWorld {  public static void main(string[] args) {    System.out.println("Hello world!"); } }

In Pascal:

program HelloWorld; begin writeln('Hello World'); end.

In Perl:

print "Hello World!\n";
 * 1) !/usr/bin/perl

In Python: Of these examples, C is considered to be the "lowest level" language, which is to say that it is the closest to machine code. The others are considered to be higher level languages, and thus are (generally) closer to natural languages. Some of the complexity you can see, especially with Java, derives from the way the programs are structured: Java is an object-oriented language, while Pascal, to pick but one, is a procedural language. However, this is something that we will need to address later.

 * Reading Assignments
 * High-level programming languages (Wikipedia article)
 * Optional: The Hello World Collection (Offsite collection of "Hello, World!" programs)

 * Activity
 * Discuss why you think that there are so many different programming languages; why do you believe that a programmer would choose one over the other? It may be worth comparing this question to why there are so many different natural languages, and ask why someone who is multi-lingual might choose to use one natural language over another.

Translation schemes
Depending on the language used, and the particular implementation of the language used, the process to translate high-level language statements to actions may involve compilation and interpretation. Compilation is handled by a special program called a "compiler". Interpretation is a process in which language statements are realized into actions, and is conducted either by the CPU or by a special program called an "interpreter" or Virtual Machine.

Translating source code to machine code instructions is a process that is generally restricted to the compiled scheme and interpreted scheme. A common misunderstanding is that these schemes are properties of the language itself. Technically speaking, they are properties of the implementation of the language. Thus different implementations of the one language may produce compiled or interpreted code.

To further complicate matters, perfect classification of different schemes is difficult. To illustrate this, we will discuss the following examples below:
 * An implementation using multiple schemes
 * Multiple implementations using multiple schemes
 * An implementation changing their scheme
 * An implementation using a mixed scheme

 * Compiled Scheme. A program's source code is compiled to machine code/binary/executable. This executable is then interpreted by the CPU (in practice, most compilers do not compile directly to machine code, many compile to C then to assembly before recompiling to machine code, this process is usually done transparently). Example: GCC (C, C++), MSVC (C/C++), ghc (Haskell), fpc (Pascal), gpc (Pascal), V8 (JavaScript), Visual Basic 6 Native Code (BASIC)

 * Interpreted Scheme. A program's source code is interpreted line-by-line by a program called Interpreter, when there is a control structure . In practice, this scheme is very rarely used, because the interpreter had to reinterpret the source code every time the line is executed again and because it isn't very hard to cleanly move to any one of the mixed schemes. Example: PHP 3 and before (PHP), SpiderMonkey (JavaScript)

 * Mixed Scheme. This is a group of schemes that involves a compilation to an intermediate form but it is never compiled to machine code. Note that some languages implementation in this scheme (e.g. Sun Java) might selectively compile parts of its code to machine code (Just-In-Time compilation) for optimization purpose
 * Virtual Machine Scheme. A program's source code is compiled to a platform-independent byte-code file, which resembles machine code but cannot be run directly by the CPU. Instead, a special program called Virtual Machine would interpret the byte-code. Example: javac and JVM (Sun Java), CPython (Python), PHP 4 and above (PHP), Visual Basic 6 P-code (BASIC), various .NET languages (C#, VB.NET).
 * Abstract Syntax Tree Scheme. A program's source code is compiled to an in-memory object equivalent of the source code. Thus, the source code is only read once and the program is run from this tree. Example: perl (Perl), pugs (Perl)

Also note that all languages are theoretically able to be implemented in every scheme. However, each language fits a certain scheme better than other schemes.

Some shortsighted programmers consider interpreted languages to be inferior because they are slower compared with compiled languages. In fact, because of their dynamic nature, interpreted languages can be substantially more flexible, easier to learn, and faster to develop—sometimes you can have your program weeks sooner for the small price of being a fraction of a second slower; especially when you are using the fast computers of the modern age. In some limited cases, an interpreted language's core functions might be so highly optimized to the extent that an average quality program in compiled language could be slower than one written in interpreted language. In other cases (like applications using a database, or network access) a majority of your application's time is spent waiting to access data or the network, and using a "faster" compiled language will not make much difference. In fact, the general rule is: don't choose a language because it's faster. Otherwise, you'd be better off using assembly language directly. Choose a language you're comfortable with, one that looks "sexy" to you. It will be your friend during your whole programming work so choose well. Try several languages out before making a definitive choice.

It would be nice to have one language to "rule them all"—but we don't. The fact is, many different languages exist for different purposes. There are a few languages that fulfill a wide variety of programming needs, but to encompass all of them, it would have to be such a huge undertaking and become cumbersome and segmented as programmers begin customizing the language to their needs. Truth be told, many languages have become customized thus and released as independent packages, simplified for a smaller audience and streamlined for efficiency in that area only. Lua is for example targeted for scripting in games. While it's usable from outside of this context, that specific context is where it will probably be the most efficient/adapted.

Why should we create computer programs?
What is it that makes computer programming useful or pointless? What are the goals, common problems, and solutions related with computer programming?

Optional reading: History of programming—what problems and tasks motivated the invention of programmable machines?

Writing a program without knowing what problem you are trying to solve is the equivalent of swinging a knife without knowing what it is that you want to cut.

Code with a purpose. This is how:

Basic goals of computer programming
When you are planning to create a computer program you should:
 * Ensure your program fulfills the need it is addressing.
 * Ensure that people can easily use your program.
 * Ensure that it is easy to understand, fix, and improve your program without a major time investment.
 * Enhance problem solving using logic.
 * Developing a high understanding of principles in programming.
 * Demonstrating basic concepts, and software applications.
 * Recognizing ethical working codes.

Common problems
These are very common mistakes programmers make:
 * Your program does not do a job any better than an available alternative program. At best, you're re-inventing the wheel.
 * Your program does not work as intended.
 * Your program is too complicated or too primitive to be useful to most people.
 * Other people, or yourself at a later time, can't understand the programming behind your program. This means your project won't grow.

Solutions

 * Utility and Usability
 * Survey the field to look for programs similar to what you intend to develop. Determine what you like and don't like about those programs. Figure out ways to improve those programs.
 * Find source code for similar programs to what you want to make if at all possible. Unfortunately, people often write a lot of inferior code and leave it floating around the Internet. Don't be one of those people. Only release useful, well-written programs.
 * Thoroughly plan what you want your program to do before you start working on it. One way to do this is to make a flowchart of what you want your program to do.
 * Aim towards the maximum functionality your program can achieve while maintaining minimal complexity. Think of the iPod, matchstick, doorknob and television. They are simple yet effective.
 * If possible, talk to people who might use your program to get an idea of what features they would want or expect.
 * Remember the 80–20 rule: 20% of the features in most programs are used 80% of the time. If you can successfully identify even a few of the seldom used features and leave them out, you can save yourself some time and frustration.
 * Maintainability
 * Make it easy for someone to look at your program's source code and understand what's going on.
 * Use comments when you're doing somewhat complicated things in your program, or when in doubt.
 * Always choose readability of your code over memory performance. Though in the short run this may not always be the best choice, in the long run, the performance can be improved if the code is easy to understand.
 * Use simple, easy-to-understand names for variables. The convention is that a variable should be written variable_name or variableName.
 * Look at examples of source code, and especially source code intended as an example of proper programming form. Recognize the structure they're using to make things simple.

Make programming easy for you and everybody else
Computers and computer programs are intended to make our lives easier, not more complicated.

Programmers have figured out a very good way of doing things: Free Software.

Free Software is software written by an author who has released that software with the source code, freely available for anybody to look at, modify, improve and implement into their own software. Just like wiki, this is an easy, efficient and useful way of doing things.

To make programming easier for all coders, you should:
 * Release under GPL GNU General Public License
 * Take advantage of Free Software to create more Free Software
 * Make your code readable and efficient

How does one become a programmer?
A programmer is generally tasked with producing a solution to a problem via a computer program, which can be reused as various particular instances of that problem arise. To accomplish this task, the programmer therefore must be able to understand the problem, derive an appropriate solution, and then be able to effectively express that solution in a computer programming language.

The first prerequisite to becoming a programmer is to develop a strong background in problem solving as is often required in fields such as mathematics and engineering. The ability to formally, concisely, and clearly state a problem and then derive its solution is a fundamental skill that precedes the process of any computer coding. The study of computer algorithms focuses on the generalized problem solving approaches often applicable in computer science. Techniques such as programming design patterns provide practical templates which often help frame solutions in an understandable, reusable manner. In general, there are many different classes of problems in computer science that require different techniques to solve effectively: having a strong repertoire of approaches aids in finding good solutions.

The second prerequisite to becoming a programmer is knowing a programming language with which to express a particular solution to a problem. A programming language is a tool, which practice will help hone into expertise. Learning multiple languages can often be helpful as the process will demonstrate the particular strengths of different approaches to solving particular classes of problems.

In both these areas, practice is essential. Exposure to a wide variety of problems and tools to solve them will increase your understanding of the field as whole, to judge for yourself the relative merit of techniques in the field, as well as to discover unique, new approaches to addressing the problems of computer science. As with the practice of any new skill, do not be afraid to make mistakes, to redo earlier work, or to stumble along the way to expertise.

Those unfamiliar with programming may think it is like a write-up, written linearly from beginning to end. That is not the case. Instead, it rather resembles sculpting.

Don't be afraid to make mistakes because you will make them—constantly and for the rest of your career. Even the best programmers make mistakes regularly (if they try to say differently then they are either lying or deluded). Making mistakes is really part of the programing process. Someone said, to find a solution to a problem you must partly solve the problem. So you'll probably end up rewriting parts of your programs several times. Part of what distinguishes better programmers is their ability to catch at least some mistakes before they become a problem. Nobody can catch them all without help. Well, nobody can catch them all : there is no bug-free program. Additionally, it is good coding practice to code the smallest modules of a program, one at a time. This provides an isolated testing environment. Just be sure that everything is planned carefully from the outset, so that the little modules are not "orphaned" from other modules that they need to run. Note that when this approach is used, care should be taken to lay the foundation first, making careful note of "dependencies" within the program; code modules upon which other modules rely first, and then code higher-level modules after the foundations have been thoroughly tested. Unit testing is a good programming practice. Some programming processes, such as XP (eXtreme Programming), recommend to write tests before actual code.

Learn to work with others in a team environment. People have different strengths and weaknesses and a good team can bring together people whose strengths and weaknesses are complementary. The members of a team can teach each other. Most importantly, teams can tackle problems that would be too big for an individual. Beware, though, teams are not easy to lead and you can easily make a project a disaster by just gathering as many people as you can. If you want to work with a team, come with a solid design and a strong vision of what the project should look like when it's finished. If other members of the team suggest new ideas, take them with consideration but do not fall in the feature-greed pitfall, e.g. your project is never finished because the final goal grows beyond all proportions. As the XP process suggest, make small and frequent releases, prefer running code to vague and abstract design. Also, be careful how you go about this, you may not always agree with your team and that's okay!

As you continue to practice the art, take some time here and there to learn about the underlying theory that makes up the field commonly referred to as Computer Science.

 * Next Lesson
 * Introduction to Programming


text:
Switching from C to C++

Some believe that learning C++ is easy and suggest learning C before learning C++, while other people disagree and believe that if your intention is to learn C++ that you are better off learning C++ directly rather than trying to learn C first. Switching from C to C++ can be both easy, as there are many similarities between the two languages, and hard, as there are many differences that require forgetting what you know and habits that you may have developed from programming in C.

Differences

 * C++ uses new and delete operators for memory management while C uses library functions.
 * C++ extends structs and unions, and also includes classes.
 * C++ has templates while C does not.
 * C++ has operator and function overloading.
 * C++ requires type casts conversions but C is less strict and C++ also provides alternative type conversion semantics.
 * typedef creates unique types in C++, and creates type aliasing in C.

Thinking in C++
If you are previously a C programmer and have decided to switch to C++, you should throw away some C concepts and get used to the C++/OO way of doing things:

 * C programmers tend to write lots of global functions. If these functions needs an object to work, you should make them member functions of a class.
 * You should group similar functions working with different types in a template.
 * C programmers usually prefix their identifiers to prevent name conflict. However, this is not necessary in C++ as they can be put in a namespace.
 * There are usually lots of pointers and type casts in C. However, you should use less pointers in favour of references and less type casts in favour of derived classes.
 * Think everything as objects. For example, if you write a control program for a plane, you should create a class called Plane and create functions inside it.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Switching from C to C++


text:
Introduction to Programming/Organization

How is a program organized and used? [part 1]
A simple program is a list of statements. When the program is invoked, the computer starts at the beginning of the list and executes each statement in order until it reaches the end. Then it stops. The exact form of a program, where the "first statement" is located as well as what can be done in a statement are all determined by the programming language being used.

From here on, this learning activity will be covering all material that should be reinforced through actual programming exercises. If you have not yet selected a programming language, please do that now and do the first lesson. This lesson will usually introduce a minimalistic program known as Hello, world!. Though seemingly meaningless, this lesson is nevertheless important because it gives students three critical skills—editing a source file, compiling the source file (if it is a compiled language) and running the resulting program.

 * Break to do the first programming exercise
 * Java version

Statements
Most computer programming languages have statements or something similar to them. The terms line and line of code are also used.

A statement is a more-or-less atomic piece of code that is clearly differentiated, usually by a special character or character sequence called a statement terminator.

In C (and languages like C such as C++, Java, etc.) the statement terminator is a semi-colon. In BASIC (and languages like BASIC such as Fortran, Ruby, Python, etc.) the statement terminator is a newline. In Prolog and Erlang the statement terminator is a period (.).

this could be a statement; this would be another statement;

The syntax rules for statements are very rigid and ruthlessly enforced by the compiler/interpreter. Inexperienced programmers sometimes miss subtle nuances in programming language rules, causing them no end of trouble. When learning a new programming language, you should have access to an experienced programmer who can help you with these kinds of problems.

 * Next Lesson
 * Previous Lesson


text:
Introduction to Programming/Variables

A "program" is a set of instructions stored in a computer's memory for it to execute. Usually in the course of execution the program will create new information. Also, nearly every program written must store information supplied after the program was created.

Such information may include user input, custom settings, or calculated values. Because this information can vary, the term variable is used to describe the element of a program which stores this information. For example, a name variable could contain "Jack" or "Jill" or any other value.

Variables
You may already be familiar with variables as they are used in mathematics—to represent unknown or inexplicitly defined fields of an equation. For instance, in the equation y = m*x + b, each alphabetic letter is a variable that represents something unknown (m is the slope of the line, b is the y-intercept, x is any legal x-value in the function's domain, and y is any legal y-value in the function's range.) In computer science, however, the value of a variable is never "unknown", but rather it is explicitly defined, although it may change in ways that the program's author cannot predict. It is important to remember that there is absolutely no (or at least very little) relationship between the term variable, as it is used in mathematics, and computer program variables.

In computer science, a variable is nothing more and nothing less than a named location in memory where data can be stored. In some languages, any kind of data can be stored in a variable while, in others, each variable is given a well defined type by the programmer and only data of the correct type may (or at least should) be stored in that location.

The location referred to by a variable may or may not have useful data in it, but typically it does not until it has been initialized. The process of carving out a piece of memory and assigning it a name is called creating, allocating or declaring a variable. In some languages, variables are automatically initialized when they are declared (given a value when they are established as pointing to that location in memory). Most languages allow variables to be initialized when they are declared but do not require it. The use of an uninitialized variable is a common source of programming errors, as the data stored in memory at the location that the variable points to is "garbage", nonsense bits that could have adverse effects on the running program.

In a program, you may see a line of code such as this one:

It may look like a math equation, but it is more than a math equation. It is an instruction to the computer to fetch the values from two memory locations, which do have absolute "ID numbers", but for our purposes and the semantics of programming languages are called pi and r, multiply those values together and then store the result in the memory location called area. It is very convenient that this code can take the familiar form of an equation but we cannot allow its appearance to fool us because it does not define a mathematical function; rather it defines a strict set of instructions that the computer will follow when running this line of code.

Similarly, most languages allow variable assignments such as the following:

Looking at this assignment as a mathematical equation, it makes absolutely no sense—no value is equal to itself plus one. But we're not talking about mathematics here. While it may look like an equation, this is a variable assignment that states "retrieve the value of X, add one, and store the result back in X." So if the value of X is 0 before it reaches this line, it will become 1 afterward.

Several languages have a particular operator for this operation, e.g :

Variable Types

 * Reading assignments:
 * Strong typing (Wikipedia article)
 * Data types (Wikipedia article)

Most languages have a variety of primitive types such as integers, floating point numbers, single characters and Boolean variables. Many languages also support a variety of aggregate types (eg. arrays). The exact size and format of available types may vary based upon operating system, hardware architecture, programming language and/or the specific compiler used.

One of the important things to take away from the reading is the concept of static typing. Most modern languages are statically-typed.

Despite the tremendous variety, the statically-typed languages generally follow some well-defined patterns:
 * Compilers are quite picky about assigning valid values to each variable.
 * There exist methods of converting between types.
 * There are ways to define custom types.

Byte

 * Reading Assignment: Byte (Wikipedia article)

With the possible exception of Boolean variables and user defined types, the byte (eight bits) is the smallest unit of information used in modern programming languages. A bit is represented by a 0 or a 1, and therefore a byte is a sequence of 8 0's and 1's, which have a total possible permutation of 28 combinations, or 256 distinct combinations.

Application to Variables
System memory must be allocated to store variable values; both the compiler and the author of a program must work together to determine how much memory should be allocated for each variable, and this memory is allocated in a sequence of consecutive bytes in memory.

Variable Data Types
Below are common usages of the byte in programming languages for data types of variables.

Numeric Types
Each of these have slightly different names on different platforms and in different programming languages. The absolute size is specified in bytes, regardless of the environment. (see Data Types for more detail)
 * one-byte (8-bit) value: 0 to 255 (unsigned) or –128 to +127 (signed)
 * two-byte (16-bit) value: 0 to 65535 (unsigned) or –32768 to +32767 (signed)
 * four-byte (32-bit) value: 0 to 4,294,967,296 (unsigned) or –2,147,483,648 to 2,147,483,647 (signed)
 * eight-byte (64-bit) value: 0 to 18,446,744,073,709,551,615 (unsigned) or –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (signed)

Character Data
A single byte is often used in many languages to store a single text character. These are often denoted by the variable type char, which is a short-hand for character. Other languages, such as Java, might use one or two bytes to store a character, depending on the string.

 * Next Lesson
 * Previous Lesson

title: Introduction to Programming/Variables


text:
Introduction to Programming/Control Structures

Up to this point, the programs that we have looked at are very simple and serial in nature. Obviously computers can do more, but how?

Say, for example, that you write a small program that calculates how many seconds are in a given year. This is clearly a pretty trivial program, but it does have one interesting wrinkle—the number of days in a year isn't a constant. So how do we write a program that uses different values depending on the year? There are many different ways that this can be accomplished, but one of the most straightforward is to have a piece of code that is only executed if some condition is true—if, say, the year in question is a leap year then set the number of days to 366 instead of 365.

The If Statement
Up to this point, everything that we've covered involved simple, linear execution of every line of code. In the seconds in a year example from above, we could have a line that declared a variable daysInYear and initialized it to 365.

int daysInYear = 365;

That is the end of what we know how to do so far.

What we need now, is some way to say that, in the event that the year is a leap year, assign the value 366 to the variable daysInYear. One way to do this is with an if statement.

In most programming languages, an if statement contains three parts. The first part is a keyword that tells the computer that it's an if statement (some languages may have an equivalent structure that uses a different key word). The second part is a boolean expression. The third part is a statement or group of statements.

The way that the computer executes an if statement is that, first it evaluates the boolean expression. If the expression evaluates to false, it skips the third part, the statement(s), completely as if they weren't even there. On the other hand, if the expression evaluates to true, then the statement(s) are executed.

In a Java/C/C++ environment, where there was a boolean variable isLeapYear, you would write code that would look something like this:

int daysInYear = 365; if (isLeapYear) {       daysInYear = 366; }

It may not be the most interesting code ever written, but it is simple, direct and produces the correct result.

Variations Of If Statements
An alternate way to set the number of days in a year might be:

int daysInYear; if (isLeapYear) {       daysInYear = 366; }   if (! isLeapYear) {       daysInYear = 365; }

This form seems kind of awkward and it requires the condition to be evaluated twice. Many programming languages allow an extension of the if statement, an else clause. It would look something like this:

int daysInYear; if (isLeapYear) {       daysInYear = 366; }   else {       daysInYear = 365; }

An if statement may be followed by exactly zero or one else statements. If the if statement evaluates as true, then its group of statements (in this case "daysInYear = 366;") are run. If the if statement evaluates as false the else clause's statements are executed (in this case "daysInYear = 365;").

Sample Problem: Checking an Error Condition
One of the more common uses for the if statement is checking error conditions.

Let us suppose that we are working on a piece of code that performs a divide in a calculator program. We have three variables dividend, divisor and quotient. We want to divide dividend by divisor putting the result into quotient, unless divisor is equal to 0 in which case we want to report an error message. Assume that there is a statement ReportErrorMessage that does exactly that and write some code that performs the divide operation.

answer

Loops
A loop is a program structure that executes the same piece of code zero or more times. A loop consists of a group of statements (called a block in many languages) to be executed and a boolean expression, called a condition. Every time the computer executes the statements in the loop (called an iteration), the condition is evaluated. The computer continues to iterate as long as the condition evaluates to true.

In some programming languages a while loop looks something like this:

int counter = 1; int sum = 0;

while (counter < 10) {   sum += counter; print sum;

counter += 1; }

This is the style of while loop used in Java, C and C++. The code of the block is delineated in this example by a matched pair of curly braces. The condition is inside the parenthesis that follows immediately after the keyword while. The sample while loop given above will execute nine times with the value of the variable counter starting at one. With each iteration through the loop, the value of counter is incremented by one. When the value of counter reaches ten, the condition will evaluate to false and the loop will not be executed. With each iteration, the program will print out the sum of the first N integers with N equal to counter.

Exercise: Fibonacci numbers
Using the above loop as a template, create a block of code that will print out the first 10 Fibonacci numbers.

answer

Pre-conditions versus post-conditions
The while loop shown above is an example of a loop structure where the condition is checked before the code is executed. This is known as a pre-condition. The block is not executed at all if the pre-condition is false when reaching the loop.

In Java, C and C++, there is a structure that is called a do-while loop that is nearly identical to a while loop, except that it uses a post-condition. Because the condition is checked at the end of the loop, post-condition loops are guaranteed to execute at least once.

int counter = 1; int sum = 0;

do {   sum += counter; print sum;

counter += 1; } while (counter < 10)

 * Next Lesson
 * Previous Lesson


text:
Introduction to Programming/Scope

The Motivations For Scope
Imagine that you have a really nice collection of tools—really nice. Now imagine that you decide to lend your tools to any neighbor who asks. Unless you have exceptional neighbors, you will probably find it necessary to modify this policy eventually because some of those tools will end up broken and others will disappear forever without a trace.

In the early days of computing, computer memories were small, the amount of data being processed was small and the size of the programs were small. In those days, all of the data was kept in one place and could be accessed by any part of the program. As computers and programs got larger and more complex, it was found that it became far too easy for one part of a program to mess up the data needed by another part of the program. Furthermore, it became difficult to determine which parts of the program were using the data correctly and which were not.

Features were added to programming languages so that parts of a program could control the access to their data.

Scope
Scope refers to the visibility of variables and methods in one part of a program to another part of that program. The importance and meaning of scope varies between languages, but there are two general scope concepts many languages have in common: local and global scope.

Local Scope
Variables or methods that have local scope (and for object-oriented programming, this includes instances of classes) are accessible only in the current block of code. There is a sort of "nested sets" model to the notion of scope. Beginning with global objects (see below), each contained block may access objects defined in a containing block; that is to say, in a code fragment in which a variable is defined and the program enters some kind of loop block, that loop sub-block does have access to that variable defined outside of the block, and it may, additionally, override it temporarily by declaring a variable of the same name in its own local scope (the scope of that loop block). See the example below. Local scope essentially refers to variables that are limited, as far as access is concerned, to the most current block of code, and not necessarily to any "outer" blocks that might also be counted in the nested model.

Global Scope
Certain variables and methods can be said to have global scope. This term encompasses a very qualified situation: all of the variables defined at the very beginning of a program are available to the entire program. Likewise, in a function, the variables declared at the beginning are available to all the remaining code in that function.

Scope Resolution
Most programming languages allow the programmer to "step outside" the current local scope and bring in variables or methods "from the outside" so to speak. In C++, this is accomplished using the "scope resolution operator" which is the double-colon: :: By using this operator, the function or program can obtain access to data members located in another "branch" of the program. If the structure of containment of variables in a program is thought of as a family tree, this means that a child requests access to his cousins through, say, the grandparents. e.g. "My mom's sister's daughter's dolls" is an example of stepping through the tree, and such a reference would use the scope resolution operator, although it is rare to see more than one level referenced in a statement containing the ::.

Duplicate Names
Variables used in a program, especially one involving mathematics, often are designed to solve a problem in which the same letters are ordinarily used on paper, but even then represent different values. Think of the x or a and b. A programmer must pay very careful attention to this fact and not "re-use" variable names, because to the computer, they are all the same. With one exception. It is possible to override a local variable that is defined slightly above the current block, by declaring another variable of the same name and possibly the same type, inside of this current block. This new variable with more local scope than the first can be used within the current block, but because the outer variable has been temporarily overridden, the new variable's value will hide whatever the outer variable's value is. Here is a C++ example:

int a=25; int b=30; { //at this point, a=25, b=30 a*=2; //a=50, b=30 b /= 2; //a=50,b=15 int a = b*b; //a=225,b=15 } ''//a = 50, b = 15

As you can see, the two variables were manipulated within that inner block, but then a second version of a was created with a new value, that was lost once we passed out of the block. The other changes were preserved, however.

Even with an understanding of variable scope, it is always good programming practice to declare variables at the beginning of their respective block, actually as high up as is practical in the hierarchical structure of the program. This is so that they can be easily referenced and there is no ambiguity as to whether a variable has been defined at any given point in the program.

 * Next Course
 * Previous Lesson

title: Introduction to Programming/Scope


text:
Problem based learning

Problem based learning (PBL) is an approach to education where students can actively learn. Used mostly in higher educational settings, PBL allows students to work together in teams and tackle problems that resemble real-world scenarios. Rather than instructors lecturing and giving students’ information to memorize for a test, PBL put the students into the driver’s seat. This gives students the ability to collaborate and explore what they already know, their hunches, and explore available resources to try and find a solution. Once the problem is clarified, students set out to find answers and therefore teach themselves.

Where it is used

Problem based learning is used in a learning environment, traditionally the classroom. Although PBL is geared towards collegiate settings it is being used in high school and other institutions. PBL has been a primary method of teaching in the medical and law fields for a long time. It is now being implementing in engineering, computer science, and other fields as well. Traditionally problem based learning occurs in the classroom setting and therefore students and professors are the key participants. In PBL the students are more essential than the instructor. In the professional field, project teams working on real life problems are using the same process.

To gain a picture of where PBL is being used around the world, the PBL Directory was set up by the University of Brighton. How it works

Problem based learning is effective because it does not simply entail the student to memorize dictated facts, but requires the students to become actively involved and use their own reasoning skills. PBL requires the student to access the knowledge he/she already has and use available resources to discover new information. Being able to relate a topic to an already existing understanding of the world helps students learn and understand new information. If a student learns or figures concepts out on his/her own he/she is more likely to retain the information. Having to constantly recall on information learned causes a deeper understanding of the subject and better long term recall, because constant refinement and revision of what was learned will take place throughout the course.

PBL accomplishes these objectives because the problems are the main vehicle for learning not the instructor. Making the student the center of learning will make the student actively engaged and more motivated. One of the first steps in true learning is to recognize that the information is important. Presenting real world based problems to students early in the learning process demonstrates the importance of the material. PBL causes students to learn how to apply information and approach problems that have no definite right or wrong answer, which improves the students reasoning skills and critical thinking skills, along with introducing new material. Students who use problem based learning in school have a greater understanding of how different subjects relate to each other, understand the application, and have better problem solving, group working, critical reasoning, and communication skills.

Implementation

The class setting that uses problem based learning is slightly different than the typical classroom setting. The teacher should not lecture very long, he/she should simply introduce the topic, problem, and what is expected of the class. The students then divide into groups. In the groups the students ensure they understand the problem and then begin brainstorming on solutions. The students are allowed to use the internet and any other available resources. Between the resources and the knowledge of the various group members a solution is devised. Even though there is no right or wrong answer the students need feedback to make problem base learning an effective learning tool. The facilitator then informs the group what was good, what would not actually work and why, and other suggestions. Allowing the class to see other solutions is also another good way to receive feedback and additional ideas.

title: Problem based learning


text: User talk:English202c

title: User talk:English202c


text:
Storyboard Artwork Project/Using 3D software

{| cellspacing="0" cellpadding="0" style="margin:0em 0em 1em 0em; width:98%" How to create 3D stamp artwork for the Storyboard Artwork Project
 * colspan="2" style="width:100%; vertical-align:top; border:1px solid Sienna; background-color:Cornsilk;" |

Creating Stamps with 3D software
You can create 2D poses using a variety of 3D modeling and animation programs. DAZ Studio and Blender are free (as in free beer), while Poser is easy to use and Blender is open source (free as in free speech) and runs on all platforms.

 * Blender
 * Blender is a free and open source 3D animation suite. It supports the entirety of the 3D pipeline—modeling, rigging, animation, simulation, rendering, compositing and motion tracking, even video editing and game creation. Blender is well suited to individuals and small studios who benefit from its unified pipeline and responsive development process.

 * Poser
 * Poser was the first easy to use program for creating 3D still artwork of human figures which look realistic. The original artwork for Poser was created by the parent company of DAZ which now has DAZ Studio.  Now there are additional figures are available from a wide variety of shops on the Internet.  There is an entire cottage industry out there of about 200,000 people who create artwork of human figures.

 * DAZ Studio
 * DAZ Studio is a free 3D program which works with many of the same figures as Poser. At the DAZ Store, you can see all of the digital puppets sold by DAZ.

 * }

{| cellspacing="0" cellpadding="0" style="margin:0em 0em 1em 0em; width:98%" Position and render the model
 * style="width:60%; vertical-align:top; border:1px solid Gold; background-color: LightYellow;" rowspan="1"|

Three Views
The easiest way is to create just three views of your figure. To do this, you simply put the figure on an empty background and take pictures from five angles. With DAZ Studio, simply rotate the camera around the figure. Position the figure in a natural pose with the mouth slightly open (so it can be used in shots where the person is both not talking and talking.)

The pictures should be at least 500 pixels tall. Use a portrait lens. (This is a mild telephoto lens. This is about a 135mm lens on the old 35mm film cameras.)

For the storyboards of the short motion picture "Seduced by the Dark Side!" which talks about the meaning of life and the movie "Star Wars", Wikiversity Film School needs stamps of a young person and an old person. We need both a set of stamps full height and a set of stamps for a medium shot as shown above.

 * style="padding:0em 0.5em 0em 0.5em;" |

The angles (if you do three angles
 * style="width:40%; vertical-align:top; border:1px solid #abd5f5; background-color:#f1f5fc;" |

 * Position at five angles (or more)
 * Front at a slight angle (20 to 30 degrees)
 * Profile (80 degrees)
 * Back angle (135 degrees)

 * }

{| cellspacing="0" cellpadding="0" style="margin:0em 0em 1em 0em; width:98%" Position and render the model
 * style="width:60%; vertical-align:top; border:1px solid Gold; background-color: LightYellow;" rowspan="1"|

Five Views
Create five views of your figure. To do this, you simply put the figure on an empty background and take pictures from five angles. Position the figure in a natural pose with the mouth slightly open (so it can be used in shots where the person is both not talking and talking.)

The pictures should be at least 500 pixels tall. Initially try a portrait lens. (This is a mild telephoto lens. This is about a 135mm lens on the old 35mm film cameras.)

For the storyboards of the short motion picture "Seduced by the Dark Side!" which talks about the meaning of life and the movie "Star Wars", Wikiversity Film School needs stamps of a young person and an old person. We need both a set of stamps full height and a set of stamps for a medium shot as shown above.

 * style="padding:0em 0.5em 0em 0.5em;" |

The angles (if you do five angles
 * style="width:40%; vertical-align:top; border:1px solid #abd5f5; background-color:#f1f5fc;" |

 * Position at five angles (or more)
 * Front (5 degrees)
 * Side (20 to 30 degrees)
 * Profile (80 degrees)
 * Back angle (135 degrees)
 * Back (170 degrees)

 * }

{| cellspacing="0" cellpadding="0" style="margin:0em 0em 1em 0em; width:98%" Position and render the model
 * style="width:60%; vertical-align:top; border:1px solid Gold; background-color: LightYellow;" rowspan="1"|

Full set of Views
For a truly complete set of stamps, you can also create a complete set of view with the camera looking down about 30 degrees and another set of views with the camera looking up about 30 degrees. To do this, you simply put the figure on an empty background and take pictures from five angles. With DAZ Studio, simply rotate the camera around the figure. Position the figure in a natural pose with the mouth slightly open (so it can be used in shots where the person is both not talking and talking.)

The pictures should be at least 500 pixels tall. Use a portrait lens for straigth on shots and a wide angle for looking up and looking down.. (A portrait lens is a mild telephoto lens. This is about a 135mm lens on the old 35mm film cameras.  A wide angle lens can be as strong as a 24mm on an old 35mm film camera.)

 * style="padding:0em 0.5em 0em 0.5em;" |

The angles
 * style="width:40%; vertical-align:top; border:1px solid #abd5f5; background-color:#f1f5fc;" |

 * Position at seven angles (Telephoto)
 * Front at a slight angle (10 degrees left and right)
 * Front at a slight angle (45 degrees left and right)
 * Profile (almost 90 degrees)
 * Back angle (135 degrees)
 * Back full (170 and 190 degrees

 * Advanced
 * Same looking strongly up (very wide angle)
 * Same looking sharply down (very wide angle)

{| cellspacing="0" cellpadding="0" style="margin:0em 0em 1em 0em; width:98%" Examples of TEST stamps for Tux Paint
 * }
 * style="width:60%; vertical-align:top; border:1px solid Gold; background-color: LightYellow;" rowspan="2"|

Crop and mask the images

 * In a program such as Photoshop, crop the images and add a mask to create the stamp. Save the images as PNG files and upload to Wikiversity.  If you have trouble with any of this, I can do it for you.  (Simply @undefined [[Image:Crystal Clear app xfmail.png|32px]] and we will figure something out.)

The completed stamps

 * Here are the completed stamps after cropping and masking. Click on the picture to go to the original which will be full size. (These are only miniatures shown here.)

Load these stamps into Tux Paint

 * Once you have downloaded the full sized stamps to your hard drive, put them in the stamp folder for Tux Paint. Then the next time you start Tux Paint, these stamps should be ready for you to use in Tux Paint.

 * style="padding:0em 0.5em 0em 0.5em;" |

Two girls talk about the weather
 * style="width:40%; vertical-align:top; border:1px solid #abd5f5; background-color:#f1f5fc;" |

This storyboard was created with stamps in just a few clicks of the mouse.

The figure on the left is drawn smaller (magnified less) than the figure on the right so it looks further away.

The time to draw this picture was about 15 seconds. This makes storyboarding very fast.

 * style="padding:0em 0.5em 0em 0.5em;" |
 * style="padding:0em 0.5em 0em 0.5em;" |

The girl meets Tux
 * style="width:40%; vertical-align:top; border:1px solid #abd5f5; background-color:#f1f5fc;" |

Here we see a scene from the movie, "Tux and Me" where Tux explains the meaning of life to the girl.
 * }


text:
Template:I5

 * This is similar to, but defaults to five spaces rather than three when indenting.
 * Essential guts:

title: Template:I5


text:
Talk:Service econosystem

There are specific application domains that I am targeting for the creation of initial service econosystems.

mises.org

biomedcentral.com

(specific projects within) sourceforge.net

These will each serve as learning examples that will enable the invention(s) to be reduced to practice.

A key motivation for developing information currency is the acceleration of information utilization.

title: Talk:Service econosystem