Sunday 31 March 2013


Introduction to programming concepts

Computers belonging to different domains are used to perform a variety of tasks. Do you know how a computer is able to perform different tasks?
To carry out the work, the computer input, process and adhere to the basic principle OUYPUT. Computer information in a set of instructions called a program, process, and production activities is needed.
In this chapter input, process, output requirements and the introduction of a computer. The instructions in a computer program and died PROGRMMING explains the role of languages​​  In addition, it describes various tools to solve the problem solving.
  Input process and output
You might have noticed computer being used at airline reservation counters, shops, restaurants, and various other locations. At each of these places, a user enters some values in the computer and the computer generates an output, which is, either displayed on the computer screen or printed on a paper.
Let us consider the example of an airline reservation counter. When you want to resrve a seat on particular flight, you provide information about your requirements, such as the destination, the data and time of your departure, and the class in which a booking is required. The executive at the reservation counter enters this information in a computer. The details regarding the availability of tickets are then displayed on the screen.
The preceding automated process is not carried out as one activity. It is broken into a set of activities that are carried out in separate phases. Let us see the phases involved and the process followed for each of the tasks.
              Phases
To undersand what happens when you enter some values in a computer, let us break the entire set of activities into separate phases.
Consider the example of the airline reservation counter. In the first phase, flight requirements are keyed into the computer. This phase is called the input phase. The flight requirement information is then processed to determine whether seats are availble on the particular flight is known as the processphase. Once the processing is complete, the result is displayed on the computer screen, indicating the status of seat availability. This phase is called the output phase.
The cycle of activities performed by a computer is also known as the input - process- output (I-P-O) cycle.
I-P-O Cycle
A computer consists of several componets, such as a keyboard, mouse, mouse, monitor, printer, and central processing unit (CPU). Each computer participates in any one of the phases: process, or output. For example, the keyboard and mouse are used for input. The CPU and memory inside the CPU are used for processing. The monitor and printer are used for output. Following figure depicts the (I-P-O) cycle.

Programs and programming languages
Have you ever wondered how a computer:
Ø  Remembers the steps to be followed to process reservation requests
Ø  Manages to calculate your shopping bills at the local store
Ø  Generates your report card at school
Is a computer an all-knowing machine? Do you have to buy a different computer for each of the preceding activities? The answer to the last two questions is ‘No’.
It is not an all-knowing machine, and you do not require a separate computer for each of these activities.
Then, how does a computer function? A computer is an electronic device. It needs a set of instructions called a program to perform the I-P-O cycle. A program needs to be written in a specific language, called a programming language.
Let us discuss programs and programming languages in detail.
Programs
All of us perform a number of tasks in our day-to-day lives. Some of the tasks that we perform are:
Ø  Crossing the traffic signal while you are in a car
Ø  Managing your budget
Ø  Troubleshooting why your printer is not responding
Ø  Forming a strategy to reach the next level of a computer game
To perform these tasks, you follow a step-by-step procedure. For example, while driving a can, you comply with the following sequence of steps to cross a traffic signal:
1.       Approach the light.
2.       If the light is red, you will stop.
3.       If the light is yellow, you will slow down and then, stop.
4.       Otherwise, the light will be green and continue driving.


