 
PROGRAMMING WITHOUT CODES

Hitesh Choudhary

Copyright Hitesh Choudhary 2014

Published at Smashwords

About the Author

Mr Hitesh Choudhary www.Newdemy.com]is a prodigious Information Security Expert and Programmer. He is an accomplished programmer, IT-Security researcher, Author, International speaker and engineered in electronics and communication. He is an expert in [C programming , C++, Objective C, Perl, Python, PHP, SQL, and most web-oriented technologies. Also he is a Cyber Crime Consultant. His expertise includes computer and network security, exploit research, wireless security and computer forensics. He is presently helping as a Cyber Crime investigator for Rajasthan police and Delhi police. He has solved a variety of typical cyber cases and has got appreciated by the Police Department. He is also an active consultant and speaker for Indian Army Intelligence and his work was featured in 20+ air, print and live media.

Author of many books, articles, and online courses on the technical aspects of the Internet and the World Wide Web, Mr. Hitesh has built a reputation for his ability to grasp complex technical topics and explain them in clear, concise terms.

Web Home Page: www.HiteshChoudhary.com

Table of Contents

Preface 5

Chapter 1: Programming without codes 8

What is programming? 8

Importance of programming 8

Terms associated with programming 9

What is programming language? 10

Writing statements and source codes 11

Complied and Interpreted languages 12

Just-in-time 14

Chapter 2: Introduction to variables and data types

Importance of variables and data 15

Importance of lowercase and uppercase characters 16

Understanding strong, weak and duck-type languages 17

Working with numbers 18

Usage of characters and string 19

Analysis on arithmetic operators in programming 20

White spaces in programming 21

Adding comments to code for human understanding 22

Chapter 3: Basic elements of programming 23

Introduction of 'if' statement 23

Usage of 'if' statement 24

Working with complex numbers 24

Introducing 'else' statement 25

Introduction to the 'switch' statement 26
Chapter 4: Breaking the code apart 29

Introduction to functions 29

Understanding variable scope 30

Splitting the code into different files 31

Chapter 5: Introduction to Iteration 32

What is Iteration? 32

Introduction of 'for' loop 33

________________________________________________________________ Table of Contents

Chapter 6: Introduction to string concatenation 35

Usage of string in programming 35

Finding patterns in string 36

Analyzing different patterns in string 38

Importance of uppercase and lowercase in strings 38

Introduction to regular expressions 39

Chapter 7: Working with arrays 41

What is array? 41

How to form an array? 42

Behavior of array 43

Iterating through collections 44

Collections in other languages 46

Chapter 8: Style in programming languages 47

What is style? 47

What is pseudocode? 48

Chapter 9: Input/output and persistence 51

Significance of input and output

What is event driven programming?

Introduction to file I/O

Chapter 10: Introduction to debugging 56

Cause of debugging 56

General errors in programming 56

Debugging logical errors 57

Chapter 11: Introduction to Object Orientation 59

Why we use object-orientation? 59

What is an object? 59

Analysis on real world objects 60

Reviewing object-oriented languages 61

Chapter 12: Memory Management across languages 62

What is memory? 62

Memory management in low and high-level languages 63

Introduction to algorithms 63

Introduction to multithreading 65

Chapter 13: Most renowned Languages 66

Introducing C-language 66

The Java world 67

.Net languages: C# visual basic .NET 68

Ruby
Preface

The greatest and miraculous change profoundly marked its appearance was with the sky-rocketing boom in the world of computers. And undoubtedly, the real power of magic relies in the handful lines of codes, which we hear every day as 'programming'. Everybody in this world should learn how to program a computer because the actual impact of the coding falls over you; as it teaches you not just how to think but how to think wide.

Most people don't realize just how important programming is. Just about every aspect of our modern lives is influenced directly by code. Today almost medium-to-large sized company either has a team of developers or has to hire developers to do jobs for them. From web applications to mobile applications, to DVRs and more; our lives run on code. The real benefit to learn programming is being able to automate simple tasks and find new ways of solving problems. Learning to program trains your mind to think about problems in a different way and breaks down the complex problems into smaller parts. And the biggest hot-spot more than ever is the number of development jobs increasing to a point where it is impossible to fill the demand. It's pretty unlikely that demand for programmers will ever decrease and it is very likely that it will only increase over the coming years. So, if you are looking for a great career field, with high earning potential and great future prospects; you might strongly want to consider learning to code. It's an immensely creative activity which is replete with fun and excitement where you're free to do anything and everything.

This book will help you out understanding each and every concepts related to programming without codes. This is an essential read for all the early beginners as well as the experienced programmers as this book deals with concepts starting from a lower level of difficulty to the higher one and that too in a very simple and a reader friendly environment. All those who start up with a mood of complex and puzzling appearance of programming will certainly wipe out from mind and the reader will develop a special interest in comprehending the basics behind the code.

What this book covers

Chapter 1, Programming without codes, deals with the very basic level to begin with what is programming. It makes you cognizant about the backdrop of programming and its very importance. It tells you about how programming is related to our daily lives. This begins with the very basic step and takes all the terms associated with programming along with simple examples. Relevance of source code and byte code is explained in detail with compiled and interpreted languages.

Chapter 2, Introduction to variables and data types, focuses on the variables and data types that are used in programming. It is very important to understand the usage and characteristics. Complete elaboration on strong, weak and duck-type languages have been given in detail. This chapter also give a brief about the backdrop of numbers in computers. Combinations of various operators have been elucidated.

Chapter 3, Basic elements of programming, introduces all the frequently used statements like 'if' and 'else', switch statement along with sufficient number of examples. This chapter gives you a very easy understanding.

Chapter 4, Breaking the code apart, talks about functions used in programming. Variable scope is another important thing to be taken care of while working with functions in most modern programming languages. Here we also talk about splitting the code into different files.

Chapter 5, Introduction to Iteration, opens up with explains each and every aspect of Iteration with its meaning. Usage of Iteration has also been detailed with simple examples. 'for' loop in programming includes some examples which fulfills the sole idea of conception.

Chapter 6, Introduction to string concatenation, helps you out in the usage of string in programming with proper and easy examples. We have also included a short analysis on an incident which will enhance you understanding concerning the subject. This chapter gives a brief about global property and pattern in string. Detailed introduction of regular expressions have been given.

Chapter 7, Working with arrays, discusses about the complete concept of array and its implementation in programming. Cases have been segregated for different steps while forming an array. A very smart example keeping tract on its analysis has also been included. This teaches you to understand the behaviour of n array.

Chapter 8, Style in Programming languages, opens up with giving you a brief about what style means in programming. How style varies in different languages is detailed in this chapter. A very basic and interested concept of pseudocode makes thing clear to you. As in other chapters here also we have taken certain cases for reader's easier understanding.

Chapter 9, Input/Output and persistence, deals with the inputs and outputs in modern and traditional programs. Event driven programming is detailed in this chapter along with sufficient examples. Other languages have been taken into account for input/output files.

Chapter 10, Introduction to debugging, opens up with a very interesting topic of this book. It tells you about the general debugging logical errors in programming. Gradually it takes to you the syntax to understand it in a complete package.

Chapter 11, Introduction to Object Orientation, talks about the reason of using object orientation. This chapter brings up the concepts from the ground level discussing about what object is actually referred in programming. A short analysis on real world objects has also been done.

Chapter 12, Memory Management across languages, talks about what memory is in terms of computer and how wisely it is managed in different languages. How memory is allocated to the object is elucidated in this chapter. Memory management in low & high-level languages are also included. It also introduces a brief idea about bubble sort along with short programs.

Chapter 13, Most renowned languages, makes the reader to dwell slightly into where C languages can be employed and very briefly what functions are used in it. Then, it includes basic concepts of Java, .NET (C# and visual basic.NET), Python and Ruby with simple examples. Short resemblance between these languages has also been introduced and succinctly explained.

1

Programming without codes

# What is programming ?

What does it strike to your mind when you hear of programming? You might have come across such question many a times. In simple terms, a computer program is a set of instructions. But this might sound is bit problematic because when you hear of complex program like Photoshop or Flash or some software playing high-definition video or a 3D game. Of course, that can't be simply a set of instructions. But it revolves around the some part of instructions and codes. There stands no doubt that every computer program we talk about is a sequence of instructions. There are separate small commands following in a sequence. There is no fixation or limit over the number of instructions. It can be either five or 5,000 or may be it can reach to 5 lakhs as well. Every instruction indicates towards the performance of small but specific task. The knack lying behind programming is: when you are given a lengthy task to perform then the systematic way to break it apart into smaller sections and consider it as individual steps. The surprising element here is that we all come across such situations in our daily lives and resolve them in the similar way.

# Case Incident: the importance of programming

Let's take an example for an easy understanding. Imagine a situation where you're waiting for a friend in a café house. Your friend falls into an ambiguous situation where he is unknown to the café house and want to seek your help to know the directions. Your phone pings up and it's your same friend, asking you for the way to reach you. He says he is at a nearby metro station and as that metro station falls in your way to your workplace. Though you're pretty well know the way from metro station to the café house and have a clear picture in your mind as simple as from point A to point B. But to make it understand to your friend who is unknown to the area you can't just instantly communicate the way it comes to your mind. You need to break it down into places as if they are connecting together one after the other. So, you'll begin like, "take right towards the museum hall at the main road, then drive down to half a mile, then after take left turn towards a fashion mall, then take the second right and finally turn left. You'll see café house opposite to fashion mall. You need to specific, simple, clear, self-contained while giving instructions.

The thing which plays the vital role here is: sequence. If you're directions get jumbled up then you'll receive false results. You might confuse your friend if you're instructions aren't clear and easy to understand. Ambiguity in the sequence in the instructions can take you long hours or might still not reach the real destination. All your need to be specific is with your sequence and also the particular landmarks that you mentioned would be of great help for your friend.

Now extracting out the core part from this example is that while programming we're directing the computer with specific and sequenced instructions.

Conclusion:

The whole story encircles the trying to break apart a complex task into smallest individual sections and making use of programming language in writing those instructions. Undoubtedly, if have never been too much into programming then, you would probably not known to those instructions and how they are framed up. Of course, while working on your computer you can't give instructions like 'turn left or right'. Now the question arises what can be those basic fundamental instructions to be given to a computer. In fact, they are very basic ones. Tasks like addition of two numbers or changing the color of the individual pixel or displaying a letter on the screen. It's important to give enough instructions to the computer to get your task done.

Programming that we see in our daily lives:

Now you can extract out from these examples that programming of the some complex games or various applications that we see now-a-days are nothing but an organized, individual and sequenced instructions encapsulated together to perform or run a specific task on your computer. If not that difficult to understand as sit seems, it's even not as easy as a piece of cake. It turns out generating accurate results when spend long and long hours to design some codes and of the capability of the computer to perform them well could not hold the back seat. Imagine if are asked to write a set of instructions that could calculate every single individual pixel on the screen thirty times a second. You might wonder with the level of speed it requires and the why the instructions hold such an importance in programming. Your one wrong instruction can produce futile results.

Take an example:

You can compare it with the example of a friend that we mentioned above. If his car has only two speeds: 0 and 5000 miles an hour. Your wrong instructions can make him drive down to some wage place and just result into a complete wastage of time. The same applies to computers. They exactly what you tell them, so the instructions you give should make sense in order to get the task done flawlessly.

# Terms associated with programming

Statements:

Programming languages deal with these instructions by writing what are called statements. You can consider these statements in programming languages as sentences in English. As we make use of words, numbers and punctuations to express one thought that spurts up in our mind; the same goes with programming codes framing an individual piece of instruction. Most of the times the programming statements are kept to be pretty short, sometimes just a few words. Now, making use of these words, numbers, and punctuations depends on the programming language being used to perform a task. You must have noticed some programming languages end up with a semicolon after the completion of each statement, same as we end a sentence in English with a period.

There are some languages which make use of all uppercase, some can make use of all lowercase characters, though there are some which follow their own set of instructions. To understand the rules of programming languages to need to understand and at least memorize the syntax they have. It is necessary to know how to write those pieces of instructions in the programming language that you're making use of. Writing the statements in the right order and using the right syntax hold a vital importance.

Some examples are as follows:

BASIC: Let Balance=1000

Applescript: set balance to 1000

Java: balance=1000

COBOL: MOVE 1000 to BALANCE

In simpler terms, programming is the ability to deal with the idea coming out of your mind and then taking it apart into its individual pieces.

# What is a programming language?

Since the scenario of computers has begun we have been accompanied through hundreds of programming languages. Perhaps, there are handfuls of programming languages that are more popular than others. Every time we think of any software, the thing which strikes our mind is the programming language hidden behind. With the boom in the computing languages in the software world, very day it gives birth to hundreds of languages. Some make a big hit with their arisen and many couldn't.

The changes in the software world are gradually come into shape. Once you're clear about the basics of a particular programming language; it becomes easier to pick up the other additional languages.

Consider the CPU, the chip, the central processing unit which is the brain of any computer, desktop, laptop, server, phone, game console. All of these do not understand the programming languages that we set to perform specific tasks on the computer. Many a times we might hear somebody saying that he's writing some codes for the computer, but it's an amiss. The thing to mark out here is that the chip only understands machine code or machine language. These are the actual instructions that run directly on the computer hardware. It is not possible to just write machine code despite of tricky programming languages. It reason behind this is that these are numerical operations which perform small instructions inside the computer memory. Such instructions are only readable by a machine and are not meant for a human being. There are different machine codes for different models of CPU.

Low and high-level languages:

Writing programs in machine code can be sometimes too lengthy and tedious task. They are meant to bridge the gap between human beings and the computer hardware. However, there are few languages that are quite close to machine code. These are known as assembly languages. The problem arising here is that the more the language is closure to a machine code, it will pose more problems in writing codes and it is required to have a detailed knowledge of the hardware. This came to be known as low-level languages. To overcome the drawbacks of low-level languages a new language was introduced; which came to be known as high-level languages. It is quite easier working in high-level languages and can be shared across different platforms. The only limitation with these languages is that they run slower. High-level languages hold a lot of importance and are widely used now-a-days. The thing to keep in mind is that it is important to convert high-level languages to machine code.

Importance of source code:

Programming is all about knowing about the source code which is sometimes referred to as statements like the way we use in Java, C++, Ruby, Python. The significance of source code lies in the requirement of translation into machine code so that we're able to run on the computer. The code we generally get associated with is actually the source code.

Before dwelling into the core part of programming it is necessary to understand three basic things.

  * how to write

  * how the source code gets converted to machine code

  * how to execute the program

Writing statements & source codes

Let's see how to write statements or source codes. Programming language's source code is written in plain text. The following points will help you out in understanding easily.

  * Open up a simple text editor that comes with your operating system (Notepad on the PC or TextEdit on the Mac).

  * The file extension is very important. Example: .js for JavaScript and .groovy for Groovy files or .txt for text files.

  * If you're writing code in a program where you see a formatting bar with bold and italic options, then that probably not the place for writing codes.

Programming language source code does not need to be bolded or underlined or italicized or justified. When you're using a program like TextEdit on a Mac, it has to be a plain text.

There are some one statement programs which are written in a language called ALGOL 68. It was aired in 1968 giving it the mane ALGOL 68. The other very renowned languages are Python and Lua. The important thing to note here is that though the statements in these languages are same but that doesn't mean that are identical. There are some languages which require a little more than one single statement to be considered as a full program. There are many other languages which are given explicit starting and ending points. An older version of ALGOL, ALGOL 60, was written in all caps and required the words BEGIN an END to mark out the program.

ALGOL 60

BEGIN

DISPLAY("Hello,world!");

END

Languages like C and other languages which are based on C like C#, C++ and Java requires curly braces and weird esoteric keywords.

C

#include<stdio.h>

int main(void)

{

print("Hello,world\n");

return 0;

}

C#

using System;

class Example

{

static void Main(string[] args)

{

Console.WriteLine("Hello, world!");

}

}

Java

public class HelloWorld

{

public static void main (String[] args)

{

System.out.println("Hello World!");

}

}

Text editor's are most widely used among programmers as it provides a user-friendly environment comprising of many features. Some of the typical features are line numbers, the most widely used Find and Replace. They often have color-coding. Remember that it is not the same as formatting. Color coding happens automatically and it helps you to read and recognize different parts of the language. They have syntax checking as well. This is very much similar to spell checking in a word processor. Syntax checking will help you out in rectifying if there's something wrong in the code that you've typed in. Sometimes these text editors are oriented towards a particular language only.

Integrated Development Environments or IDEs

An analysis on web development brings out that the chosen web development application is also a usable programmer's text editor. The very important term which comes out of this is the Integrated Development Environments or IDEs. These are large programs which include a good programmer's text editor but usually they are incorporated for professional development. Some examples of IDEs are Apple's Xcode on the Mac or Microsoft's Visual Studio or Eclipse which is a cross-platform. You are not needed to concentrate on IEDs at this particular stage; they are mostly used in specific area of development. At this particular stage you need to learn how to convert your coding into machine code so that it can run on the computer itself.

# Compiled and interpreted languages

Converting the source code into machine code requires two main things to be done: compiling the source code and interpreting the source code. Most languages you'll deal with will have many of the factors common but it is important know the differences as well.

Case incident: to analyze compiling and interpreting

Let's imagine a simple situation. You have your computer and I have my computer and you're going to write a program that you want me to run.

Keeping in view the usage of the compiled language, you're writing the source code. You have a program called a compiler that will go through that source code and create a separate file that contains the machine code. These files are sometimes referred to as executable files as you're utilizing them to execute the program. Now you gave me that file to run it on my computer. I'm unknown with the source code; it's safely kept with you. On the other hand, the other situation is with an interpreted language you don't compile the source code before sending a copy to me. My machine will be required to interpret the source code whenever I want to run your program.

One thing is clear that interpreter is different from a compiler. Interpreter will have to go through your source code line by line and processing it at the same instant. It does not save it as a separate machine code file. You might wonder that you've used interpreted languages even if you don't know it.

Web-pages with javascript

Now throwing some light on the web pages with Java script then you'll find that JavaScript has been sent to you over the web along with a bunch of other files like webpages and images. It is sent as source code onto your computer and your web browser will interpret that JavaScript so it can run that code. Now to decide which one is the best can be bit perplexing because their one half has good points and on the other half there are bad points as well.

Benefits of compiled code are as follows:

  * Once it is compiled, it is immediately ready to run and you can send it to 100 or 1,000 or 100,000 different people.

  * It can be optimized for a CPU. This makes it much faster to work.

  * You need not to send your source code to everybody, which might be a good thing.

Darker sides of the complied code are as follows:

  * If you've compiled it on a PC, the executable file won't work on a Mac. It is required to be compiled separately for different kinds of CPUs even when you're working on the same platform.

  * Every time you're writing the code; to compile is an extra step that you need to take to test your program.

Benefits of interpreted code are as follows:

  * You need not to care for the kind of machine because you don't have to provide machine code. Your work ends after sending the source code.

  * It is portable and flexible across platforms.

  * It is easier to work with. While testing it is just required to write the source code and then run it.

  * No worry about conversion of source code because that the load of the interpreter.

  * There is no in-between compile step.

  * It can be easier to debug because when things go wrong you always have access to all the source code.

Drawbacks of interpreted code which over-shadow the benefits:

  * Everyone who needs to run that program on their machine has to have an interpreter for that language on their machines.

  * It can be sometimes slower because you have to interpret it every time the program is required to run.

  * The source code is public because you're sending it to everyone who needs to run that program.

Just-in-time or JIT:

Analyzing the benefits of both the complied and interpreted language we can extract out the advantageous part from it. We've noticed that in the complied model all the work is done upfront but that's a bit inflexible. Secondly, switching over to the interpreted language, all the work is done on the receiving end but that is a little slower. Considering the upfront where we compile is called an intermediate language. This can be treated as machine code while still being portable across different platforms.

It can be sent to the people who need to run it. Each person who runs it takes it the last step from where it is taken to the machine code on their computers. This is sometimes referred to as Just-In-Time or JIT compilation. This intermediate language is also known by the name bytecode.

When to use complied or interpreted language?

According to theoretical analysis all computer languages can use any of these methods. C, C++ and Objective-C are found as compiled languages and they require a compiler. The compiler can be downloaded free of charge but they're mostly built into integrated development environment applications. Languages like PHP and JavaScript; in fact most of the languages with the word script at the end are usually interpreted. Renowned languages like Java, C#, VB.NET and Python make use of this intermediate hybrid approach.

It does not make much difference to know whether the language is compiled or interpreted but the thing to take into account is the language that they have chosen. If the priority of your program is absolute maximum speed running on one single platform then you'll probably switch over to a compiled language. On the other hand, if you're required to get your code accessed across multiple platforms then you should quickly move down to an interpreted one.

If you want to build iPhone apps or Windows desktop apps or some dynamic website, you need to firstly drive your attention towards the language choice and the after, the language choice will determine whether you are needed to be compiled or interpreted.

2

Introduction to variables and data types

# Case incident: importance of variables and data

As we begin writing a simple program in any programming language there are pieces of information which need to be taken into account. Suppose if you're preparing a loan calculator. You are required to keep a track of the amount of the loan, the number of months and the interest rate. Let's take another example. You're willing to write a program of some game then need to keep an account of the current score, the position of the player on the screen, how many levels to secure a good score, what image do we use for the player and many such factors hold a lot of importance while writing a program. These all factors falls under the category of data and we create variables to hold that data. In simple terms, you may consider variables are containers.

Whatever we try to perform or execute on the computer, it goes to the computer memory and occupies a part of it. A name has to be given to it while the program is running. This occupied space is given a name and then a value is stored into it. The stored value can be any fictitious thing like an email address or a date or a number and any valid data. This data can be changed whenever required. As variables can vary, thus it is named so. While programming it is needed to create a variable like this. The name of the variable is up to us but it advised that it should be relevant to the piece of data that it going to hold.

Take an example:

Let's consider a variable named year or let it be customerEmail or todaysdate. Many a times you'll notice non-relevant words as well; may be sometimes just a single letter like a. While we're creating a variable, we're carving out a small area of the computer's memory to hold a value.

int year;

long customerEmail; (letters)

double todaysdate; (numbers)

var x; ($)

Rules to be followed while naming a variable:

  * The name must be written as one word.

  * There are no spaces allowed in between the word.

  * It can be made of letters, numbers, the dollar sign and the underscore.

  * No other characters are allowed but it can't begin with a number.

Undefined variables:

Suppose you're writing a line of code for a variable to exist. Though it has a name 'year' but it doesn't have a value right now. Such variables are regarded as undefined and undefined variables have a special significance in programming. But there is no point in keeping a variable that stays undefined. Thus, we need to define or set the initial value of the variable at the time we create it. It can be done by two statements. Firstly, you need to declare the variable then after put or store some value to initialize the variable like year =2011.

var year;

year = 2011;

This statement puts the value in the variable or we can say we've initialized the variable. This is actually a command instructing to place the value 2011 in the variable called year. Both of these statements can also be combined into one statement; simply like defining or declaring the variable by creating it and at the same time initializing it to some value.

The' = 'sign sets the variable to the initialized value.

Importance of lowercase & uppercase characters:

There are some programming languages which are case sensitive. If you create a variable called x with a lowercase x this would be different from the other variable named as X with uppercase X. These are two different variables. But it might happen that the second was a mistake and you're unknown to it. Maybe you meant to say lowercase x, but because of the automatic creation of variables. You now have two different variables and nothing in programming would actually give you an error on this. You must be cautious while naming the variables. When you are creating multiple variables at the same time, you can of course do them on multiple lines. But it can also be combined onto one line by separating the variable names with commas.

x = 200;

X = 210;

Similarly if you're creating multiple variables and assigning them separate initial values; it still can be combined onto one line. This makes it easier to read and shorter to write. As a programmer, once you've created a specific variable you can store any value into it. It could be numbers, text or dates.

int year;

int month;

int day;

OR

int year, month, day;

OR

int year = 2011, month = 10, day = 31;

Data types:

Most of the programming languages have their own sets of principles to be followed while writing a program. While creating a variable, you don't just give it a name but it is also necessary to tell what type of information is going to be stored in that variable. It must be decided beforehand if you're going to store an integer which means a whole number having no value after the decimal point. It can also be a floating-point number which can have a value after the decimal point or may be just a single character. When you're storing multiple characters in a variable, it is called as a string. If it is a Boolean value then it can have a value that can be either true or false. Hence, it is important to define the data type before storing the value in the variable.

Strongly-typed language:

Once you have made a choice among various data types, it is not allowed to change it. This is known as a strongly typed language. Many variables can be created in a particular program but it is necessary that each variable must be of one particular data type. It can crash your program and produce many flaws if a wrong data type is stored in the variable that wasn't designed for it.

Weakly-typed language:

There are some weakly-typed languages as well. It is only required to create variables for integers and strings. We just create a generic variable or you can say an empty container. It can be simply used to put any type of value. If you create this variable without assigning it any value then it would starts off as an undefined variable. However, you can use the name of the variable and an assignment operator to set the value of x = 200.

x = 200;

x = "Hello World";

x = 'Hello World';

x = True;

Usage of double quotes:

The undefined variable can also be set to a string. This simply implies that more than one character strung together. It is necessary to put the string into double quotes. It can contain spaces and special characters inside the double characters. Opening with a single quote and closing with a double quote is not allowed. But double quotes are preferred more because that is mostly used in programming languages.

Many of the programming languages make use of either single or double quotes to mark the start and the end of a string.

Boolean values can also be stored which says either true or false. The word true or false does not need the quotes around them. They are considered as a part of the language. Thus, an undefined variable can be stored with a number or a string or a Boolean value.

Weakly-typed languages are easier to work with because they are user-friendly and give a liberty to put anything anywhere. The only problem with weakly-typed language is that there is no guarantee whether the variable declared contains the right kind of data. Many-a-times while programming, there is no need to change the type of data that a variable stores.

Take an example:

If a variable is defined as high-score then it is understood that it would contain a number in it and not the word apple or the value true. Another example can be a variable called firstName then it is itself implicated that it should be a word and cannot contain the value say 25.8. The advantageous factor working with strongly-typed language is that internal rules shun a lot of common errors from occurring.

Conclusion:

The analysis of the above examples made one thing clear that before making use of any variable, it is important to know to write them.

# Working with numbers

Backdrop of numbers in computer:

While working with variables there are two things to take an account of: the variable or the container and the different values that are going to store in it. The most common kind of values in computer programs is numeric values. The word computer is associated with a machine. Dwelling into hundreds of years ago computer was a job. In the 17th, 18th and 19th centuries we could be employed as a computer. It just meant a person who computes or does calculations. Then came the ages of machines and it yield far better results than the person ever could. Whenever the word computer strikes to our mind; instantly we think of hardware. The root cause which led to the invention of computers was the arithmetic calculations on numbers.

The representation of the numbers can be seen in almost every task we do in our daily lives. Such as dealing with bank balances in dollars and cents, the position of a spaceship on the screen, the height and width of a web browser window, the coordinates of a device using geo-location, the amount of milliseconds an MP3 song has been played. Even colors are represented with numeric ranges of red, yellow and green.

Significance of numbers:

You need to be very conscious of what type of number you're using: integer floating-point, positive or negative. Let initialize the variable x to the number 5. If you're new to programming, lines like x = 5 can look queer to you because may be the last time you have seen this was equations in school studies. But you need to mark out a point here that the equals sign here is just not a description but a command. It simply depicts that place the value 5 in the variable called x. It does not matter what it contained earlier but after execution of this line, 5 gets stored into the variable x. This is what the equals sign does. It assigns a value and so it is known by the name assignment operator. You must have noticed that there are no quotes around the number 5. The number 5 is referred to as a numeric literal. It represents the fixed value 5. The variable part of this line can change as our program runs, but the literal does not. 5 have a same meaning every time. If you want to change the number by a ten thousand then you can easily do this. But make sure you do not put any commas in it. Such as x=1000000. Just make use of the number itself. Numbers are regarded as positive by default though they can be negative as well.

X = 5;

X = 1000000;

Usage of characters and strings:

While programming when we come across text, characters, words, sentences or email addresses. It requires strings to describe those kinds of values. Some description regarding strings has been already given in the above illustrations. Whenever we see words enclosed in sets of quotes without much stress we can easily make out that it deals with strings. This format can be used to create variables. Consider a variable called x and set it equal to the words "Hello, world".

We know that while placing strings in your statements, double-quotes are used to enclose the text or the sentence. On the other hand, single quotes can also be used. But both of them cannot be used at the same time. The situation when you require both of the formats can arise when quotes inside quotes are to be placed.

Case incident: 1 (Analysis on double and single quotes)

Let's imagine that you're needed to put a phrase as a string. Again you have to make sure that it doesn't get hazy in identifying the string quotes and phrase quotes. If you use single-quotes to mark out the opening and the closing of the string then it could face a problem. We can notice that there's a single quote in the middle of it. This might pose a problem in understanding where the string gets open and closed.

X = "Hello World";

X = 'Hello World';

X = 'Hello World"; (error)

Conclusion:

The solution which can be employed here is to use double-quotes along with a single-quote contained inside them. This would be perfectly fine. Nevertheless, it may get a bit difficult when we're dealing with more complex sentences.

Case incident: 2 (Analysis on double and single quotes)

You've another phrase which comprises of both double quotes and single quotes. There is no easier way to mark out the beginning and the end of the string without some introducing some special character. It will be required to escape the quotes. This can be one way in finding out the solution of it as per requirement. The entire string begins and ends with double quotes. To have the double quotes inside the same string, a backslash would be needed to place before the double quotes to be used inside the body of the string itself.

X = "Don't mix your quotes";

X = "He said \"that's fine,\" and left.";

Conclusion:

Strings can considered as the holding place for some characters. We can put questions inside the strings as well. It can be even converted to either upper or lowercase. One thing to always remember is while defining the name of the variable; it is suggested to define it in such a way so that it reflects the information inside the string. Variables give us a lot of information about the contents and regarding what they're holding.

# Analysis on arithmetic operators in programming

You might have studied about the symbols like equals to in your primary classes. Such symbols are equally important in programming language as are words because it makes things to occur. When we want to place a value 500 into a variable, it can be done with the help of equals to operator and is commonly known as assignment operator. The variable takes the literal value i.e. 500.

balance=500;

Let's find out few more such operators which are widely used. Most common among all is arithmetic operators such as addition, subtraction, multiplication and division. Asterisk is used for multiplication and the forward slash is used for division. Many a times, they are used in combinations as well giving it a special meaning. Considering an example of a variable a = 100. Whereas variable b is set to 50. We can make use of the plus sign on the right-hand side of the assignment operator to perform an addition operation. Adding up the two values in two different variables and saving the result in a new variable called result. The result comes out to be 150.

a = 100;

b = 50;

var result = a+b;

The plus operator could be changed to a minus sign and perform subtraction operation. In the same manner, we can easily apply asterisk for multiplication and the forward slash for division. The significance of assignment operator is that it assigns the value present at theleft-hand side of the equals to sign to the variable at the right-hand side. Multiple operators can be used together butsome of theoperator symbols are treated to be more important than others.

Combinations of different operators:

Suppose you have two values in two different variables. Applying addition operation makes it 5+5 i.e. 10 and the multiplication operation would make it 10*10 i.e. 100. But if the operators are applied in different positions it can yield very different results. If both the operations are employed simultaneously then again the result would come out to be different as multiplication holds a higher priority and would be performed earlier than addition.

Now suppose if there are same variable names on both sides of the equals sign then the current value of score would be taken into consideration. Later on, the result would be stored in the variable score. If the score is 100, it will now turn out to be 110. This idea to add a value to an existing variable rather than creating a new variable is very common and so there is a shorthand for it which is +=. Score += 10 implies that whatever the value of the score variable is; add 10 to it. Here the \+ and the = have to be written as one.There is no space in between them. This is considered as one operator. Similarly, we have -=, *= and a /= for subtracting a value or multiplying a value or dividing a value respectively.

If we need to just add 1 to an existing variable, then we could evaluate it either by writing a = a + 1 or by using a shorthand a += 1. But the usage of an increment by 1 to a variable is so common that it build up its own shorthand which is ++.a++ implies add 1 to the variable a. This is how the language C++ got its name from. It's the impression of C+1 depicts the next version of C. Falling on to the other sides, the same idea we utilised while subtracting 1 from a variable by writing it long hand as a = a - 1 and later on build up a short-hand for it as a -= 1 or just a--. The ++ is called the increment operator whereas, -- is called the decrement operator. Thus, it is clear that these symbols have equal importance within a programming language as the words themselves.

a = a + 1; a = a - 1;

a += 1; a -= 1;

a++; a--;

# Whitespaces in programming

Most of the modern programming languages do not get affected by whitespace. Whitespace are simply spaces or tabs or line breaks. These are considered as insignificant and can be avoided. It does not matter if the line breaks are placed in between the lines whether at the start, at the end or in the middle. It does not hamper the result if you decide to put some tabs or few spaces before staring the statement. The whitespaces are ignored and the characters are being read. The ignorance of whitespaces is possible because of semicolon which implicates the end of the statement in programming.

Usage of whitespaces:

Whitespaces are useful when multiple statements are combined onto one line. It does not pose any problem writing it this way. But it is suggested to make use of one statement for one line. In fact, the whitespaces are avoided inside the statements. You can put multiple spaces between different elements of same statement. It is advisable not to create a mess out of it by using multiple statements or multiple spaces in the same line.

While writing in C-based languages, the programmer intends to immediately close with the semicolon as soon as possible. It is similar to the way we use the period at the end of a sentence in English. You may use white spaces for readability. Using too many elements in the same statement can be hazy to read. Whitespaces are used to clear it out.

Whitespaces in operators:

There are few customs that you may run into. Let's suppose we're using the ++ operator. There are two places where whitespaces does matter. Firstly, while making use of an operator that has multiple characters like the ++ operator. You can put a space between the variable name and the ++ and the other way is you may put a space between the ++ and the closing semicolon. You cannot put a space in between the two. Don't get confused; this is not two addition operators. It is one ++ operator which is also called as the increment operator. It has an ability to add one to a variable. There's no space in the middle of that. Similarly, the same thing goes for operators like --, += or -=.

a = 5;

b = 10;

c = 20;

x = true;

z = false;

a++;

b--;

c+= 10;

Whitespaces in strings:

Secondly, whitespaces matter a lot inside a string. Whitespaces are placed between the words that are there in the string. Whitespaces will hold a lot of importance when you're required to make a line break inside a string. But you can't just simply place a whitespace to split up in two lines because in the end you're winding up the entire statement with a semicolon. The only solution to make this happen is to make use of backslash. This backslash is sometimes referred to as escape character. Those special charters are \n; this simply implies a new line and used as a string literal.

print("What is your name?")

print("What is n\your name?")

# Adding comments to code for human understanding

After writing sufficient number of lines in programming, you can add comments to your code. These comments will remind your code lines actually implicate. Even after accessing the codes a six months or may be year later these comments would remind you significance of each line of your codes.

Representation of comments:

They can be easily applied by simply writing a line that begins with two forward slashes. Anything after these two forward slashes is avoided making it a single line comment. Soon after leaving that line the comment is over and the rest of the code is unaffected. The other way of applying the two backslashes is after the existing line. But is mostly advisable to place it before the code it is meant to be applying for.

// This is a comment

Sometimes a blank line is also observed before the comment because it makes it more visible. Multi-line comments can also be created. Despite of using multiple lines with two forward slashes, the other way is to use a /* when beginning a comment and ends up after the appearance of */. Multiple lines of comments are mostly used for large lumps of coding. Though often two backslashes are used for commenting but some programming languages have their own syntax of writing comments for codes. Thus, it is always advisable to check out the syntax of the particular programming language you're writing the code in.

3

Basic elements of Programming

# Introduction of 'if' statement

At the time programming we might want to introduce some conditions to execute the program. Till now we were writing the statements in the program whose each line is being executed one after other. The speed of executing the program depends on the how fast the computer switch over to the next line to execute it. There might arise a situation where the program pauses prompting for information from the user. After seeking the information it again goes to the top line executing till the last line. The whole procedure seems to be very time consuming or complete wastage of time. To overcome this difficulty and willing to save the execution time, it requires having a special type of coding.

Take an example:

Let's imagine you're writing a bank balance program. But during programming there are few questions which need to be a part of your programming. If the bank balance is positive, calculate interest. If it comes out to be negative, charge a penalty. The other condition could be: if they check the checkbox on the form, add them to the mailing list and if they haven't then don't. There can be many other conditions like if the position of the missile image is exactly similar to the position of the spaceship image, then flaunt the explosion image.

There is a need of such a programming which deals with the conditions as well as a part of the code while executing. In other way round it can be said that a code that sometimes runs and sometimes doesn't with respect to the conditions of the program at that time. Such a code is conditional code. And so, we introduced if statement which exist in every programming language.

Building the 'if' statement:

The 'if' statement is written in almost every programming language. The general format is the condition declared in the parentheses i.e. the round brackets is found to be true, and then execute the code written in between the opening and closing curly braces.

The word 'if' is used in the statement to declare the conditions. Along with the word 'if', there is a pair of parentheses comprising of an opening and closing round bracket which contains the condition part to be followed. Then after, an opening and closing curly brace which contains the code part to be executed.

If you're new to programming then you need to bear in mind that in programming languages, the symbols used are very specific and holds a special and different meaning. For example parentheses indicate simple round brackets and braces indicate curly braces.

if ( )

{

// your conditional code goes here

// ...}

Remember few things:

  * You need to be very cognizant enough when to apply opening and closing braces.

  * They are not interchangeable.

  * Parentheses, brackets, or braces are always found in pairs, unlike semicolon or equal sign.

  * Once you've begun with the opening braces, it needs to be closed as well. Sometimes we forget to close it. It can be several lines later, but it needs to be there.

Usage of 'if' statement:

As we know the parentheses are used to write the condition that we need to specify. The curly braces are used to mark out the execution part if the condition turned out to be true. The code in the curly braces can be one statement or a dozen or may be more than that. Coming on to the condition part, we don't use the word condition. Suppose if the condition is if a is less than 100. You can understand it by taking it as a question. It is required to check if 'a' which must be holding some numeric value is less than 100 or not. If it comes out to be lesser, then we'll move into the curly braces part. The code part inside these parentheses can be sometimes evaluated on finding the condition true or can be fritter away on finding the condition false. The thing to notice here is we are looking for whether 'a' is 20 or 30 or 50; we're just finding out whether the condition is true or false. the break down, as being either true or false.

Let's imagine a condition where you want to check out the equality. Checking out whether something is equal to something else, we cannot use the single equals sign. It will be required to use double equals sign having no spaces in between. This is known as comparison operator. The condition can be whether 'c' is equal to 999. Again we're just focused in finding out if the condition comes out to be true or false. This comparison operator is used many renowned languages like C, C++, C#, Java, JavaScript and many others. Don't get perplexed with the single equals sign which is known as assignment operator. Both have very different meaning. Assignment operator is used as a command. It sets a value, not checks a value.

The condition to check inequality simply means something is not equal to something else. This can be written as != . This is one operator. Let's see the usage of it with the help of an example. The condition to check out is if 'd' is not equal to 100. We're looking for whether it is true or is that false. On finding it to be true we move on to the code block. It is grouping a section of code together and executes after finding the condition to be true. Code blocks can also be nested inside each other if it is required. It seems like the code inside a code block is indented.

# Working with complex conditions

Let's begin with creating a condition and then adding some more thought to it. We've created a variable called balance and settled its value equal to 2000. Let's apply 'if' statement to it. The condition to be applied is if balance is greater than 0. Now we can easily see that it is greater than 0. Of course, code block will also be required quickly jumping to the opening curly brace and then running down through a couple of lines to the closing curly brace. In the end, the code part prints that balance is positive on finding the condition true.

Complex conditions simply imply more than one condition together.

Introducing 'else' statement:

There can be a situation where the condition comes out to be false. Using another 'if' statement is not the solution. The solution is to add the word 'else'. It will also make use of the opening and closing curly brace for the code block. This is the second code block.

There is a very important point to be noticed. If the condition comes out to be true i.e. greater than zero gives us the output as balance is positive. But think about when it is equal to 0. It will give us the output as the balance is negative. There might arise some problem with this because we haven't specified any condition regarding this. Computer only does what we have specified in the code. It has no understanding or assuming things of its own. In the case of equal to 0, we need to introduce another condition. Such problems arise when we dealing with positive and negative numbers. It is advised to be as exclusive as possible about what you're checking against. The condition should be if the balance is greater than or equal to 0. As zero is not considered as negative so, the output will come out as the balance is positive. You can also make use of an operator >=. This is regarded as a single operator.

More conditions like if balance is greater than 10000; can also added by introducing another 'if' statement and making it more complex.

balance = 5000;

if (balance > 0 )

{

print ("balance is positive");

}

else

{

print ("the balance is negative ");

}

Setting comparison operators:

To understand the usage of comparison operators let's example. We're writing code by using 'if' statements and want to check whether one variable is equal to another variable. The comparison operator is written as the double equals sign, also called as the equality operator. According to case, we'll check if the contents of the variable 'a' are equal to the contents of the variable 'b'. If it is found out to be equal then the execution of the statements present inside the opening and closing curly braces i.e. the code block would be executed. The thing to mark out and remember forever is the comparison operator is double equals sign and not the single assignment operator.

if (a == b) {

// execute this code

}

Analysis of comparison operators using two variables:

We have a couple of variables. Variable 'a' is set to 5 and variable 'b' is set to 10 using the single equals sign to assign the values of these variables. Now we're introducing 'if' statement checking out whether the variable 'a' is equal to variable 'b'. Unknowingly, if we have written single equals sign instead of double then it will give flaws in the result. It will set the value of 'a' variable to the value of the variable 'b'. The result would be a=10. The result will come out, even though it is not the desired one because the computer only understands the code written. The error doesn't spurt up because it is perfectly legal syntax. To produce the desired result, it is required to use the double equals sign.

a = 5;

b = 10;

if ( a = b ) {

//always true!

}

In JavaScript and a couple of other languages like PHP, the equality operator is represented as the three equals sign or triple equals sign. This is also called as strict equality operator.

= assignment

== equality

=== strict equality

# Introduction to the 'switch' statement

You're now pretty much clear about writing and usage of 'if' statement. But there arises a specific situation where it's not the only option for checking out a condition. Let's take an example to have a closure look at it. It is required to check a variable for a selection of very specific values. We create a variable called grade. The condition is to check out whether it is Premium or Regular or Diesel. We can make use of separate self-contained if statements or combining it with else statements altogether. But this will make your program too lengthy. And when you have more than say five options to switch over the, it will even lengthier. To overcome this situation, most of the languages have a special statement called the switch statement. It has a very readable format.

grade = "Premium";

if (grade === "Regular") {

print("this is this")

}

if (grade === "Premium") {

print("this is that")

}

if (grade === "Diesel") {

print("this is Something")

}

In other languages, switch statement is called the select or select case statement. It has the ability of listing several situations or cases in one place.

Format of 'switch' statement:

Now employ the same example mentioned above using switch statement. It is required to check if the variable named day is Monday, Tuesday or Wednesday. It has a similar format to that of the 'if' statement. As in the 'if' statement we made use of the word 'if' along opening and closing parentheses for the condition and the opening and closing curly braces for the code block. In case of switch statement, we'll make use of the word 'switch' (all lowercase). You should know what the switch is looking for. In this particular case, it is the variable day. You need to put 'day' inside the parentheses. Neither it is greater nor is it lesser than something. It implies that we're looking for the variable called grade. The code block inside the body of the switch statement describes the different situations or the different cases that we're looking for as per the requirement of our program. The format goes like: Use the word case and describe the first option. In this case, the day is equal to Monday. Following this, in the similar manner describe other cases. There is no need to use equals sign or the double equals sign because we already know about the variable that we're looking at i.e. grade.

grade = "Premium";

switch (grade)

Write "Premium" followed by a colon. Then after you need to describe what has to be done after the selection of the particular case. If you're checking out a variable that contains a string then the double-quotes will be required. On the other hand, if you're checking a variable that is a number then cases would be like: case 1, case 2 and case 3 without putting them in double-quotes.

grade = "Premium";

switch ( grade ) {

case "Regular":

print("this is this");

break;

case "Premium":

print("this is that");

break;

case "Diesel":

print("this is something");

break;

default:

}

Make sure you do not get confused with the semicolon; we are using colon here and not semicolon. As this format is quite readable, it becomes easy to scan and figure out what we're actually looking for and what has to be done then after.

Benefits of 'switch' statement:

The major benefit of using the switch statement is that we can finish off the program easily. There can be a situation when no option is matched among the cases mentioned. The word 'default' can be used when no case is found. This is not in double-quotes. Do not get confused we're not checking the variable for the default value.

Going through each of the statements describing cases, let's suppose we're looking for the variable day which is equal to Tuesday. Moving on to the first case, we came across Monday which is not the right match. Next, we move down to the second case and we got the match. It's Tuesday. This will indicate an alert sign. But because of the format set in the switch statement called fall-through will immediately jump down and find the next statement to be executed. To prevent fall-through in our cases we'll add the word 'break'. This implies that we're done with this case. So at the end before the next case we write 'break'.

Break keyword simply indicates to jump out of the particular switch statement. It is not required to put the break keyword after the default statement because it will by default set to jump out of the program.

4

Breaking the code apart

# Introduction to functions:

Addition of more and more code makes the program quite messy, harder to read and harder to follow. Most of the programming languages break apart the large amounts of code into smaller, reusable and modular pieces. These are turned into smaller programs and have different names in different programming languages. They are called modules or subroutines or subprograms or may be sometimes as just routines or methods. There are few programming languages which call them as functions.

A function is simply the idea of extracting out a block of code from a large chunk of program. These subroutines or functions can be of one line or five line or even more than that. It is a block of code wrapped up together and given a name. These functions can be called later in any program and treated as the one single function. These functions follow the verb-noun format such as calculateArea, createMessage and animateImage. All of these functions encapsulates a block of code, no matter even if it is just a single line and performs a specific task. These functions can be called anytime in any program.

Functions are small programs comprising of a block of data extracted out from large chunks of code of a program specifying a particular task to be performed.

Format of functions:

The code is created surrounded by the curly braces depicting where the function starts and ends. The code written in the block is called the body of the function. Collectively they can be called as functions but since there are numerous such functions, it is required to give them a unique name. As was the case in variables, giving names to the functions is up to us. Few examples of functions are createMessage, hideMenu and there are many more. For easy understanding you may consider it as myFunction.

After naming the function, the opening and closing parentheses are required. If there is some data or parameters or arguments to be passed into the function; then it is placed inside these parentheses. Empty parentheses simply imply that there are no such parameters or arguments to be passed. It can be called in a program by using the name of the function followed by the empty parentheses and a semicolon. This is how the body of the function is called and all the code inside it is executed. There is no bondage on using the function more than once in a particular program. It can be called many a times.

Functions in programming:

The important thing to remember is once you've created a function it won't be called automatically. It will be required to call it. If you have one or more functions in many programming languages it doesn't make any difference officially where the function was written. It can be written in any order. It is required to call the function and then define it. That is why almost all programming languages quickly scan the code and figure out the function existing behind that code before it tries to run or execute it. It is important to define the functions before calling any of them. Define all the functions up at the top of the code file. This is considered as one of the rules to be followed while programming.

function ( ) {

print ("This code is inside the function");

// loops, if statements, anything!

//....

}

//sometime later

myFunction ( );

myFunction ( );

myFunction ( );

Either termed as functions, modules, subroutines or methods are callable units inside a larger program and comprising of small block of code is a core feature of all programming languages. This makes the programs easier to write and understand. Also much of the memory and time is saved. You can understand it by comparing with a live example where different programmers are given different parts to write and thus splitting the work making more organized and less complex. There are some complex functions as well. They not just perform an operation but also return values or can also accept data.

myFunction ( );

function myFunction ( ) {

// lots of code

myOtherFunction();

}

function myOtherFunction ( ) {

// lots of code

}

# Understanding variable scope

There is another important thing to be taken care of while working with functions in most modern programming languages. Let's imagine we've created a function and defined a variable inside that function. This variable only exists inside that function. This has led to the introduction of variable scope. Every variable has a scope. This depicts the location or the visibility of the variable. After jumping into the function, we'll create the variable 'x' and print the contents of that variable, let's say it 500. Now after coming out of the function if we try to print up the content of x again, it's not going to show any result. This is regarded as undefined. It is unknown to the x variable because x variable does not exist outside that simple function.

Variables declared inside the functions are referred to as local variables. They have local scope and are only available within the opening and closing curly braces of that function.

There is a keyword which helps out if we are required to make the contents or the local variables visible outside that function. The value can be returned by using the Return keyword. Another way to access the local variables of a function is to again declare and create the variable outside the function. The variable x created outside all the functions is referred to as a global variable.

Global variable is that variable which can be used anywhere, anytime regardless of whether inside function or outside the function.

The thing to keep in mind is not to use the word 'x' to declare the variable again. Inside that simple function where we initialized the variable 'x' to 500; if we called the variable inside the function it would be x=500. And outside the function it would be 500 as well. You need to be cautious about where the variables are defined.

x ; (global variable )

function simpleFunction () {

// lots of code

x = 500; (local variable )

// lots of code

print (x) ;

}

simpleFunction () ;

print (x) ;

# Splitting the code into different files

Many a times, we must have seen hundreds or thousands of lines of code in programming. Even though we can split the numerous lines of code into functions, still sometimes it gets difficult to read and navigate through the code. There one more way to make lengthy code more manageable. Despite of keeping the entire code into one file, it can be further split up into several files. This is employed in every programming language. Of course, it cannot be used anywhere randomly. It cannot be done like keeping half a function in one file and half in the other. Several functions can be grouped together in one file and several more in another. This makes it easier for multiple people to work on the same project by working on separate files.

You might come across some complex applications built by software developers where they might have hundreds or thousands of separate code files for one project. There's nothing unusual in that.

5

Introduction to Iteration

# What is Iteration?

Iteration can be treated as the programming catchphrase for a loop. Let's find out the idea lying behind it. You begin writing some code. You want to introduce some statements in your code implicating to look into all the MP3 files in a folder and changing the position of an image on the screen. It is required to write some statements to let it happen simultaneously. Now suppose you are needed to repeat it. Probably you might think of writing it again and again as per the need. But all this will turn out to be quite tiresome if imagine you need to repeat it several hundred times. This led to the introduction of such a function wherein we write the statements once and then just say "Repeat this". Repetition can occur any number of times or it can be set to repeat until told to stop or can be told to go through all the fields on a web page. Thus, repetition of the statements is up to us.

Repetition of the particular statements can be done by creating loops and this procedure came to be known as iteration. Creating loops is very easy. The important thing to be taken care of is not when to begin any loop but when to stop. The loop can be prolonged to even 5,000 times or can be until told to stop; it has to have something to keep a track of it. Therefore, all the loops will have conditions that control how long the loop should proceed.

Usage of Iteration:

Most of the languages follow the same format in programming. We've seen in the 'if' statement if the condition turned out to be true, execute the code in the block. Let's take an example. There is a variable a = 1. The condition is if a < 10 then print up value of 'a'. Undoubtedly we can make use of the 'if' statement here. The way could be simply replacing the word 'if' by 'while' and this gives us a loop. This implies while this condition is true, execute the body of this code rather than if this condition is true. Regardless of how many lines of code is there in the body of the loop, it gets executed for each iteration. Every time the loop goes around the code would be executed.

Infinite loop:

When variable is set to 1, the value gets stored in memory. Then after we move down to the while just like it was there in the 'if' statement. According to this particular case, it evaluates as true. As 'a' is less than 10; we quickly jump into the body of the loop inside the curly braces and executes the code out there. Here, it is just popping up an alert. When we move down to the end of the loop, it is marked by the closing curly brace. The control again goes back to the start of the loop and checks the condition again. This happens automatically until a < 10.

Problem with infinite loop:

But there can arise a problem if the value of isn't changed then it will keep on revolving making it an infinite loop. Infinite loop is not advisable as it makes us stuck in the loop forever. At that time the only option would be either turn off the computer or force the program to terminate. It will be required to keep track on how many times we want the loop to be repeated. It is required to add a line to increment the variable 'a'. If we make use of an increment operator such as a++ and making it a part of the code; again we get into the loop and check for the same condition. It prints the value on finding the condition true or executes whatever code is there. If we write a++ just before the body of the loop closes, it will keep incrementing the value of 'a' by one.

The value of 'a' will be now 2. This is how the loop will keep going, incrementing the value of 'a' and checking out the condition. At some point the value of 'a' will reach 10. Checking it out we'll find out that it is not less than 10. As the condition comes out to be false, we'll quickly jump out of the loop without executing any of that code.

# Introduction of 'for' loop

The while loop is often used in C- based languages. After going through many of the while loops, it was realized that a pattern begins to emerge by it. Many times more or less we deal with the same elements. Despite of the number of lines written inside the code block, we need to set an index to keep the track of the loop. The same is applied outside the loop as well. The condition is needed to be checked every time with the increment of the index inside the loop. The increment operator is written just before the closing curly brace of the code block.

Format of 'for' loop:

There are three important things to bear in mind for a successful loop. It is almost common to the format of 'if' and 'while' statement. That is why it is also known as 'for' statement.

Three important things:

  * The word 'for' is used similar to the format of 'if' statement.

  * Just after the word 'for' follows the opening and closing parentheses.

  * The opening and closing curly braces containing the code.

  * There is a section that sets up the index, the section that checks the condition and the section that increment the index. These three parts are separated by two semicolons.

Take an example:

Firstly, we begin the loop by creating a variable 'i'. It is set to 1. The first time we hit this loop we'll create a variable called i, set it equal to 1 and check to find out whether it is less than 10 or not. As we can easily figure out that the condition is true so we will jump into the loop. All the line of code in the loop is executed. Just before the closing curly brace we'll increment the index. This will check the condition again and keeps on looping until that condition turns out to be false.

for ( i = 1 ; i < 10 ; i++ ) {

// do stuff

// do stuff

// do stuff

i++;

}

The benefit of it is that it makes the things go in an organized and readable format. Everything about the loop is written at the top. It is not needed to look outside the loop for finding the index being set up nor is it needed to scan inside the loop for the increment of the index to make sure if it's in the right place or not. It's quite clear and to the point way of setting up a loop. Such type of coding is very common and frequently used online and in books as well. 'while' and for loops are often used in most of the manual looping. These are same across all C-based languages.

Other loops in programming:

Other than 'while' and 'for' loop, the other loops which are used in programming are 'do' or 'do'/'while' statement. The basic difference between these and the 'while' loop is that in the 'do'/'while' loop the condition is moved to the end of the block. The format of 'do'/'while' is completely different. It doesn't match to the formats we've seen yet. But the elements are still in the same place.

Take an example:

Let's set up an index a = 1. We're using keyword 'do'. The code will be written in the opening and closing braces just after 'do' keyword. The code block also contains the increment operator of a++. But the condition that we're going to check is at the end in the 'while' loop i.e. a < 10.

a = 1;

while (a < 10 ) {

print(a);

a++;

}

Same as in 'while' statement we need a semicolon at the end of the 'do'/'while' statement. The contrary part between the two is that whatever is there in the code block will be executed once before we have gone through the condition. Even if the condition was false when 'a' started off at 100; the code in the block would be executed before the condition is checked.

Mostly 'while' and 'for' loops are much more common than 'do'/'while' loops. It requires checking the condition before entering the loop. This makes it more readable to have the condition at the top of the loop than at the bottom.

6

Introduction to string concatenation

# Usage of string in programming:

Many programming languages are weakly typed language. They can store any type of value without caring about the pre declared datatypes such as string and Boolean. The programming languages rectify the difference and treat these values differently.

Take an example:

Let's take an example to understand the difference. There are two variables named as foo and bar. Suppose the variable day is initialized to5 and amount is initialized to 5 without double quotes. These are numeric values. If you want to print the result after adding them up, you'll make use of addition operator. The outcome will be 10.

foo = 5 ;

bar = 5 ;

print ( foo + bar ); // 10

foo = "5" ;

bar = "5" ;

print ( foo + bar ); // 55

Conclusion:

The important thing to mark out here is the values stored in the variables were numeric values which were easily understood by the addition operator. It adds them together.

Take another example:

If on the other hand, there are again two variables created with the same name as before. This time the value stored in the variables is 5 and 5, but inside double quotes as a string. Now you again apply the addition operator to add them up.

foo = 5 ;

bar = "5" ;

print ( foo + bar ); // 55 \- one is a string

foo = 5 ;

bar = "b" ;

print ( foo * bar ); // NaN

Conclusion:

This time the result would be different. The result would be concatenation and not addition. It will put the two together i.e. beside each other and give the output as 55. Such a result is the behaviour of the concatenation of string. Even though the value stored was numeric, but due to the double quotes it was treated as string and not a numeric value.

Analyzing a case incident:

You're working with area codes and phone numbers. You don't want to show them in a manner where those will get added to each other and becomes a different number. You want them to be concatenated one beside the other. It can get confusing if they are placed just beside each other because you cannot identify the area code and the phone numbers. Now think if one variable is a string and the other variable is numeric. Of course, the string will take charge and concatenation will occur.

You might face few situations where you try to store such values in the variables that just do not make sense. There are two variables boxes=5 and we create other variable packets equal to the letter A. We try to print boxes times packets and then boxes multiplied by packets. Concatenation it doesn't work here. The result might come out as five times A i.e. A then A then A till five times. Such a result may be or may be sensible that you were expecting.

# Finding patterns in strings

We have already studied about strings in programming. Programming languages are designed in such a way that their behaviour reflects their characteristics and features.

Understanding global property and methods in string:

Let's imagine you have created a variable named phrase and gave it a simple value. We'll make use of global property to access all the information out there in the variable.

phrase = "This is a simple phrase.";

print( phrase. length );

The name of the variable followed with a dot can access certain built-in information about that variable. Such a dot length property is called as global property.

Let's get a bit deeper to have a closure look. Suppose you're working with a string that also has the same behaviour and we can make use of the same dot operator to access its data. Strings also have methods which are commonly known as functions. We've already studied about functions which are called by using parentheses. Methods are almost similar to functions that belong to a string.

Again create a variable called phrase and use the dot operator phrase dot to access all the built-in methods like UpperCase. Just like a function it can be called by using the parentheses. As a result, the string will get converted to uppercase. Similarly there are many such behaviour that string has. These characteristics or behaviour of the strings are changed from one programming language to other. Strings are quite powerful and have various built-in behaviours like converting to uppercase or converting to lowercase. This allows us to certain pieces of methods within them. The thing to understand about strings is that they are a bit complex than numbers because we can have strings using different cases.

phrase = "This is a simple phrase.";

print( phrase. toUpperCase() );

Analyzing different cases of string:

Case 1:

Create two variables. One of the variables contains the word "Hello" with an uppercase H and the other variable containing the word "hello" with a lowercase h. Now find out if they are equal to each other. Of course, they are not because uppercase H and lowercase h cannot be treated the same way.

Case 2:

Suppose you have no consideration about whether it is uppercase or lowercase and want to have a case insensitive comparison. You just want to find out if it contains the same word. You cannot check it in a very simple way. You need to make use of the methods of strings to do the comparison between the two. It is required to convert both the strings to the same case and then do the comparison. What you actually have to do is like: convert str1 toLowerCase and str2 toLowerCase and now ask whether they are equal. The outcome now will be like: Yes, they are equal. Such abilities of the string help us to perform many such tasks as per our need.

str1 = "hello";

str2 = "hello";

// str1 != str2

if ( str1.toLowerCase( ) == str2.toLowerCase( ) ) {

print ("Yes, equal");

}

Case 3:

We can also find certain words that exist inside the strings. This is often employed in strings. Let's again create a variable called sentence and use the indexOf method of the string. Now make use of the same dot operator and then indexOf. You can clearly see that it is a lowercase 'I' and an uppercase 'O'. Let's pass another string into it. In this case, word is Elegant. You want to know the index of elegant in the string. This actually means that if the word Elegant exists in the string where it begins from. Now the output will be like if that word exists in the first string, it will return the position of the word and that's zero based.

The first letter of the string which is the uppercase W and will be positioned 0. Elegant will begin at position 10. If that word is not found in the string, it will return -1. Taking another example if the certain phrase or word did not exist, you could call sentence. If passing in a DDDD and then applying indexOf method. We know that does not occur. If the result is -1, you could print a statement that says, 'No, this word does not exist in the string.

pharse = "we want a groovy keyword.";

postion = phrase.indexOf("groovy"); // 10

// it returns -1 if the term is not found

if ( phrase.indexOf("DDDD") == -1) {

print("That word does not occur.");

} // there is also .lastIndexOf ( )

Other possible cases:

There are dozens of ways that you can combine these different kinds of operations to find out if the word exists in a string. There is a method called lastIndexOf. Dot lastindexOf gives the last position of the word in a string. Whereas, dot indexOf gives the first occurrence of the word in the larger string. If you're working with larger amounts of text, you can also break a string apart. There are several methods to do this. One way to do this is to use slice method. Create a variable called phrase and give it some basic text. Next, create another new variable called segment which is based on the part of phrase. Use phrase dot slice and slice expects two arguments. In this particular case, pass in 6,11. There is a significance of this numeric value. The first number is the position that we are going to start at in the phrase. It starts from 0. Therefore, it becomes 0123456. 6 is the position we're going to start and 11 would be the position we are going to stop.

pharse = "Yet another phrase.";

segment = phrase.slice(6,11);

Ultimately, we are getting 6, 7, 8, 9, 10. This is how we can extract out those letters and store that result in the second variable. It can be simply visualized as pulling out a section out of another string. There are other methods like dot substring() or dot substr(). It's one and the same thing. It gives us a couple of other options as well. Other than slice, there are other options as well to perform this task.

This can be seen in all modern programming languages. Other than comparison and equality check; it can be used for greater than and less than. Let's take an example to understand this. We have got two strings here: aardark and beluga. Write an 'if' statement to check out whether if (str1 < str2). It will begin comparing the first letters. According to this case, you intend to find out if a less than b. This is almost like doing a phonebook comparison. The result is true here i.e. first string is lesser than the second string.

str1 = "aardvark";

str1 = "beluga";

if (str1 < str2 ) { ... // true

str1 = "aardvark";

str1 = "Beluga";

if (str1 < str2 ) { ... // false

Importance of uppercase & lowercase in strings:

The usage of uppercase and lowercase can make a lot of difference and can be confusing sometimes. Let's take the same example as before to understand the difference. You have astonishment with a lowercase a, and Bachelor with an uppercase B. Again you need to do the comparison between the two wanting to find out if str1 < str2. Many programmers get confused over here and this as true. Contrary, it's false. The reason lying behind is that in programming language, the internal structures of the characters are encoded in such a way that the uppercase letters are considered less than the lowercase letters. Therefore, uppercase B is reckoned as to come before a lowercase a. So the condition is false. In case you want to change this or mistakenly you have written uppercase B, again you will have to use the ability of the string to be converted and calling toLowercase on both of these before comparison.

To wind up with this, it is apparent that strings have a lot of built-in behaviour which allows us to deal with different conditions.

# Introduction to regular expressions

We have studied about much built-in functionality like conversion to uppercase or lowercase, slice out the pieces. We can also find out if a word exists in the string. But sometimes there can be a case where we want a different approach and rather we are interested in the format of the string.

Take an example:

You are required to know whether the string is an email address or you may say if it is an URL. The other cases can be you want to check if a password has a mixture of uppercase and lowercase letters or may be the existence of some special symbols. You might be required to verify whether a credit card number has the correct amount of digits. These are just few examples where you will have to make use regular expressions built into many programming languages.

Regular expressions are sequences of characters that describe and have the ability to match patterns and strings.

Although nobody finds 'regular expressions' comfortable to begin with. But they are very useful and it is important to know about them. There is always two parts to work with regular expressions. First, create the expression that describes the pattern you're looking for and next, try and apply it to something and find out if it matches.

Usage of regular expressions:

Firstly, it is required to create the regular expression. There are few ways to create it. one way is create a variable and name it myRE for my regular expression = /hello/. This might look strange to you because we haven't seen such a programming yet. These quotes have significance. This forward slash (not back slashes) marking it as a regular expression.

Another way of employing regular expression is almost the same as before with a slight difference. Despite of myRE; now we make use of a new word RegExp which is regular expression and store the string hello into it. In either of the cases we are actually creating a new regular expression object. Most of the object oriented language employs regular expressions. The second word new implies creating a new object. The word hello is simply a pattern which is up to you. You may take some word as well. It is now required to look for the word hello if it exists in another string. Once the regular expression is created, we will have to test it. Create a new variable called myString. We'll test the regular expression against this new variable. Therefore, the 'if' statement will be if myRE dot test. Dot test is a built-in method. It is treated as a function that belongs to this regular expression.

myRE = /hello/;

// or

myRE = new RegExp("hello");

myString = "Does this sentence have the word hello in it?";

if ( myRE.test(myString) ) {

print("Yes")

}

You have passed in the variable myString and with the help of the above function you're willing to check whether it contains the word hello in it. The output will be a Boolean response. By calling the above function to test will return either true or false. In this particular case, if the word hello exists in myString, we will write a code to get it printed and say, yes.

Complex patterns in regular expressions:

There are some regular expression objects which have other methods that can return different data. The special characters are used for creating complex patterns. Let's take an example. Create a new regular expression variable and use the shorthand format which uses the two forwards slashes, one at the start and the other one at the end. Whatever is being written in between them is the pattern that we are going to match. The point to mark here is that the forward slashes themselves are not part of the pattern. As we have already seen the match on the word hello, so let's move onto some different examples. Prefix this by the caret character. It actually means hello has to be at the start. If instead of this, the pattern was hello$ before the forward slash, it implies that hello has to be at the end.

myRE = /^hello/; // ^ at the start

/hello$/; // $ at the end

/hell+o/; // + once or more

/hell*o/; // * zero or more

/hell?o/; // ? zero or one

hel*o means that it would be a 0 or more. Hence, it would match all the previous ones and also match heo. Here l doesn't appear at all. There is a question mark for 0 or 1 match. It would match heo or helo, but would not match more than that. The vertical bar symbol means it is matching either for hello or goodbye. The decimal point is the period which means any character.

If you're using backslash w inside the pattern, it is going to match an alphanumeric and underscore. The other case is if you use backslash b inside the pattern. It would mean you are looking for a word boundary like a space or a new line. The square brackets can also be used to provide a range of characters to match on. In this case, if you are looking for the 'ope', then it would match on these words: cope, rope, lope and dope. These are among the very few patterns that can be form complex patterns in strings.

/hello|goodbye/; // either|or

/he..o/; // . any character

/\wello/; // \w alphanumeric or _

/\bhello/; // \b word boundary

/[crnld]ope/; // [...] range of chars

There are many patterns for regular expressions such as if you're willing to match a date or a password or credit card format. One of the regular expressions which are still on process is to match on an email address. It's a complex operation and people are still discussing and debating from many years on what the perfect regular expression for an email address is. Sometimes you might notice there is a kind of a repetition of the same kind of thing. The reason lying behind is that an email address can follow many complicated rules. The regular expressions for email addresses might be not perfect but this is what has come across the most. There can be complex patterns in regular expressions where you are not looking for a perfect match but something which is good enough to fit in well. There is no need of memorizing the formats even if you're new to programming. You just need to set your focus on the fact that they do exist, for what purposes they can be used for and how they're used. Most of the times, you will probably notice that the syntax of regular expressions are built-in to most modern programming languages.

7

Working with arrays

# What is array?

An array is an organized collection of similar type of data. The data or the values are encapsulated one above the other and given a name. We have already seen how to create one variable at a time. After creation of the variable and giving it a name; we can make use of the equal sign to assign that variable a value. The value could be a letter or a number or a string or may be it's a Boolean value. But the thing is that it will be one value. There raised a situation where one wants to store multiple values in a variable. This led to the introduction of array. An array is the notion behind having multiple values all contained in a variable which can be treated as data and collectively forming an array.

Format of an array:

Create a variable named as myArray containing multiple values in it. It's a great way of keeping the data together that belongs to each other or is kept for the same purpose. Now, there is no bondage on the number of values to be stored in the array. It can be dozens, hundreds or even thousands of pieces of information stored together. There is no need to give names to every single individual piece as an individual variable.

There are a couple of concepts which need to be cleared before learning how to form an array. These are:

  * In an array, each individual value is referred to as an element.

  * It is given a number or an index that identifies where it is stored in the array.

  * Arrays have an internal order. They don't shamble their values randomly.

  * The first slot is given an index value of 0. The second slot or second position has an index of 1, the third slot is 2 and so on.

Let's create an array containing six elements. There is no minimum or maximum size. You can make arrays as lengthy as you need them. But an important thing to bear in mind is that the lengthier your array would be, the more memory it will occupy. The amount of memory which is available to you is limited and so, it is advisable not to occupy the memory unnecessarily. Keeping in view the limited amount of memory availability; now-a-days most of the programming languages have zero-based arrays. This means that the first position will be occupied by the first element in the array and is considered to be at position 0, not position 1.

On the contrary, there are few languages like the older versions of Visual Basic which used 1-based arrays. But still 0-based arrays are more common and often seen in programming languages. Index number is used to either set that value after the other or to get to that value. Hence, to access any one part of the array, it is necessary to make use of both the name of the array and the index of the element. Let's understand this by making an array. The creation of the variable will be same as we used to do it earlier. But it is necessary to indicate to the programming language that we are forming an array.

How to form an array?

There are few ways to form an array. The easiest one among them is to use the word multiple values. Create a variable named as multiple values. You can give any other name as well. You will have to use the assignment operator along with the opening and closing square bracket. These square brackets indicate that we're dealing with an array and not a single value. So, whenever you see these square brackets, it simply point towards an array. After creating a single variable called multiple values, you can that you can store as many values as you want into it.

Now the question arises how to store the individual elements in the array. You will again have to use the square brackets to mark out the position where you want to place your values or elements. If you want to feed multiple values in the array; you need to again make use of the square brackets. The numeric value written inside the square brackets is the index.

Case 1: setting and accessing elements of an array one by one

Use the name of the variable but despite of using an assignment operator to mark out the position; you will have to make use of square brackets to assign the index. Suppose you want place the element at the position 0 and set it to the value 50 and the next element at the position 1 to be set to the value 60. You can even set the position 2 with the word "Hello". The thing to notice here is that you can put any value or elements as per your program regardless of whether that is a number or a string or a Boolean value. You can put anything you want because it doesn't matter what kind of data you're storing at the different slots in the array. The thing common in them is that they are all accessed by using particular index numbers. It would be the same case no matter whether you are setting these values or accessing these values. It always starts off from a 0-based index.

multipleValues[0] = 50;

multipleValues[1] = 60;

multipleValues[2] = "Hello";

print(multipleValues[2] ) ;

The same format can be used to get the contents of the array. If you want to write a message "Hello" at the second position, it can be easily done by using square brackets and we've seen this already. Though this is an easier way of forming an array but there can be even easier and faster ways for creating and accessing the elements of array.

Case 2: setting and accessing elements of an array in one line

Instead of wasting time in writing several statements like the way we've done in the above case, we can use the square brackets and combine all the elements onto one line. We can just simply load this array up with the initial values. Let's take an example: when you write 100,200, "Hello" inside the square brackets, it will automatically create an array and put them at the position 0, position 1 and position 2. Further you can come up with adding more positions like to position 3, position 4 and so on. But it will always begin from a 0-based index.

multipleValues = [50, 60, "Hello" ] ;

Arrays are found in every programming language and there are also other ways to group values together. There can be a possibility where you do not want a 0-based index but a letter-based index. There are other ways also to access the elements of the array. Such ways can also be employed but as seen in most of the cases, they follow 0-based index. A collection in a programming language is simply multiple values that are grouped together in some way and thus, forms an array. There can be slightly different ways of creating them across various programming languages but the overall concept remains the same.

# Behaviour of array

Arrays are often considered as objects. The word 'objects' sounds very common but it has a very special meaning in programming. We will dwell more into objects but before that it would be enough to reckon them as the containers of data. Arrays are very useful and tell us information about them. Because of their behaviour, they can perform any task that we ask them to.

Analyzing with an example:

Let's see this by an example and try and understand. Create a variable which just contains a string. We have already studied about the usage of the dot length property of string variable which gives the information about the string. Suppose if with the help of this property it prints the length of the string being 5. It doesn't actually go and count all the letters. The string has the behaviour that it knows the length of it. It makes use of the same kind of format to find the information about arrays. We'll use the shorthand format to create an array containing five elements ranging from position 0 through position 4. It can also be done with the help of the string named as myArray and call myArray dot length. As a result, it will print the number 5. This is an important thing to mark out here that despite of using several statements to form an array; we just did it in a single line by using dot length property of the string.

myString = "This is a simple phrase.";

print ( myString.length );

myArrey = [10,20,"test",True,99];

print ( myArray.length );

It gets to know that its length is 5. This is the length of the entire array containing five elements in it. Although the elements are positioned at 0, 1, 2, 3, 4; but it showed up 4 as the highest index. When you call dot length on a string, it automatically understands that the programmer is asking for the number of characters in the string. Similarly, when we call dot length on an array, it gives us the length of the array.

Methods in arrays:

We have already seen the usage of functions. We use the name of the function along with the opening and closing parentheses. We can create functions ourselves and can also use the built-in functions like alert. In this case, you're calling a function and then passing in some information that also returns a value. Functions are used in every programming language. We have seen a bit about methods which were very similar to functions. A method is a function that belongs to an object. Instead of calling a method directly, we use the name of the object followed by a dot and then the name of the method.

SomeFunction ( );

// to call a function

print("Hello");

result = calculateValues(5,73);

SomeObject.someMethod ( ); // to call a method

myString.toUpperCase( );

If you call a method by using the opening and closing parentheses, it would be like calling a function. But it is important to specify for what purpose the method is going to apply. If it's a string variable, we can use the dot toUpperCase method to convert the string to uppercase. And there are many more methods that we can apply. You can create multiple arrays and the different methods can be called on each array. A shorthand format can be used here.

Take an example:

Create a new array and store some random values into it. There are five elements in the array. Now write myArray dot reverse along with the opening and closing parentheses without passing any value into it. It will reverse all the elements present in the array. 50 had been at position 4. It will now come at position 0 and so on. There are other methods like dot sort. It will sort the elements in the array according to the rules of sorting. In case, if the elements in the array contain all alphabetical or numerical values or may be both; we can make use of dot join. It will take all the elements of the array and combine them with commas and then after return them as a string. As per the behaviour of the array, it has all the information.

myArrey = [10, "a", 1, 40, 50];

myArrey .reverse( );

.sort( );

.join( );

While programming you might be thinking whether you have to memorize the things. The answer is no, at least not initially. You can't memorize every single method on every single object as there are so many. You can find a reference guide in this case.

You can refer to the reference guide for the language that you're working with and explore the different methods available for that language as per your need. There is no need to memorize everything. Just try to know where you can find the reference of the syntax.

# Iterating through collections

An array is one of the most common things that are found in all programming languages. Despite of thinking too much on array, it is better to try and find out the different kinds of applications available in your computer which is the collection of things. An email program is a collection of emails; an address book is a collection of contacts; MP3 player containing a collection of albums and playlists are some examples of collections.

Usage of loops in array:

The most common thing you need to do is to iterate through or loop through every element in an array. And it is very easy to do this. You don't need to know much about array here. Let's imagine you have a simple array with five elements. It doesn't matter with the number of elements in the array. You can set up a basic loop like a while loop or a for loop. It has the regular elements.

All we have to do is to set up the index. We have already seen the importance of beginning with the 0-based index and while working on the basic array; it is always advised to start the index from 0. You need to check the condition now and you'll notice something different this time. But at this stage you need to know the length of the array which you can find out with the help of dot length property. You may write the condition as while i < 5 (i is the index), but it is much easier to write while i <myArray dot length. This will save your line of codes and make your program look short. As we've seen earlier also, since it's a loop we'll be required to increment the index at the end of the body of the code block.

i = 0;

while ( i < myArray.length ) {

//...

//...

print ("The value is:" + myArray [i] );

//...

i++;

}

The thing to keep in mind is every time we iterate through or loop through we can make use of the index. The value of i helps us to access the current element.

Taking an example:

To make it more clear to you; let's try and understand the difference in the usage of i in this example. If you create a variable i, go through the code and execute it. Here the value of index is 0. Moving on to the next line, you see the condition if i is less than myArray dot length. Here you'll have to first of all find out the length by using myArray.length which will come out to be 5 in this case. Now you'll begin checking out the condition. There are five elements in the array. This means myArray.length is 5. Now we need to know the value of i to check on the condition. You might remember that dot.length property gives the highest number of index i.e. 4 in this case. The condition comes out to be true. Therefore, we jump into the body of code block and start executing the code. Now there can be either some alert message or might be you want to access the first element of array. We'll write myArray and the value of i which is 0 for the first element. Moving down to the further processing; we'll get to the end of the loop and increment the index.

We'll move back and check the while statement again. Now the value of i is 1 after increment. Now we need to check whether 1 < 5. The output is yes, it is. This is how we'll keep on moving through the loop while adding 1 to the index, accessing the element at that particular position and executing the code. At one point we'll come across 5 while keep on incrementing the index. At this point the condition becomes 5<5 which is not true. Hence, the outcome will be 'No, it isn't'. As the condition was to check while i is less than 5. So, after we encounter 5; all the other values will be of course, greater than 5. Therefore, the program will terminate here. While we're checking the condition we're actually checking against the length of the array and the value of index access the current element.

# Collections in other languages

It's important to know how other programming languages deal with the collection of data. There is no need to get too specific about each individual language, but there are a few key notes which the programmer should be cognizant about. First of all, most modern OOPS oriented programming languages allow any kind of element in the array. It can be numbers, strings, Booleans or can even have elements undefined. It allows mixed data. On the other hand, there are many languages which allow specific kinds of data in an array. It is an array of strings or an array of integers. Alternatively, strings and integers can be stuffed in the same array as well. This is probably more common across languages.

Concept of mutable & immutable objects:

Secondly, some modern programming languages allow to create an array where the elements can be added up or subtracted. Suppose, if there are three elements, we can add more elements to it or even subtract from it. Whereas, other languages allow arrays to be of fixed size. It should be known to you how big the array is before accessing elements. Suppose you have an array of five elements long. Once you have created the array, you can't change it. There lies a concept of mutable versus an immutable object. If something is a mutable it can be changed, whereas if something is immutable it cannot be changed after it has been created.

While dealing with different languages, you need to choose if you want an immutable array or a mutable one. You might be thinking that flexibility of array is much more comfortable to work with. But there are times where we do not require doing any kind of addition or subtraction. Let's see through a couple of examples. When you're dealing with days of the week or the months of the year; we do not require to do any kind of alterations. There is no need to eliminate any element mid of the program.

Benefits of immutable arrays:

One of the strong advantages of immutable arrays is that they are faster to work with. All one has to do is just allocate an area of memory for that array which it knows is not going to change. On the other side, working with mutable or changeable objects, one thing will keep troubling your head that this array may grow or shrink. We know that an array is an organized list of items. We begin from the position 0 and keep incrementing the index one by one. But there can be other kinds of collections as well. Now imagine instead of the built-in index of 0, 1, 2, we might want a, b, c as the indexes.

Take an example:

You have a list of states. The collection is very useful but we are using the abbreviation for these states. Despite of using indexes as 0, 1, 2; we'll use MO, TU, WE. Many languages allow this kind of an array and it can be given a few different names. Such kind of array is called as an associative array. This can also be considered as a dictionary or map or a table. It can be associated with databases. But it's not a database. It has nothing to do with a database. These are variables in memory and allow us to access each individual piece of data. So whenever working with any language it is advised to know about the built-in support for different kinds of collections.

8

Style in programming languages

# What is style?

While working with different programming languages; you will come across a new factor called style. You need not to worry about the rules or the syntax or how to write the code rather style tells us how you should and shouldn't write it. It actually deals with what names should be given to the variables and what is the right place to put the curly braces or how should you call the functions and how should you applied in the code. All the programming languages have developed a set of style guidelines.

The major point of style guidelines is that you need to focus on making your code readable, consistent. You will also need to keep an eye over how other programmers are writing their codes because that will help you out in making your code look easier to read. Also you can refer some books to rectify whether the code you're looking at is written well or not.

Take an example: style in C based language

Let's have a look at the style guidelines used in C based languages. These are very much similar in many other languages. You have already been to some of these rules earlier. The rules goes like you must use letters, numbers, dollar sign, underscore. But the thing to mark out here is that it can't begin with a number. This doesn't imply that this is the only perfect way of writing a variable or a function name. It just means it is allowed. You need to focus on readability and meaningfulness.

Create a variable named as 'a'. You can choose any other letter also. Sometimes variables are even given meaningless words like 'coo' or 'shu'. But the information represented by these programming variables is very useful. In case of an image, the information could be a name, a date, the height and width of an image. Now-a-days, naming conventions hold the dominant part. Variables and functions are the two whose names are decided by us and are mostly written in CamelCase format. This actually implies that name of the variable starts with a lowercase. But in case if there is more than one word, it will capitalize the first letter of each subsequent word. Just like the hump of a camel and so the name given.

variable score;

variable highScore;

variable everHigherScore;

Style in other languages:

There are few languages which separate multiple words with underscores and the same thing goes for functions. The functions which make use of multiple words for clarity are such as calculateDistance and often they are seen as verb-noun format like checkFormFields. Some style guidelines suggest separating the words instead of using underscores in other programming languages. In some cases, abbreviations are prefixed before the variables like a string or an integer.

function calculate ( ) {...

function calculateDistance ( ) {...

function checkFormFields ( ) {...

CamelCase format is the dominant style in modern world. It is recommended by the Yahoo and Google style guidelines.

The problem with brace style is where to put the opening and closing curly braces and how much to indent your code. While using 'if' statement or a 'while' loop, the curly brace gets opened up on the same line as the keyword. The code is indented inside the block and the closing curly brace closes on a line by itself matching up with the keyword. You must have noticed while using 'if' and 'else' statements that 'else' is written on one line with both the closing of the previous block and the opening of the next code block. The other styles like Pascal or Allman style have the opening brace on its own line and then it lines up with the closing brace. This is very much common in languages like C#. But the C based languages, for 'while' and 'if' statements and its makes use of the opening curly brace on the same line as the keyword. You should be consistent over the way you write the code.

For an overview to keep some rules in mind are as follows:

  * You should make use CamelCase format for variables, functions, and methods.

  * Open curly braces on the same line.

  * Define functions before calling them.

  * Use semicolons to end a statement.

  * Always use proper variable declaration.

# What is pseudocode?

While you start writing a program, you might come across a blank text file, the syntax, case sensitivity and the curly braces. There can be many other things to keep in mind while writing a program. Now despite of remembering all these things and there are thousands of things associated with it. So it is not practically possible to make your mind engrossed in memorizing the stuff. Instead you can jump off from your computer and either find a piece of paper or look for a whiteboard and then begin writing what's called pseudocode. Make one thing very clear that pseudocode is not a language.

Pseudocode is the term for writing the computer instructions in plain English. They are written to the point which makes it readable to anyone who comprehends the problem; no matter whether they have a pretty good command over codes or languages.

Case 1:

Let's go through few examples. Suppose you're asking the user for email addresses and pens it down on either a whiteboard or a piece of a paper. If the email address is found to be matched to the accepted pattern, add them up to the email list or else show up the error message. The basic thing about pseudocode is that there are no fixed formal rules, but some of the rules are very common to see.

Conclusion:

The way you deal with things and go down to follow the steps matters a lot. Despite of simply asking the user for email address, you could have also asked to prompt for email address. To make it more clear and understandable, it is always advisable to break the things apart and makes it readable. Create an email variable, ask the user for email address and store user's email addresses in the email variable. This might be a bit lengthy. What are we trying to do here is defining the structure of the code. You will now come across programming keywords like if and else and while and for. Pseudocode is only indented to make the structure to be followed easily.

Different people have different ways of writing the pseudocode. The longer you will write a language or the lengthier you steps would be; the more the pseudocode will have a tendency to inculcate the style of that language. Sometimes you might fall upon pseudocodes written partway in uppercase. Many a times while writing pseudocodes, people overtly mention where an if or a loop ends by using a phrase like END IF or END LOOP. This exactly serves the same purpose as a closing curly brace in any C-based language. The only thing which makes them fall on opposite sides is that there are no rules in psedocode. The only focus is on clarity and understanding.

Case 2:

The thing you should clear in your mindsets is your pseudocode should make sense. Let's see an example where you're going through a list of numbers and adding them together. We will start off with setting total to zero, getting a list of numbers, looping through each number in the list and finally adding each number to the total. You need to remark where the loop ends.

Conclusion:

If the number is more than zero, it will print a positive message, else it will print that it's zero or last message, end if. All that matters is it should make sense whether you can program or not. There is no syntax of writing pseudocode. It's a place where you don't have to worry about braces, parentheses, brackets and naming conventions. It is not necessary that one line of pseudocode will break down into one line of real code. Sometimes one line of pseudocode like send email can split up into several lines of real code. The best thing in pseudocode is it explores and let you know the problem without necessarily knowing exactly how to code it. In case you have a problem in writing a code; it exposes where you need to go and learn about it. Even when don't have any knowledge about the language; you can still write psedocode and identity the problems.

Case 3:

Let's suppose as if you're building a game and you know how to work with images. You have some idea about such programming as you have done some of it already. You start writing a pseudocode code like this. If a missile-image touches the spaceship -image, you're going to replace this spaceship-image with the explosion-image. An explosion sound will be played and then you need to check if the remaining-lives counter is zero. If none of the lives are left, you will show the "game over" message. In case it is not zero, you will subtract one from their remaining lives. You will show the begin message. You will reset the spaceship to the starting position. This is not necessarily the perfect pseudocode for a game, but you're following the steps here. Even if you do not know how to play a sound in the language; you can still build your pseudocode. You can make your own personal task list and pen down all the problems you want to look up for. You can pen down like: "research how to play short sound effect." After you've figured it out; you can code this.

Conclusion:

It must have cleared to you now that pseudocode is not just for beginners. Many very experienced software developers also work out a lot of their problems in pseudocode; so that they can have a better understanding of it without worrying about syntax. It's a very useful habit to get into to start sketching out your programming ideas in plain English before you write code.

9

Input/output and persistence

# Significance of input and output:

Programming is all about input and output. But many years down the line, the usage and meaning has changed. Years ago the idea about programming was very simple. The only programs which we used were batch programs. It used to go around in a very short and snappy way.

Case study: traditional and modern programs

Let's give you an example of it. The program was like a food processor. You would be giving a file of data as input, then let the program process all of these files. Later on extract out the results to another file or directly to the printer. Finally, the program terminates. You did not interact or interfere with the program while it was processing.

Such types of programs are designed to run and finish as fast as possible. But later on such programs were designed that run with graphical user interfaces. Programs like a web browser that not just start and run all the way through as quickly as possible.

On the off side these programs can also stay up in between the process. We can interact with these continuously and erratically over hours or even days or even weeks. But here the input and output has a different meaning. A mouse-click over something or something typed in a webpage is the input whereas; change of images on the screen is the output. This is not the same as saving and loading files because sometimes we are required to save documents to the hard drive or load files from the hard drive or save information to the web.

Introduction to persistence:

Describing everything as input and output is very common. When you are saving some information and then running a program. Finally you want to save information either to your document folders or to a database or to the web or to a cloud. All this simply implies that it will come out of the currently running program. But that data would still be on the drive or in the database or in the cloud. This is termed as persistence. It is referred to save the state of a program. If you won't decide where to persist the data it will just disappear.

All the variables we've worked with so far get stored in the computer's volatile memory in RAM while the program is in process. On the other hand, when we close the program everything is disappeared if you don't decide where to store it. But the major problem is that different programming languages support different ways of persistence. Languages which are mostly used for desktop development, mobile development or mainframe development have built-in ability to write a code to save or load files to the hard drive.

# What is Event driven programming?

Till now we have seen all the code gets executed as soon as the page loads the script file. It goes through it as fast as possible and finishes. But this is not just what we are seeking for. There might be a situation where the program starts to react on some input from the user. Here, the task just doesn't get over with prompting the names. You may want your program to react on whole lot of different things. The inputs could be whether the user clicks somewhere on the screen or do they move the mouse or does the user resize the window? These are all events and the programming driven by such events as inputs are termed as event-driven programming.

Examples of Events:

The ability to employ event-driven programming is built into most of the languages now. Unsurprisingly, we are cognizant about it that such events are already happening around. When the page is loaded, that's considered as an event. When the user clicks somewhere on the screen, this is another event. And when we say when they move their mouse falls under a whole bunch of events. Scrolling the screen up and down or clicking into a text field or typing the keys on the keyboard are all events. Even when they leave the form, it's another event. To wind up all this, we can say events are going on all the time.

Why Event-driven programming is used?

Your job as a programmer is to find out the ways of doing this. One of the ways is to write some functions that run it only when the user clicks a button or moves his mouse. You are not required to ask every time if the user has pressed any button. The operating system is designed such way that it takes care of it now. You just need to decide which events you want it to react to. You can write what are called as event handlers or event listeners. You can give them your own term. This is similar to a function which is waiting for an event to happen. The point to notice here is they are all written in lowercase and begin with the word on. Such as onload, onclick, onmouseover, onfocus, onblur. All you have to do is write a function and peg them up to these events.

Take an example:

You have one event called multiple functions or multiple events. You're free to give any name. Though there are several ways to handle an event but here we are concerning on one for a basic understanding. While working with event-driven programming, there are two pieces of information that you require. First, what is the event and second, what do you want to do with it. Now keep in mind that these events can happen on different pieces of the page or may be the different pieces of your user interface. It's just an idea of a click event. But this click event must be happening over something. It can be either on a button or an image or some other part of the screen.

Format of Event-driven programming:

The general format is element dot event name. This format encircles both what is the element as well as event. If it is like: window dot onload. This indicates the load event of the window object. The window here represents the browser window. This is an event you can react to when the page gets loaded. If you want to fill out lots text fields then the format would be: nameField dot onblur. The onblur event will occur when you leave a field. Type your e-mail address and click on the Tab key. This event will be called. This is one of the most common ones: myelement dot onclick. Now this element could be heading or an image or a paragraph. When you write myelelmnt dot onclick; you are actually creating a function here.

myelement.onclick = function () {

// your event handler code

//...

//...

}

The idea of the word function followed by parentheses, and then followed by the opening and closing curly braces is the general format that we've seen earlier also. Usually, the word function is associated with a name. If it's not given any name, it's called an anonymous function. It means a function without a name. We know that the function is just a bunch of code wrapped up. When we use a function it is actually indicating towards an occurrence of an event and then after the code inside the block is executed.

Usually whenever you declare a function; you make use of the opening and the closing curly braces. While following this format, you might come across a semicolon after the closing brace. This is something contrary to what we have seen in 'if' and 'while' statement. They don't use a semicolon just after the closing curly brace. The reason of putting a semicolon here in this case is because the entire line is a statement and not a function. So the format becomes: myelement dot onclick = the function and whatever is inside it.

# Introduction to file I/O

It's a very common requirement to have a program which reads files on the hard drive or save files to the hard drive to persist information there. Let's have a closure look over the input and output files. Take a few pseudocode examples and then try and find out how it looks in another language. When you see file input/output or file I/O might look easier on a first look. But it's not as easy as it sounds. It reads the most basic of files. You need to know the path. First, you need to open the file and then read the contents of the file. And finally you need to close it.

Case 1: with the help of pseudocode

  * Write a simple pseudocode just like:

  * Open file at path myfile.txt. This allows you to grab hold of it.

  * Read the contents of the file into a string variable.

  * Close the file.

There is always a rule or you can say a procedure to close the file when you're done with it. There can be many problems that you might face while closing it. It could be like if that path has no file or some other program has that file already open or if they have already grabbed it or if that file is too huge that it cannot be read into a string variable. So there can be hundreds of possibilities of problem to occur. While dealing with file input/output, you will come across is a lot more conditional code going on to check out the things and that could possibly go wrong. No need to worry about it too much. All you want to do is to read in a small text file that you know exists.

Case 2: Using Ruby

Let's take an example using the programming language Ruby. As told earlier also; do not worry too much about the syntax. We are only focusing on the overall approach here. It's not about whether you can scan this code and find out the file path or look where you had opened and close the file. You just have to keep an eye over the general approach here.

We'll open the file called simpleexample.txt. Because you haven't given any path information here, so this file should be in the same folder as the program itself. The next line will tell you which file is to be opened here. Write file dot open using that filename. The "r" in quotes have a significance here. It means open this file in read-only mode. If you want to open this file where you could write to it; you will have to use "w" in quotes and for both reading and writing; you can write "r+".

filename = 'simpleexample.txt'

f = File.Open(filename, 'r' )

f.each_line { |line|

puts line

}

f.close

Different programming languages support opening files in different modes. One mode is for reading, other mode for writing and another mode for reading and writing. There might be an overwrite mode if the file exists already or another mode to append if the file exists already. These types of modes are very common and useful. Opening a file in read-only mode has less impact on the system and it allows other users to open it too.

We've got a couple of curly braces being used. It appears to be some kind of container. We are actually reading each line and using puts, p-u-t-s. This puts a string in Ruby language to display each individual line. In the last line we're writing f dot close. This is closing the file that we have opened on line 2.

Let's write a string out to a file in Ruby. We begin by creating a string called message. The same thing will go with the filename = 'myoutput.txt'. Then after we call File dot open. We'll be using a slightly different format here. We have got the "w" in quotes which mean to open in write mode. The last line allows us to have an automatic close to the file that you opened a couple of lines beforehand. Again the approach is important here rather than the syntax. You are required to know the path to open the file, to write the contents and in the end close the file. Ruby is one of the simplest languages for reading and writing files.

message = 'This is for output.'

filename = 'myoutput.txt'

File.open filename, 'w' do |f|

f.write message

end

Case 3: In other languages

If you have shown this in C++ or Java or C#, you would have to deal with more number of lines. There's a big difference between reading a typical text file and reading a file of binary data like audio or video. In other languages you rarely read an entire file at once unless you know it is small. Despite of it, you read the file as one piece at a time. You break it down into pieces. Let's see an example where you want to process one line at a time rather than reading a text file all at once. , you process it one line at a time. The pseudocode here is to open the file at the path myfile.txt. Then after go through a loop that says while the file has lines left, read one line and display that. Finally, end the loop.

We'll again go through the loop enquiring whether it still has lines left. The output here is positive. Similarly we'll go through another line, display that line and this is how we go piece by piece through the entire file. Finally, we'll close the file. If the file is opened it needs to be closed.

Concept of streams:

Many higher-level languages like C#, Java and Objective-C, you can end up working with files by using what is called streams. The concept of a stream is very simple. It means a stream of bytes like a conveyor belt of bytes. It is not as complex as it sounds. While working with streams, you need to take them all as one piece at a time. It's easier working with streams because you need not to worry where this data lies. You even don't have to enquire if that file is on your hard drive or not. It doesn't matter whether you're reading this data online or offline. It is a stream of data that you need to deal with. The only problem that a programmer who is new to any language might face is finding out how that language works with file input and output. You'll figure out yourselves that most languages deal with the same concepts in slightly different ways. They all have substantial built-in functionality for reading and writing different kinds of files.

10

Introduction to debugging

# Cause of debugging:

If you're completely new to programming then it would be difficult for you to write even a single line of code that works correctly. Programming languages are very specific and it's very likely to get mistaken in the special characters that it uses. Like using a colon instead of a semicolon, missing a closing quote, using the wrong operator or the wrong name. Once you get beyond programs like "hello, world" and begin writing programs which are important. It becomes difficult to write more than a few instructions without tripping up over your own logic. You expect your code to work and it's quite possible to get upset when it doesn't. There are a few things that experienced programmers know and non-programmers don't.

# General errors in programming:

It is very rare to have a program which works correctly at first attempt only. There will be times when you don't expect our code to work anymore. Your code can still break every time. Programs aren't just written. They are edited into existence, built slowly piece by piece. Every programmer spends frigging more time debugging their code than actually writing their code. Every time you write a few lines, you check it, fix it and then write a few more. Again you check them, go back and fix the first ones we just broke down. This process keeps on repeating.

Don't worry about mistakes. They are likely to happen. Every time you fall into some mistakes; it will be a plus one to your knowledge in programming. This is how you learn to debug the code. Keep rectifying what went wrong with your code and go back and fix it. You might come across some situations when you'll find your program was working finely but you noticed some odd behaviour in the result. You will notice this odd behaviour in the errors in your code. This breaks down into two main categories.

The first and the foremost are syntax errors and logic errors. Let's find out the difference. Most of the times, the problem is found in the syntax. This means that something is wrong with the actual format of what you wrote. Further possible errors could be misspelled keyword with wrong case letter or usage of a colon instead of a semicolon or forgetting to close a quote on a string. It's not that easy to debug such errors when you've got thousands lines of code.

Debugging syntax errors:

Even experienced programmers are likely to commit such errors and from time to time they have to go through letter by letter figuring out what they have missed out. It's very common to count the opening and closing curly braces to make sure that they match up. One of the benefits of using programmer's text editors is that they highlight the syntax. While you're working in an editor and green means a comment. Sometimes you can make a mistake like when you've accidentally opened a multi-line comment. This made everything after this an actual comment, whereas what was required was a single line comment.

Color coding can help you a lot when you're just scanning your code to find syntax problems. These kinds of problems become less occurring when you get familiar with any language. Might be you still make them but it would be lesser. One of the benefits of using a compiled language rather than an interpreted language is these syntax problems are found before you even try to run the program. The very useful thing in compiled language is the complier as your code needs to go through the compiler before execution. But with an interpreted language, you often have to attempt to run it and find out what's wrong.

function startCountdown () { //get contents of the "minutes" text box

minutes = document.getElementById("minutes").value; // check if not a number

if (isNaN(minutes)) {

alert("Please enter a number!");

return;

} //how many seconds?

secondsRemaining = minutes * 60; //every second, call the "tick" function

intervalHandle = setInterval(tick, 1000); //hide the from

document.getElementById("inputArea").style.display = "none";

}

Debugging logical errors:

Next comes, the logic issues. Generally, these are the most acquainted and the major problems for any program. This happens even when your code is correct in syntax and if you're working in a compiled language, it even compiles, but there pops up a flaw in the logic. Let's see through an example. Create a function and that might have a lot of code in it but somewhere in the middle, you've got a return statement.

The problem is if you have fall upon a return statement and a function, you'll straight away jump out of the function into whoever called it. This implies that any line after the return statement would never be executed. The problem with such an error is that they can be extremely difficult to find. There are some logic errors that even fall into their own category like problems with arithmetic. Such types of errors are also correct in syntax but they are meaningless.

function myFunction( ) {

//do stuff

return 0;

//do stuff

//do stuff

//do stuff

}

If you write some code having a variable named as 'a' and set it equal to 50 and the other variable b = 0 and storing the output to a variable called result. The task assigned to result is result = a/b. The syntax here is correct: the right case, the right operators and even the semicolons at the right place. The problem is this doesn't make sense. a/b here is 50/0. Dividing by 0 is not allowed. It is logically meaningless, so the computer can't perform this. You will notice in many programming languages, the line that tries to divide by 0 will cause your program to crash completely. These are just a few examples of the errors that are committed very easily.

a = 100;

b = 0;

result = a / b ;

print(result);

The logic errors will be the most significant problem you'll face have as a programmer. In any debugging situation, try to reproduce the problem. Hopefully it will help you out to figure out the cause of the error easily and where it has occurred. You need to figure out if your program is actually running the way you thought it to be.

11

Introduction to object-orientation

# Why we use object-orientation?

The most popular programming languages developed in the last 30 years are all Object-Oriented languages. But this is not actually true. These were not object-oriented languages. They were straight procedural languages where the program was written as a lengthy procedure. It contains named functions and subroutines to make it look more modular and maintainable. It has a very long piece of code enclosing all the data and the variables defined in one place and all the logic in another. As programs get lengthier; it becomes really difficult to manage and plan out things. Object-Oriented languages started to gain popularity in the '80s. In Object-Oriented language, the one large program gets split apart into self- contained objects. These are similar to several mini-programs and each object here represents a different part of the application. Every object contains its own data and its own logic. They also communicate between themselves.

These are objects are not just randomly created. They represent the way you talk and how you tackle the problem which you are trying to solve. They can represent things like employees, images, shapes, bank accounts, player objects, students, spaceships, asteroids, video segment, audio files and whatever that exists in your program. Object-orientation can be referred to as a programming paradigm. It's not a language itself but a set of ideas that is supported by many languages.

There are also other alternatives to Object-oriented programming. Other than just procedural languages like straight C, you might also work with logic programming languages like Prolog if you pursue a university computer science course. Functional programming languages like Haskell tend to be more popular in the academic world or for very specialized uses like computational linguistics. If you want to work in the pragmatic world of creating web applications, mobile apps, desktop applications, game development, it is advised to use Object- Oriented programming languages.

What is an object?

Always remember one thing that the introduction of Object-Orientation and computing was intended to dwell more into programming and bring the real world closure to it. When you refer to an object in a computer program, you should know what is that object in the real world. It's difficult to describe an object before you know something about it other than just taking it as a thing. So here we are looking for the objects which even belong to real world like you can say like apple, mug, fruits and there are more thousands of etc. These are all objects or you may say these are all things.

Behaviour of objects:

Objects are separated from one another. They have their own characteristics and existence. Their unique identity makes them independently different from other objects. If there are two mugs placed before you. It is not necessary they are same. Their unique characteristics, attributes and behaviour can be entirely different from each other. This makes them two different objects. There should be no complexity in dealing with objects. An apple is an object, so is an aircraft, so is an iPhone or flowers or glasses and the list is endless. All are objects. But what makes them very different from each other is the way they behave and their individual attributes. One object might contain other objects as well.

There is no point in getting perplexed among these objects because these are all real objects and we have already known a lot about their characteristics which gives an elucidate understanding in their separateness. They have inherent properties that describe them.

Take an example:

A mug can be full or empty. An apple can be green or red. A tree can be short or tall. A lamp can be off or on. These are called the attributes of any object, things like color, weight, and size. They describe the current state of an object and the state of one object is independent of another. When you turn one lamp off, it does not mean that all the lamps in the world will be turned off.

Most objects have multiple attributes. A mug can be full or empty or the other state could be it is half empty or half full. At the same time it could be black or white or blue or some other color. It could be small or large. The behaviour of the real world objects are varying. A telephone can ring and an airplane can fly. The behaviour is specific to the type of object it is. An apple cannot ring and a telephone cannot fly.

Conclusion:

The point to remember here is the three things: identity, attributes and behaviour. They are one and the same thing that describe an object in an object-oriented programming language. Objects in a computer program are self-contained. Their identities separate them from other objects. They also have their own attributes. This information describes their current state or the things they are efficient enough to do.

# Analysis on real world objects:

You might be wondering what are actually real world objects. The real world objects tend to only use the word object for things that you can see and touch. In computing you can take it further. In a computer program you often make use of objects that represent real world items like car, house, apple or anything of this sort. But a date, a time or a bank account could also be an object even though you can't touch and hold a bank account in real life. But it is still a well-defined idea and even in real life it meets our definition of object. It is having an identity. One bank account is different from another bank account. It has attributes and data that describe its current state. An account number, a balance, an account holder name all have their own behaviour. You can deposit to a bank account, you can withdraw from it, you can also open it or close it. It can be concluded from this that though they are not physical items but still can be described from their behaviour. Similarly, objects in a computer program are just the things which are having a visual appearance on the computer screen.

Undoubtedly, buttons, images and spaceships can all be objects but invisible things like a timer or an array can also be treated as objects. So don't just focus purely on physical items or visible items when you are working with objects in a computer program. If you're new to Object-Oriented Design, it can be a little challenging for you to figure out if something in your application is a new potential object.

It's quite easy when your application needs something like car, employee or document. But it's not that easy when you're building an event management application. Can an event be an object? One way to find out is to ask if it's a noun. We have read in primary classes that nouns aren't just physical things, but people, places, and ideas or concepts. The other way could be put the word "the" in front of it. The mug, the apple, the car or the television; no doubt they are objects. But also the bank account, the time, the date or the event; these also work.

# Reviewing object-oriented languages

We've seen earlier also that object-oriented programming is above all a concept. There has been a lot of discussion over pure object-oriented language in deciding what languages best meet that definition. You should identify beforehand if the language supports the creation of objects. Words like polymorphism, encapsulation, inheritance and abstraction are the terms associated with object-oriented languages. What is important to know here are not the above mentioned terms but to know what the current state of object is.

Object-oriented programming has been such a successful idea that all the languages except one employ it. C is not an object-oriented language rather a procedural-oriented language. It predates the time of object-oriented programming came into existence. But the advanced version of C is C++; C++ is object-oriented. It has the original name of C with classes.

Objective-C is also just C with additions to support classes and objects. C# and Java are both languages that extract a lot from C and add object orientation. On the weaker sides of things, Perl was not originally an object-oriented language but it support some features. We've already studied; JavaScript is object-oriented loosely and the same is PHP and Python. Ruby is the purest object-oriented language here. Whenever you begin to program in C, the thing to bear in mind is to get familiar with the type of language and start figuring out what built-in classes exist in it.

The best thing working in object-oriented programming with a lot of existing classes is that somebody else has already written the behaviour that you don't have to. In JavaScript we've gone through some examples having classes that depict simple things like arrays and dates. While working with languages like Objective-C, Java, and C #; classes are there to represent text boxes, images and buttons. Moreover, these can be used for files, video players and cryptography functionality. In fact almost for anything else that you can think of.

12

Memory management across languages

# What is memory?

The thing we haven't discussed yet in detail is memory. Usually after creating the variables and objects and using them up; we forget about them. But actually this is not the case always. In many programming languages, you can't just create an object, use it and forget then after. It is important to manage the memory that the object uses because that manage the lifetime of that object.

How to allocate memory to the object?

If you go through some pseudo code examples, you would realize that instead of just creating an object; firstly it is required to manually allocate an area of memory. You will have to grasp a portion of RAM implying that you are using. You can create your object and then point it to that area of memory where you want to store it. This simply indicates that is the portion of memory you'll be utilizing. That's where your data is being stored. You can use a reference variable called a pointer for that object. This will help you out to call methods of that object and access its properties.

At the same time you should also be aware of what all things are no longer used. If that memory is no longer used to you then you should free that memory. It's not that difficult as it might seem to. When you start passing through these objects, you start calling functions and finally have a long lived program. This can get a bit difficult. A very common mistake noticed is you allocate some memory to the object you created then after using you forget it forever. The reason behind this is that you don't need that object anymore. The point to mark here is that you should always remember to free the memory. Sometimes you think you have made the memory free but it has not probably. This gives you a memory leak. It's not a big problem if you have done it once. But if next time you create a long-lived program that have thousands of objects and when you run the program, it's going to get slower and slower and take up more and more memory. This can even crash your program. The memory leak isn't the only problem you can face.

Take an example:

Let's go back to the first object whose memory you have already freed up. There might be a possibility where a variable points to that area of memory. This is called a pointer. If you try and use that variable because you think the object still exists but actually it doesn't. This actually called a dangling pointer. This can make your program to crash. That is why memory management is important and a bit difficult code to write. The difficulty level has risen because with more high-level languages are evolving; there are different methods for dealing with it.

# Memory management in low & high-level languages:

We've have already learnt about low-level and high-level languages in the earlier chapters. The languages like assembly language and C are quite close to the machine code. You need to learn a lot about how the machine operates. Whereas, in languages like Java, C# and VB.NET; you are not needed to know about the machine code. If you're working with assembly language and C, you will have to do a lot of manual work to allocate and free areas of memory that you've used.

As you start to get more into modern high-level languages, there are several techniques for dealing with it. Objective-C and C++ can choose to use something called reference counting. It is preferable to manual memory management and allows keeping a counter on who is using the object. Rather than manually freeing the memory, you can just allow the system to free it up when it realizes that counter has reached 0. When you switch over to languages like Java, C# and VB.NET; there is a memory management technique called garbage collection.

Rather than keeping track of individual objects, the system itself keeps the track of how much memory your application is using. It also keeps scanning through all your objects and find out which ones are still relevant and which ones are still being used up. Suppose if it sweeps through a thousand objects, clearing up 500 of them and finally leaving 500 of them around. This is regarded as garbage collection because it fritters away the unused objects and saves the memory. But it doesn't happen all the time. There is no surety when it is going to happen. As a programmer when you're dealing with these languages, sometimes you can suggest to the garbage collector that it is a good time to go and clear up areas of memory. But it is not required to work on the individual level of the individual objects. Further when you get into more scripting languages, it becomes completely automatic. You have no control over when memory could be reclaimed. But the issue is the more automatic it is, it becomes slower and less efficient it is.

Writing manual memory management code is tiresome and difficult. If you are able to do it absolutely the right way then it will lead to the most efficient use of memory. It's your primary focus then you'll have to look for languages that allow you to do manual memory management. The importance of memory management was a prior concern a couple of decades ago as compared to the present world. Therefore, years back the higher level languages employing memory management features like garbage collection holds a lot of importance and could efficiently create code and thus programs worked faster.

# Introduction to algorithms

You often come across a term in programming called an algorithm. It sounds similar to a program itself. Algorithms are sequential steps to accomplish some task. But in terms of programming, it is considered as a small procedure or a part of the program rather than the whole program itself. Perhaps, it is just a function. It performs a specific task. There are many different ways to accomplish the same task so there are many different algorithms.

An algorithm is a series of steps to accomplish a task.

Take an example: understanding concept of bubble sort

Suppose you've a series of numbers which you need to sort. It could be 5 or 5000. There are several ways of accomplishing this task. Let's see through one of them. Let's take you want to compare two numbers at the same time. Take the first two numbers and compare them. If the first one is greater than the second, then flip them. Moving down the series, compare the next two. Again, if the first number is greater than the second, flip them again. In this particular case you'll have to move up again and compare the next two. Check out whether the first is greater than the second. Now you find out that it is greater. Scour through each number in the series step-by-step means that you have to scroll through the numbers individually. You can take the biggest number on the first pass and movie down and then compare it to the number first passed. When you get to the end of this first pass, you reach the highest number is at the end. But still they are not in order. You need to make another pass, go back to the start and compare those two numbers. If the first one is higher than the second, you will flip them. This time you need not to go all the way to the end because you've already bubbled up the highest number. You will notice that you have reached the last number. Quickly you can return to the start and compare the numbers. But you don't need to flip those two. After multiple passes, you won't need to flip anymore. They're all in order. This is referred to as a bubble sort. This is a simple sorting algorithm.

You can make multiple passes and bubble the larger numbers up to the top of the list. Let's now understand this by the help of a pseudo code. You can write a bubble sort in just a few lines of code. It doesn't matter whether you feed five numbers into it or 5000. It's a simple straightforward algorithm but unfortunately, bubble sorts are not so efficient enough. If you have to work with large lists of data, then bubble sort doesn't produce an efficient result.

with list of items

repeat

swapped = false

for i = 0 to (list.length \- 1 )

if list[i] > list[i+1] then

swap ( list[i], list[i+1] )

swapped = true

end if

end for

until not swapped

Now you might be thinking if there are other ways to perform this task. To some extent it also depends on how long the list is. There are many sorts like bubble sorts, heap sorts, quick sorts, insertion sort, merge, selection, permutation sorts and these are just some of the best-known and most prominent sorting algorithms. There are many more than this. The best thing now-a-days is that in most languages you'll find sorting functions are already built into the language. While working with arrays or other collections, you can expect them to have built-in sort functionality to them.

It's not necessary that the simplest algorithms which you can write well are the most efficient one. The most efficient algorithms can be very difficult to write, hard to understand and maintain. This is one reason why computer programming has often been called an art rather than a science. If the same problem is given to ten experienced programmers then it is likely to get 10 completely different solutions. The point is there is not just one way to solve a problem. There can always be ways to betterment and improvising the older one. Many a times while programming you might fall upon problems to decide between ease of use, development and speed.

# Introduction to multithreading

You must have seen the operating system running multiple programs at the same time. This is referred to as multitasking. The complete concept of performing multiple things inside one program is called multithreading. You must have come across multithreading many times while working on your computer. It keeps your program responsive; specifically in desktop or mobile applications with a graphical user interface.

How multithreading works?

You must have interacted with programs where you click a button and it seems to make the application freeze and then a few seconds later come back. Multithreading is designed to get you past that. Your program has undergone a main thread of execution by default. What happens is all your code runs on one thread. This is like a conveyor belt taking care of instruction after instruction.

Let's take an example:

Call a function but the way you used to be earlier. You'll have to jump into that function on the main thread, call it and tell it to start on another thread which is a custom thread. Your main thread continues processing and by the time the secondary thread has another task to do.

Problem with multithreading:

Nevertheless, there are a couple of things to be cognizant of. The most challenging thing before multiple threads is that it has to compete for the same resources. It would be a less good thing for two different threads to be saving the same file. Let's see through an example. The problem can arise when you use the same variable to keep track of a counter. There are few restrictions when working with multiple threads. Any variable made on a custom thread can be limited to that thread only. It's very common when you'll find the main thread allowed to change the user interface. Though multithreading is usually found in a general purpose programming language, but you'll find it in all major desktop and mobile programming environments.

13

Most renowned languages

# Introducing C language:

The most influential language C was invented in the early `70s at Bell Labs and it still in fabulous use around the world. C has influenced many renowned languages like C++, C# and Objective-C. Also languages like Perl and PHP owe a remarkable amount to C. C is a pure structured language; also known as non-object oriented language.

It's neither about classes nor objects. It is a purely low level language that works with manual memory management. It is a compiled language which strongly typed in the sense that you just don't create generic variables rather you create variables of type integer or float or Boolean values. But getting started with C language is not that difficult as it seems unless you're getting too detailed with the language.

Where C language can be employed?

C language is employed in almost everything. But probably the majority of the use these days is in more advanced situations like in games, building 3D engine and in building embedded systems. Writing programs that are actually saved onto a DSP chip or writing operating systems. You'll even find C being used to build compilers for other languages.

If you want to build desktop apps or mobile app or web applications, where you're looking for a high productivity environment, then C language can be a good choice.

If you're looking for an environment which makes your program run fast and keeps it compact; then C language can be a good catch. You just have to. But you should be able to recognize the basic structure of it. It uses the curly braces to surround code blocks. It uses the semicolon at the end of the line. It uses the two forward slash for the comment. When you create variables in C, you write it like int X not var X. This is because you're creating an integer variable or a character variable, so you need to be specific about the kind of data that you're working with.

Functions in C:

Functions are also employed in C. You don't use the function as a keyword. In actual fact, the word 'main' here indicates that this is the single most important function in a C program and in fact, in almost all C-based languages. 'main' here is the name of a function. It's the function where the program begins. This is how C and most C-based languages know where to start. There's a block of code with the word 'main' attached to it and a very common thing that you'll notice in a C program is a statement like 'include'.

#include <stdio.h>

// this is a comment

int main (void) {

int x;

x = calculateSomeValue ( ) ;

printf( "Hello\n" ) ;

}

As you'll start exploring more languages, you'll figure out several things like that. If you talk about general purpose languages it's very common to link to external libraries. Basically what happens here is this file encapsulates a whole bunch of code that somebody else wrote. These functions are very useful and you can use them in your program to get it link to it. As you get more detailed into the most general purpose languages, you'll start noticing that it's less about the language itself and more about all these external files also called libraries of code that you can get your program to link up.

How to start up in C?

Let's have a look at it and see how to get started in C. C is one of the standard languages which do not ask for many things. You need a text editor and a compiler. You'll often find C compilers built into programmers' text editors and other IDEs. This is because C predates the web. There are many websites to fetch the information about it. Box:

The classic compiler is called as GCC. It's an Open Source compiler used by a lot of different IDEs or Integrated Development Environments.

You can refer to gcc.gnu.org and this one of the best place to find some central authoritative information.

# The Java world

The next language we're going to have a look at is Java. This is profoundly influenced by C but came into highlights over 20 years later. This was launched in 1995 and was developed by Sun Microsystems. It is a purely object-oriented language. It's all about classes and objects and it comes up with a vast library called the Java Class Library. It effectually means a bunch of prewritten code that you don't have to write. There is a colossal amount of functionality already built-in there for you. It is a high-level language. You don't have to worry too much with memory management. It has a built-in garbage collector.

Concept of bytecode and JVM:

Java is a language that uses the hybrid compilation model. Neither it is compiled nor interpreted. It compiles and sends it to what is called bytecode. It is a very cross-platform language. There was adage given by Sun Microsystems was "write once, run anywhere". As it is a partially interpreted language the users have to have the interpreter for Java on their machine. And this came to be called as the Java Virtual Machine or JVM. You must have noticed that some applications on your machine require to install Java. That is why it is famous for desktop applications. You can write a desktop application in Java and then run it on a Mac or on a Windows PC or on a Linux box.

Of late, one of the biggest endorsements in Java is for developing mobile applications that run on the Android platform. So it's a C-based language.

Take an example:

The thing which pops up again is the word 'main'. This is how you tell a Java program where to begin. Let's see through an example. You have intmyInt = 55 line. Here you're using the word int. rather than a general variable, it's an integer variable. The line that begins System.out.println is how you output the words "Hello World!" on the screen. But because this is an object- oriented language and in Java everything is in a class. That's why you have to surround the code that you want in this class HelloWorldApp.

class HelloWorldApp {

//another main method!

public static void main (string[] args) {

int myInt = 55 ;

System.out.printin( "Hello World!" );

}

}

It might seem to be a bit strange but remember most of the development environment you use, provides this framework for you. You just have to get in and fill in the gaps. And as it was mentioned before, although there is a passing similarity because of the curly braces and semicolons; Java is not JavaScript. The languages have very little to do with each other.

If you're developing an interest to get started with this language then you're probably looking to get a full IDE, a full development environment for Java.

The two most popular among IDEs are Eclipse and NetBeans. This is because this language is owned by Sun and thus developed java.sun.com as the most authoritative website to go to. Sun is now owned by Oracle. You can easily direct it to find a lot of information by tutorials available giving information on how to get started and the basics of starting to work with Java.

# .NET languages: C# and Visual Basic .NET

Let's talk about two languages: C# and Visual Basic.NET. These are the two flagship languages if you're developing them on the Microsoft platform. We're taking a look at both the languages at the same time because although they do look different but their usage and approach are almost identical. These two languages were launched in 2003 by Microsoft. But Visual Basic has a longer history than that. It was reinvented at that time when Microsoft released the .NET framework.

Basics of C# and Visual Basic .NET

The vast library of prewritten code contains a huge amount of functionality that you can tap into if you use either of these two languages. Both of them are object oriented. They make use of classes and objects and both of them share the same characteristics. They are high-level and strongly typed languages. They use garbage collection so you don't have to worry about memory management and use the hybrid compilation model like Java does.

Similarities to Java:

The important thing to mark here is that neither they strictly compiled nor strictly interpreted. They go halfway. When you compile a C# or a VB.NET application, it will compile to what is called Intermediate Language or Microsoft Intermediate Language. This means that it can be distributed across a variety of different machines with different CPUs. Now each machine will take it the finishing step to move down to the machine code. Just the same way as Java requires the Java Virtual Machine on every computer which runs a Java program; .NET languages require .NET Runtime to be installed on every machine.

Resemblance to ASP.NET:

Unsurprisingly, they are closely associated with developing on the Microsoft platform, no matter whether that is Windows server or a Windows desktop system or may be a Windows phone. All this can be done with the help of .NET languages. They both have the same proficiencies for building desktop applications. You can also build dynamic websites using these languages. When you think of building a website on the Microsoft platform, it is generally fall under the term ASP.NET.

What actually ASP.NET denotes is that you're building a dynamic, smart, interactive website using Microsoft technology. When you're doing it, you're actually employing either C# or VB.NET. These languages can be used for developing mobile applications that work on the Windows phone operating system. So you can say these languages are closely associated with the Microsoft world. You shouldn't wonder when you hear that C# is not surprisingly a C- based language. Probably it seems to be closer to Java as well. It makes use of the curly braces, the semicolons to end the statement and the word 'main'. This is how you inform the .NET Runtime where your program begins.

Resemblance to Java:

You might be wondering how to execute the first line. In this particular case, its System dot Console dot WriteLine. You need not to worry about the syntax. This is just a simple way to get the text Hello World out to the console by flaunting up a message.

Take an example:

As you've seen in Java, the whole thing is enfolded with this phrase public class Hello1. The reason behind this is C# is a thoroughly object oriented language and everything inside it falls under a class.

// Hello1.cs

public class Hello1

{

public static void Main ( )

{

System.Console.WriteLine("Hello, World!");

}

}

Resemblance to Pascal:

To create even the simplest application, you just have to have a class and then call 'main'. This is the line you'll have to execute. You might have noticed that the use of curly braces is a bit different here. This is because in C#, the common usage of them is to line them up so that each on their own line matches the opening and closing curly braces. This is referred to as Pascal or Allman style. It has become the accepted style in the C# world. C# is whitespace insensitive same as in C-based languages.

Similarities in C# and Visual Basic.NET:

Coming to Visual Basic.NET, this is not a C-based language. You won't see the semicolons at the end of a statement or the curly braces. But you'll see 'main' to be used here. This tells what's the actual code is and how to run when this program begins.

Particularly, in this case you can't mark out where blocks of code begin and end with curly braces. You will have to make use of 'if' and 'end if'. If there is a Sub also known as subroutine like a function, you can make use of an End Sub or a Module. You also have this System dot Console dot WriteLine. This line is exactly the same as you've seen in C# except for the semicolon at the end of the line that is required in C#. Though the overall format of the language is different but the statements that you execute is in a .NET language. This is identical to each other as you've the same libraries and functionality available to you.

Module Module1

Sub Main ( )

System.Console.WriteLine("Hello, World!")

End Sub

End Module

If you're able to code well in C#, you can easily read VB.NET. The point here is how to get started. Microsoft has made it fairly easy to do this. Go and download Visual Studio. This is their flagship integrated development environment and you'll notice that there are several different versions of which include versions that are completely free. This is referred to as the Visual Studio Express editions. Visual Studio includes a text editor, a compiler, a debugging tool and all the things that you need to get started with any of these languages.

There are versions of Visual Studio that are commercial and cost several thousand bucks. This is how you can start up with these languages, experiment and play around. You can even create websites and desktop applications without spending anything. If you're keen to know more about it, take a look at microsoft.com/express.

# Ruby

Let's have a look at one of the newer languages in the software world. It was developed in Japan in the mid of 1990s. Many people consider it as a very pure object oriented language. Working in Ruby, you'll find everything as an object, even variables that might be considered primitives in other languages like Booleans or integers. Everything is an object. It's a high-level garbage collected language. You don't need to worry about memory management and it's completely interpreted. You don't need a compiler for Ruby rather you need an interpreter.

It doesn't compile to intermediate language like Java or the .NET languages. Most people find it very easy to approach. You don't require a lot of prerequisite knowledge to get started with Ruby. It's fairly friendly for beginners. Now the question arises for what it is used. We know that it is a cross-platform language. There are installers and interpreters available on every operating system. You'll also find it built into the last few versions of Mac OS X. It's has probably become the most famous for its use in what's called Ruby on Rails.

This is a well-designed web framework that uses the Ruby language. Along with this ruby has come up as a great language for writing small utilities and text processing applications on the desktop. You might be wondering how it appears. Obviously, it's not a C based language. You don't even need a main section.

Take an example:

Let's take an example creating a program in Ruby. Put the string as "Hello, world!". No need to put any semicolon at the end of the line, but this doesn't really tell us too much about it. Add a few more lines here. Now define a function here. You can use comments but not with the two forward slashes; rather you can use the pound sign or hash sign. After creating this function or method, use the word 'def' for defines. You're calling this welcome saying it takes a parameter of name and then it's going to output hello comma, whatever the name is. You don't use curly braces to mark the end of the function. You can use the word 'end' instead and then below it write x = bob.

puts "Hello, world!"

# this is a comment

def welcome ( name )

puts "hello, #{ name }"

end

x = "bob"

welcome ( x )

This is how you can create a variable which is a string and then you can call this function or method saying welcome and passing in x. Again, you don't have to worry about memorizing syntax. The point here is that you should focus on the overall structure. Ruby is a fairly compact language to get started with easily.

If you're working on a Mac you should have the Ruby interpreter. There are several different editors that you might use like TextMate and RubyMine on the Mac, Aptana is cross-platform. You can refer to the website rubyonrails.org, which is all about that web based framework that uses the Ruby language. Another website is ruby-lang.org. Both of these have fantastic resources to get started with Ruby; either the Ruby language by itself or as a web based framework.

# Python

Next, let's talk a little bit about Python. This is a language that's often regarded same as Ruby as it's a very clean and concise object oriented language. You can easily figure out that it's another language that comes with a really large library. In fact, this is one of the benefits of this language. There is a whole bunch of prewritten functionality that you can just type into. Again, same as in Ruby, it is an interpreted language. It has a garbage collection property as well. You don't have to worry about compilers and neither about memory management.

Usage of Python:

One of the great things about Python is that it's a totally cross-platform language. There are Python interpreters on every platform that are well supported. It's a very simple and easy language to build web applications with. It can be tied perfectly with the Apache web server and it has lots of uses as an embedded scripting language inside other applications. It uses a great deal for building applications and web apps by companies like Google and Yahoo!

Similarities in Python & Ruby:

Just like Ruby, it can also have one line statement like program. Neither you need a section called main nor do you need the semicolons. This is perfectly acceptable. But it doesn't give us the actual understanding of it. Let's add a few more lines. Similarly as in Ruby, you can use the pound sign and hash mark as a comment and 'def' for define which is actually describing a function.

Why is Python better than Ruby?

You'll find an interesting thing here. Define a function called sayhello that takes one parameter of name. Now you might wonder how it is going to end. Python is interesting because it is one of the languages that do pay attention to indentation. You don't use the curly brace to mark the end of a function. The lines are just indented inside the function. In this case, it's just one line. It says print 'hello' and follows it with the name parameter. Moving down you can just call this function. Python knows the function has ended because there are no more indented lines. It looks a little different to Ruby where you used either the word end or those curly braces in other languages. But it's leads to a very clean readable syntax.

print 'Hello, World!'

# this is a comment

def sayhello( name ):

print 'hello', name

sayhello('bob')

Dissimilarities to Ruby:

Unlike Ruby, this is a very concise readable language that's easy to get started with. There are several IDEs and editors that support Python. Two common ones are the Eclipse IDE with the extension PyDev that helps for Python development and Komodo as well. Although you'll find many programmers' text editors also supports Python.

Since python has found a great use as per information security folks, you have already created a course on Python with Eclipse and InfoSec. Infosec stands for information security.

Python interpreters are available on every platform and actually built into recent additions of Mac OS X also. The single best resource for getting started is through the website python.org. This is the official Python website and has a great amount of installers, help, and tutorials which helps you out to deal with this language.

# Objective-C

Objective-C is one of the older languages on the list. It was invented in the early 80s as an object oriented version of C. It is really the C language with some extra stuff added to it. That extra stuff makes it object-oriented. One of the benefits of using Objective-C is, it comes with a large library referred to as Cocoa. It is a compiled language and not interpreted. It doesn't uses intermediate bytecode.

Dissimilarities from other languages:

Although it's a high-level language, but it is more aware about memory management unlike Java or the .NET languages. It uses reference counting which keeps track of the objects that you have created and whether you're done with them or not. Advancement in the language means that it has become less problematic to work with. But it doesn't mean that it's a friendly language for beginners. You really need to have an intermediate level of skill to be messing with Objective-C.

Why Objective-C is so popular?

The big reason behind the augmenting popularity of Objective-C is that this is the language used for Apple development whether that's iOS development like the iPhone or the iPod or a Macintosh desktop development. It's the language that was used to build the OS X operating system.

Significance of the word 'NS':

We've already learnt a lot about it in previous chapters. We have the curly braces and semicolons at the end of the line. However, there are few things which are not shared among other languages and makes it quite different from others. We still have the main section here which denotes where our program begins. While working with C you'll notice that there are a lot of words that begin with NS and this is really an old history lesson. Objective-C was used by the company NeXTstep to build their operating system. Later on it was bought by Apple and since then it extracted out a lot of things from it. When you see examples of programs written in Objective-C, you will come across this NS letter all over the place.

#import <Foundation/Foundation.h>

int main (int argc, const char *argv[ ] ) {

NSAutoreleasePool *pool = [ [ NSAutoreleasePool alloc ] init]

NSLog (@"Hello world\n") ;

[pool drain] ;

return 0 ;

}

Basic features of Objective-C:

You will also see a lot of square brackets being used. We've seen earlier that the square brackets denote arrays, but here that's not the case. You shouldn't get confused it by considering it as C. Objective-C is actually built on top of the C language which means it is C with extra stuff. The way that you start to use the object- oriented features is that you need to mark them out by using square brackets. This is why Objective-C can appear a little strange to people who are used to other languages.

Another odd feature that is very common to come across is the @ sign in front of a string. That's how you tell Objective-C that you are denoting a string object in that language. Same as C you also have a lot of import statements. One of the powers of using Objective-C is that you can link to a bunch of big libraries full of interesting code that you can get access to. Objective-C has been used so long by Apple that they've built huge amounts of pre-written code. These can be used to build Macintosh desktop applications, iPhone applications and these are enfolded under the general name of Cocoa. If you're interested in writing applications that run natively on Apple hardware, then this is the language you should look for.

If you're interested to get more detailed about the language, there is one key editor or IDE and that is XCode. This is Apple's own integrated development environment for building desktop applications or iPad or iPhone applications or even just simple command line applications. You can refer to this key website developer.apple.com. Here you'll find downloads, reference guides, tutorials and a lot of information about getting started with Objective-C.

# Libraries and frameworks

If you've been through some of the language introduction videos you must have seen a common thread. Till now you've seen more about the benefits of the libraries rather the language. These are sometimes called libraries. They are wrapped up into the term framework instead. But it's one and the same thing. Huge amounts of code are written, tested already and ready to link to and use. C# in VB.NET has the .NET framework. With Java, you have seen the Java Class Library.

Libraries in programming languages:

With Objective-C, you have Cocoa or Cocoa Touch depending on if you're focused on the desktop or on the iPhone and iPod. Python also have the standard library. Another thing that programmers know and non-programmers don't is not about the language. It's about the libraries. When you are learning C#, you might wonder if there was something that can help you to connect with database. It was the .NET framework.

While experimenting with Objective-C, you might have come across a built-in video player class for the iPhone. It's already been written by Apple and even there in the Cocoa Touch framework. You can link to it and use it.

If you're using Python and your program needs to be save in a file and wants to unzip that file up. You'll find that in the Python Standard Library.

As a beginner when you fall upon hundreds or even thousands of prewritten classes available to the language, you shouldn't worry because you need to memorize them. It's like being in a real library. The point is not that you must read every book. The point is to navigate through the stacks and find whether what you're looking for exists or not and if so, how do you get to it. You can refer to reference guides anytime usually on websites whenever you face any problem.

Concept of packages in Java:

Microsoft has the .NET Framework Class Library where you can actually start scrolling through all these different areas. They break their classes down into different places like classes that deal with printing. While working with Java, it's the same case. These are grouped together into what are called packages. You have packages to deal with math and security. You can have packages dealing with the sound and midi, which themselves break down into classes which further deals with instruments or tracks.

Python Standard Library and the iOS Developer Library have their own set of classes. That's why learning more about the language is afr more important than focusing on the syntax.

86 | Page