In the same way, a computer uses a step-by-step procedure to perform any task. A computer is designed to accept an input, process it, and generate an output. However, you need to provide a set of instructions that specify:
Ø  The kind of input that will be provided. For example, in the case of reservation requests, the flight date, flight time, class, and destination will be some of the input.
Ø  The Processing that needs to be done. For example, accepting the values, checking for availability of seats, and displaying results will be some of the processes.
Therefore, for each job that you want the computer to perform, you require a separate program. Depending upon the requirements, instructions in a program can be:
Ø  Sequential: instructions that are executed one after the other.
Decision making: instructions that evaluate an expression (relation or condition) first and then, depending upon whether the value of the expression is true or false, the control is transferred to a particular statement
Any real-life problem that you solve with the help of a computer will consist of a number of small jobs. Therefore, to solve such a problem, you have a number of programs that together form an application. For example, a gaming application might have the following two programs:
Ø  Program to run the game.
Ø  Program to record the scores of players.
Programming languages
A computer is made up of a number of electronic components. An electronic component can be either in an ON state or in an OFF state. The ON state is represented by 1, and the OFF state is represented by 0. This implies that a computer can understand only 0s and instructions. This collection is called machine language code or simply machine code. For example, the following table depicts machine code that can be used to represent the commands, ADD and SUBTRACT.
Command
Machine code
ADD
1010000100
SUBTRACT
1010001000
The machine code of the ADD and SUBTRACT commands
However, it is difficult for anybody to remember instructions in the form of machine language code. Therefore, we use high-level programming languages to write programs. A high-level programming language consists of a set of instructions, which are represented using simple English words. Therefore, when you want the computer to display the output on the screen, you type an instruction like ‘WRITE NO SCREEN’ and not ‘00100000’. There are many high-level programming languages available, such as C, C++, and java.
All language have a vocabulary, which is a list of words that have specific meanings in that language. Languages also have their own grammar rules, which state the rules for combining words to form sentences. The vocabulary of programming languages is known as the set of keywords of that language, and the grammar is known as the syntax. For example, in a programming language, you can the following statement to display the message, “MY first program”:
     Print (“MY first program”);
In the preceding statement, print can be referred to as a keyword used in that programming language to display a text on the screen. Further, as per the syntax of programming language, the text that needs to be displayed is semicolon.
Compilers
Can computers directly interpret the instructions written in any programming language? NO, they cannot. Then, how do you ensure a computer interprets the instructions given in a program? For this purpose, a special program known as a compiler is used. Consider a situation. You are in a foreign country and trying to ask directions form a person who does not know your language. How would you understand the directions?
You would need a person who can translate the direction information into English or any other language that you can undersand. Similarly, you need a translator to convert the instructions written in a programming language into the machine language.
A computer is a special program  that processes the statements written in a particular programming language and converts them into the machine language, at one go. Like everything else in the computer, the compiler also follows the I-P-O cycle. It takes the programming language instructions as an input. It then, processes these instructions to convert them into the machine language. These instructions can then be executed by the computer. This process of conversion is called compilation.  
Tools used in problem solving
As seen, a program is a set of instructions to solve a particular problem. In the process of writing a program, you need to derive a technique to solve the problem. After deriving the technique, you need to represent the technique in a way that is helpful in writing the program easily. For this, you can various tools. The tools that you can use to represent the technique to solve a problem are:
a)      Algorithm
b)      Flowchart
c)       Pseudocode
Algorithm
A.      An algorithm is a sequence of steps required to solve a problem. It is a list of well-defined instructions to solve a problem. According to D.E. Knuth, a pioneer in the field of computer science, an algorithm has the following characteristics:
B.      An algorithm ends after a fixed number of steps.
C.      Each step in an algorithm clearly specifies the action on be performed.
D.      The steps in an algorithm specify basic operations. These operations can include calculations, input/output operations, and comparisons.
E.       An algorithm accepts the input data, in a defined format, before it can be processed.
F.       An algorithm generates one or more output after the input is processed. The resultant information termed as output can be displayed or stored for a future reference.
For example, when you approach a traffic signal while driving a vehicle, the algorithm to take adecision will be:
Step 1: start the algorithm.
Step 2: approach traffic light.
Step 3: If the light is red, stop.
Step 4: if the light is yellow, slow down and then, stop
Step 5: otherwise, the light is green, continue driving.
Step 6: end the algorithm.
An algorithm follows the I-P-O cycle to solve a problem. Here, the input is the color of the traffic light that is passed to your drain, after seeing the traffic light. Information about the color is processed in the brain. If the color is red, you need to stop. If the color is yellow, you need to slow down and then, stop. Otherwise, you need to continue driving. Here, your final action, after seeing the color, is the output.  
Consider another example where you want to withdraw a required amount from an ATM.
In this case, the algorithm will be.
     Step 1: start the algorithm.
     Step 2: insert your ATM card.
     Step 3: the ATM machine checks your card details.
     Step 4: enter the pin number.
Step 5: the ATM machine validates the pin number.
Step 6: press the cash with receipt button.
Step 7: select the amount you want to withdraw.
Step 8: collect your ATM card.
Step 9: the ATM machine counts the cash.
Step 10: collect the amount from the ATM machine.
Step 11: collect the statement from the ATM machine.
Step 12: end the algorithm.
Here, the input to withdraw a required amount from an ATM would be the ATM card, pin code number, and amount to withdraw. These inputs are that accepted, and the process of withdrawing the amount place. At the and of the process, the amount, which is the output, is withdrawn.
Consider another example where a television company may provide the following algorithm in the television manual to troubleshoot the ‘NO sound’ problem:
Step 1: start the algorithm.
Step 2: ensure that the mute button is not pressed.
Step 3: ensure that the desired volume is set.
Step 4: if the sound is still inaudible, call the television engineer.
Step 5: end the algorithm.
Flowchart
A flowchart is a graphical representation of an algorithm. It consists of a sat of symbols. Each symbol represents a specific kind of activity depicted in the algorithm. A typical flowchart would involve accepting instructions and data as inputs, processing these instructions and data and displaying the result as an output. The processing would involve the computations and the decision that are being taken.
For example, the following flowchart depicts how to take a decision when you approach a traffic signal while driving a vehicle.The flowchart to take a decision on a traffic signal

Advantages of flowchart
Flowchart offers many advantages. Some of these advantages are:
A.      Flowcharts help in analyzing the problems effectively.
B.      Flowcharts act as a guide during program development phase.
Disadvantages of flowchart
Although a flowchart provides several advantages, it has a few disadvantages as well. Some of these disadvantages are:
                                                               i.      A lengthy flowchart may extend over multiple pages, which reduces readability.
                                                             ii.      Drawing a flowchart using any graphical tool is a time-consuming process.
                                                            iii.      The changes made to a single step may cause redrawing the entire flowchart.
Pseudocode
A Pseudocode is a detailed yet readable description of what an algorithm must do. It is expressed in a formally styed natural language rather than in a programming language. A Pseudocode is used as an initial step in the process of developing. It provides the programming a detailed template for writing instructions in a specific programming language.
For example, the following Pseudocode shows the process of deciding the course of action when you approach a signal while driving a vehicle.
Pseudocode for deciding the course of action on a traffic signal
Begin
Character light, action
Accept light
If (light == ‘red’)
Begin
Action – ‘stop’
End
Else if (light == ‘yellow’)
              Begin
Action = ‘slow down and then stop’
                  End
Else
                     Begin
Action = ‘continue driving’
                End





1
Introduction to Programming in MATLAB
Summary
This lab will introduce you to the basic concepts of computer programming, including 
conditionals, loops, and functions through examples in MATLAB.
A. Math
B. Variables
C. Vectors and Matrices
D. Scripts
E. Conditionals
F. Loops
G. Functions
H. FizzBuzz
Required equipment
1) Matlab
Part A: Math
Matlab makes an excellent calculator. Try entering some basic math expressions at the 
prompt in the command window:
2 + 2
3 * 5
4 ^ 2
sqrt(9)
sin(pi/2) 
mod(7,3)
You may not be familiar with the last operation on that list. It is called modulus, or mod 
for short, and gives the remainder when the first number is divided by the second. 
Thus, 7 mod 3 would be 1, 4 mod 2 would be 0, etc. The modulus operator proves 
useful in several applications in computer programming.
Part B: Variables
Notice how when you enter an expression into MATLAB, it displays the results as 
something like this:
>> 2+2
ans = 
4
Whenever MATLAB performs an operation that returns a value, it automatically stores 
the result in a variable called “ans.” You should also see “ans” in the Workspace pane 
in the MATLAB window (it is usually in the top right). Try the following commands:
2 + 2
ans * 52
Notice how you can use the “ans” variable the same as if you had typed its value into 
the command instead. Of course, you are not limited to just the “ans” variable. You 
can create your own as well and give them any name you like. For example:
x = 4
y = 2 * x + 3
i = 10
Dog = 'Spot'
Notice how variables can store more than just numbers. They can also store text, as 
shown in the last example. Text, or a variable storing text, is referred to as a string. A 
string is really just a one-dimensional matrix of characters.
Part C: Vectors and Matrices
One of MATLAB’s strongest features is how easy it makes dealing with matrices. 
Matrices are entered into MATLAB as numbers surrounded by square brackets. 
Semicolons separate the rows of the matrix.
a = [ 1 2 ]
b = [ 1; 2 ]
C = [ 1 2; 3 4 ]
Individual elements of the matrix can be accessed like this:
a(1)
C(1,2)
Note that for a one-dimensional matrix (or vector), you only need one index in the 
parentheses. But for a two-dimensional matrix, you specify the index as row, column.
Matrix math and operations are easy as well.
d = C * b
inv(C)
transpose(a)
In addition to normal mathematical operations on matrices, you can also do elementwise operations. For example, this multiplies the first element of A by the first element 
of B, the second element of A by the second element of B, etc.
A = [ 1 2 3 ]
B = [ 4 5 6 ]
A .* B
You can also get the dimensions of a matrix with the size function:
[rows, columns] = size(A)
Part D: Scripts
So far, we have been entering every command in one by one at the prompt. This is fine 
for the simple examples so far, but when actually doing something non-trivial, you will 
need to create a script. From the file menu, go to New->Script. Name it whatever you 
want. Copy some of the code from parts A through C into the file then click the “Save 3
and Run” button (green arrow icon) in the toolbar. Notice how, in the command 
window, the output of every statement is displayed. Running commands from a script 
is the same as typing them in one by one, except in the script there is no delay between 
commands.
Part E: Conditionals
Conditional statements form the logic of a program. Nearly every program you write 
will have some kind of conditional in it. The simplest is the “if” statement. For example, 
to simulate a coin flip:
flip = randi(2); % Random number either 1 or 2
if flip == 1
disp('Heads')
end
if flip == 2
disp('Tails');
end
Copy and paste this code into a script and run it. The first line assigns a random 
integer, either 1 or 2, to the flip variable. The next line checks to see if flip is equal to 1. 
If so, it displays “Heads.” The “flip == 1” is the “condition” for the first if statement. If 
the condition is true, all code between the condition and the next “end” statement is 
executed. Otherwise, MATLAB skips to the end statement.
Note that “==” is used to check if two values (flip and 1 in this case) are equal. This is 
called the equality operator. Do not confuse this with the assignment operator (=),
which is used to assign values to variables. Equality is not the only condition that can 
be checked in an if statement. There are also:
== Equal to
~= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Notice the first line of the example above. All text following a % sign is referred to as 
“comments.” MATLAB skips over comments when running scripts. Thus, you can add 
any comments you want to your scripts, which is often helpful for explaining what a 
segment of code does.
The example above is not the only way to write this code. The flip variable will always
contain either 1 or 2. So if the first if statement is not true, then the second must be. 
Thus, we can rewrite the example above as:
flip = randi(2); % Random number either 1 or 2
if flip == 1
disp('Heads')
else
disp('Tails');
end4
Before we said that if the condition of an if statement is not true, MATLAB will skip to 
the next “end” statement. However, in the case of an if/else, if the condition is true, 
code between the if and else are executed. If the condition is false, code between the 
else and end is executed.
Conditionals with Strings
Strings cannot be compared using the same operators as numbers. If you try it, you 
will get something like the following:
>> 'Dog' == 'Dog'
ans =
1 1 1
>> 'Cat' == 'Rat'
ans =
0 1 1
Each character of the first string is compared to the corresponding character in the 
second string. If you try to compare strings of different lengths, you will get an error.
Instead, you must use the string comparison functions built in to MATLAB. Use the 
strcmp function to test if two strings are the same:
strcmp(string1, string2)
This will return true (1) if the strings are the same and false (0) if they are different.
Nested Conditionals
Conditionals can also be nested within each other. For example:
if A
% Code here run if A is true
else
if B
% Code here run if A is false and B is true
else
% Code here run if both A and B are false
end
end
The “elsif” statement can be used as shorthand for nested conditionals. The following 
is equivalent to the above:
if A
% Code here run if A is true
elsif B
% Code here run if A is false and B is true
else
% Code here run if both A and B are false
end
Multiple Conditions
An if statement can also check more than one condition at a time. The example below 
generates a random number on a range of 1 to n and checks to see if the number is in 
the middle one third of the range.5
n = 100;
r = randi(100);
if r >= n/3 && r <= 2*n/3
disp('Middle');
end
The “&&” in the condition is an “and” statement. In this case, the condition is only true 
if both “r >= n/3” and “r <= 2*n/3” are both true.
Likewise, an “or” statement ( || ) can be used to check if the number is outside the 
middle third.
n = 100;
r = randi(100);
if r < n/3 || r > 2*n/3
disp('Outside');
end
As usual though, there is more than one way to do this. If the number is outside the 
middle third, it is not in the middle third. Just like that last sentence says the same 
thing two different ways, there are multiple ways to say it in code. In this case, using 
the “not” operator (~).
n = 100;
r = randi(100);
if ~ ( r >= n/3 && r <= 2*n/3 )
disp('Outside');
end
The not operator simply inverts the truth-value of a condition. True becomes false and 
false becomes true.
Part F: Loops
Loops are another concept that make an appearance in 99% of programs. The basic 
idea is simple; a loop executes a block of code while a condition is true. This type of 
loop is called a “while” loop. For example, to create a 1x10 vector and fill it with values 
from 1 to 10:
v = zeros(1,10);
i = 1;
while i <= 10
v(i) = i;
i = i + 1;
end
v
Notice that the condition of the while loop depends on the variable i and also that i is 
updated inside the loop. This should almost always be the case. If no part of the 
condition is updated within the loop then once the loop starts it will never end. This is 
called an infinite loop. For example:
i = 1;
while i <= 10
disp(i);
end6
If you run this, you will notice the MATLAB prompt disappears and “Busy” is displayed 
on the status bar at the bottom of the screen. If you do accidentally (or intentionally) 
create an infinite loop, you can manually interrupt it by pressing Control+C. After doing 
this, you should see a message: “Operation terminated by user.”
You can use infinite loops in programs. However, if you do, you should make sure 
there is some condition that “breaks” the loop. For example:
v = zeros(1,10);
i = 1;
while true
v(i) = i;
i = i + 1;
if i > 10
break
end
end
v
This is an infinite loop because the condition is simply “true.” True is always true. 
Thus, the loop goes on forever. The “break” statement causes MATLAB to skip to the 
loop’s “end” statement.
For Loops
A “for” loop is a special case of a while loop. It is basically short hand for a loop that 
iterates over a range of values. The above example could be rewritten as:
v = zeros(1,10);
for i = 1:10
v(i) = i;
end
v
This has the advantage of being easier to read and having fewer lines to code.
Part G: Functions
Another key concept is the function. Functions allow you to split code into smaller 
segments that are each easily understood. For example, to calculate distance between 
two points (a point here being a 1x2 matrix):
function d = distance( pt1, pt2 )
d = sqrt( (pt2(1) - pt1(1))^2 + (pt2(2) - pt1(2))^2 );
end
The first line is the function declaration. It contains the name of the function (distance), 
the return value (or values) (d), and the arguments (pt1 and pt2). Now when you run the 
command:
n = distance([3 4],[0 0])
Matlab will run your distance function, assigning [3 4] to pt1 and [0 0] to pt2. The return 
value, d, will be stored in the variable n.7
Note that in MATLAB, all functions must be in their own script file and the name of the 
file must be the same as the name of the function.
Part H: FizzBuzz
Time to put all your newfound knowledge to the test. FizzBuzz has been used as an 
interview question to test basic programming ability. The task is to write a function 
that accepts a variable n and prints numbers from 1 to n. However, if a number is 
divisible by 3, the function should print ‘Fizz’ instead of the number. If a number is 
divisible by 5, ‘Buzz’ should be printed instead. And if the number is divisible by both 3 
and 5, ‘FizzBuzz’ should be printed.

No comments:

Post a Comment