Showing posts with label Algo. Show all posts
Showing posts with label Algo. Show all posts

Saturday, June 5, 2010

Searching

Searching





Mencari data dengan cara menelusuri tempat penyimpanan data tersebut.



Penyimpanan data : dalam array atau linked list.



Metode searching :


  • Sequential Search

  • Binary Search

  • Fibonacci Search

  • Interpolation Search








Array dan Linked List adalah 2 struktur data dasar yang digunakan untuk menyimpan informasi. Kita dapat melakukan pencarian, memasukkan/ menyisipkan dan menghapus record di dalam database, yang didasarkan

pada suatu key value.



Pencarian Sekuensial (Sequential Search)

Data yang dicari dibandingkan dengan seluruh elemen array.

Dapat digunakan baik pada data terurut maupun tidak.

Kelemahan :

Waktu proses lama bila data yang dicari tidak ada atau terletak pada elemen terakhir array.



Pencarian Biner (Binary Search)

Algoritma pencarian biner adalah algoritma untuk mencari sebuah nilai pada tabel teurut dengan cara menghilangkan setengah data pada setiap langkah. Algoritma ini mencari nilai yang dicari dengan tiga langkah yaitu :

• Mencari nilai tengah dari tabel (median)

• Melakukan perbandingan nilai tengah dengan nilai yang dicari untuk menentukan apakah nilai yang dicari ada pada sebelum atau setelah nilai tengah

• Mencari setengah sisanya dengan cara yang sama.



Pencarian dilakukan dengan cara membandingkan data yang dicari dengan nilai yang berada di “tengah” array tsb.



Diterapkan pada data yang sudah terurut baik ascending  atau  descending.



Misal pencarian dilakukan pada array A dg n elemen Algoritma :

1. Input X (data yg dicari). Lo = 0; Hi = n-1; Flag = 0

2. A. Selama Lo <= Hi dan Flag = 0 :

    Hitung Mid = (Lo + Hi) / 2

    Bila X = A[Mid], Isi Flag = 1

    Bila X < A[Mid], Isi Hi = Mid-1, kembali ke no.2

    Bila X > A[Mid], Isi Lo = Mid+1, kembali ke no.2

    B. Bila Lo > Hi, atau Flag = 1 ke no. 3

3. Proses pencarian selesai.

    Cetak “ADA” bila Flag = 1

    Cetak “TIDAK ADA” bila Flag = 0


Saturday, April 3, 2010

Stack (Data Structure)

Dedicated to Dosen Ayu.
.. with a thank you for d clear explanation..
with patience and passion..


Dalam ilmu komputer, stack atau tumpukan merupakan sebuah kumpulan data dimana penambahan dan pengambilan elemen hanya bisa dilakukan pada satu ujung (TOP). Dengan menggunakan prinsip LIFO (Last In First Out), yaitu data yang terakhr kali dimasukkan akan pertama kali keluar dari stack tersebut. 



Ciri Stack :
  • Elemen TOP (puncak) diketahui
  • penyisipan dan penghapusan elemen selalu dilakukan di TOP
  • LIFO (Last In First Out)

Aplikasi Stack :
  • Pemanggilan Prosedur
  • Perhitungan ekspresi aritmatika (posfix)
  • Algoritma Backtraking (runut balik)
  • Algoritma Rekursif (rekursifitas)

Operasi Stack yang biasanya :
  1. Push (input E : typeelmt, input/output data : stack): menambahkan sebuah elemen ke stack
  2. Pop (input/output data : stack, output E : typeelmt ) : menghapus sebuah elemen stack
  3. Clear : mengosongkan elemen pada stack
  4. IsEmpty (): memeriksa apakah stack kosong
  5. IsFull (): memeriksa apakah stack sudah penuh

Di C++ ada 2 cara penerapan prinsip stack yaitu :
Array/Larik
Linked List



Monday, March 8, 2010

Pointer (2)

We have already seen how variables are seen as memory cells that can be accessed using their identifiers. This way we did not have to care about the physical location of our data within memory, we simply used its identifier whenever we wanted to refer to our variable.

The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte). These single-byte memory cells are numbered in a consecutive way, so as, within any block of memory, every cell has the same number as the previous one plus one.

This way, each cell can be easily located in the memory because it has a unique address and all the memory cells follow a successive pattern. For example, if we are looking for cell 1776 we know that it is going to be right between cells 1775 and 1777, exactly one thousand cells after 776 and exactly one thousand cells before cell 2776.


Reference operator (&)

As soon as we declare a variable, the amount of memory needed is assigned for it at a specific location in memory (its memory address). We generally do not actively decide the exact location of the variable within the panel of cells that we have imagined the memory to be - Fortunately, that is a task automatically performed by the operating system during runtime. However, in some cases we may be interested in knowing the address where our variable is being stored during runtime in order to operate with relative positions to it.

The address that locates a variable within memory is what we call a referenceto that variable. This reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator, and which can be literally translated as "address of". For example:

 
ted = &andy;


This would assign to ted the address of variable andy, since when preceding the name of the variable andy with the reference operator (&) we are no longer talking about the content of the variable itself, but about its reference (i.e., its address in memory).

From now on we are going to assume that andy is placed during runtime in the memory address 1776. This number (1776) is just an arbitrary assumption we are inventing right now in order to help clarify some concepts in this tutorial, but in reality, we cannot know before runtime the real value the address of a variable will have in memory.

Consider the following code fragment:

1
2
3
andy = 25;
fred = andy;
ted = &andy;


The values contained in each variable after the execution of this, are shown in the following diagram:



First, we have assigned the value 25 to andy (a variable whose address in memory we have assumed to be 1776).

The second statement copied to fred the content of variable andy (which is 25). This is a standard assignment operation, as we have done so many times before.

Finally, the third statement copies to ted not the value contained in andy but a reference to it (i.e., its address, which we have assumed to be 1776). The reason is that in this third assignment operation we have preceded the identifier andy with the reference operator (&), so we were no longer referring to the value of andy but to its reference (its address in memory).

The variable that stores the reference to another variable (like ted in the previous example) is what we call a pointer. Pointers are a very powerful feature of the C++ language that has many uses in advanced programming. Farther ahead, we will see how this type of variable is used and declared.

Dereference operator (*)

We have just seen that a variable which stores a reference to another variable is called a pointer. Pointers are said to "point to" the variable whose reference they store.

Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by".

Therefore, following with the values of the previous example, if we write:

 
beth = *ted;


(that we could read as: "beth equal to value pointed by ted") beth would take the value 25, since ted is 1776, and the value pointed by 1776 is 25.



You must clearly differentiate that the expression ted refers to the value 1776, while *ted (with an asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25. Notice the difference of including or not including the dereference operator (I have included an explanatory commentary of how each of these two expressions could be read):

1
2
beth = ted;   // beth equal to ted ( 1776 )
beth = *ted; // beth equal to value pointed by ted ( 25 )

Notice the difference between the reference and dereference operators:
  • & is the reference operator and can be read as "address of"
  • * is the dereference operator and can be read as "value pointed by"
Thus, they have complementary (or opposite) meanings. A variable referenced with & can be dereferenced with *.

Earlier we performed the following two assignment operations:
1
2
andy = 25;
ted = &andy;

Right after these two statements, all of the following expressions would give true as result:
1
2
3
4
andy == 25
&andy == 1776
ted == 1776
*ted == 25

The first expression is quite clear considering that the assignment operation performed on andy was andy=25. The second one uses the reference operator (&), which returns the address of variable andy, which we assumed it to have a value of 1776. The third one is somewhat obvious since the second expression was true and the assignment operation performed on ted was ted=&andy. The fourth expression uses the dereference operator (*) that, as we have just seen, can be read as "value pointed by", and the value pointed by ted is indeed 25.

So, after all that, you may also infer that for as long as the address pointed by ted remains unchanged the following expression will also be true:
 
*ted == andy

Declaring variables of pointer types

Due to the ability of a pointer to directly refer to the value that it points to, it becomes necessary to specify in its declaration which data type a pointer is going to point to. It is not the same thing to point to a char as to point to an int or a float.

The declaration of pointers follows this format:
type * name;

where type is the data type of the value that the pointer is intended to point to. This type is not the type of the pointer itself! but the type of the data the pointer points to. For example:
1
2
3
int * number;
char * character;
float * greatnumber;

These are three declarations of pointers. Each one is intended to point to a different data type, but in fact all of them are pointers and all of them will occupy the same amount of space in memory (the size in memory of a pointer depends on the platform where the code is going to run). Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an int, the second one to a char and the last one to a float. Therefore, although these three example variables are all of them pointers which occupy the same size in memory, they are said to have different types: int*, char* and float* respectively, depending on the type they point to.

I want to emphasize that the asterisk sign (*) that we use when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator that we have seen a bit earlier, but which is also written with an asterisk (*). They are simply two different things represented with the same sign.

Now have a look at this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// my first pointer
#include <iostream>
using namespace std;

int main ()
{
int firstvalue, secondvalue;
int * mypointer;

mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
firstvalue is 10
secondvalue is 20

Notice that even though we have never directly set a value to either firstvalue or secondvalue, both end up with a value set indirectly through the use of mypointer. This is the procedure:

First, we have assigned as value of mypointer a reference to firstvalue using the reference operator (&). And then we have assigned the value 10 to the memory location pointed by mypointer, that because at this moment is pointing to the memory location of firstvalue, this in fact modifies the value of firstvalue.

In order to demonstrate that a pointer may take several different values during the same program I have repeated the process with secondvalue and that same pointer, mypointer.

Here is an example a little bit more elaborated:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// more pointers
#include <iostream>
using namespace std;

int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20

cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
firstvalue is 10
secondvalue is 20

I have included as a comment on each line how the code can be read: ampersand (&) as "address of" and asterisk (*) as "value pointed by".

Notice that there are expressions with pointers p1 and p2, both with and without dereference operator (*). The meaning of an expression using the dereference operator (*) is very different from one that does not: When this operator precedes the pointer name, the expression refers to the value being pointed, while when a pointer name appears without this operator, it refers to the value of the pointer itself (i.e. the address of what the pointer is pointing to).

Another thing that may call your attention is the line:
 
int * p1, * p2;

This declares the two pointers used in the previous example. But notice that there is an asterisk (*) for each pointer, in order for both to have type int* (pointer to int).

Otherwise, the type for the second variable declared in that line would have been int (and not int*) because of precedence relationships. If we had written:
 
int * p1, p2;


p1 would indeed have int* type, but p2 would have type int(spaces do not matter at all for this purpose). This is due to operator precedence rules. But anyway, simply remembering that you have to put one asterisk per pointer is enough for most pointer users.

Pointers and arrays

The concept of array is very much bound to the one of pointer. In fact, the identifier of an array is equivalent to the address of its first element, as a pointer is equivalent to the address of the first element that it points to, so in fact they are the same concept. For example, supposing these two declarations:
1
2
int numbers [20];
int * p;

The following assignment operation would be valid:
 
p = numbers; 

After that, p and numbers would be equivalent and would have the same properties. The only difference is that we could change the value of pointer p by another one, whereas numbers will always point to the first of the 20 elements of type int with which it was defined. Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an array can be considered a constant pointer. Therefore, the following allocation would not be valid:
 
numbers = p;


Because numbers is an array, so it operates as a constant pointer, and we cannot assign values to constants.

Due to the characteristics of variables, all expressions that include pointers in the following example are perfectly valid:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// more pointers
#include <iostream>
using namespace std;

int main ()
{
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
return 0;
}
10, 20, 30, 40, 50, 

In the chapter about arrays we used brackets ([]) several times in order to specify the index of an element of the array to which we wanted to refer. Well, these bracket sign operators [] are also a dereference operator known as offset operator. They dereference the variable they follow just as * does, but they also add the number between brackets to the address being dereferenced. For example:
1
2
a[5] = 0;       // a [offset of 5] = 0
*(a+5) = 0; // pointed by (a+5) = 0

These two expressions are equivalent and valid both if a is a pointer or if a is an array.

Pointer initialization

When declaring pointers we may want to explicitly specify which variable we want them to point to:
1
2
int number;
int *tommy = &number;

The behavior of this code is equivalent to:
1
2
3
int number;
int *tommy;
tommy = &number;

When a pointer initialization takes place we are always assigning the reference value to where the pointer points (tommy), never the value being pointed (*tommy). You must consider that at the moment of declaring a pointer, the asterisk (*) indicates only that it is a pointer, it is not the dereference operator (although both use the same sign: *). Remember, they are two different functions of one sign. Thus, we must take care not to confuse the previous code with:
1
2
3
int number;
int *tommy;
*tommy = &number;

that is incorrect, and anyway would not have much sense in this case if you think about it.

As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is declared:
 
char * terry = "hello"; 

In this case, memory space is reserved to contain "hello" and then a pointer to the first character of this memory block is assigned to terry. If we imagine that "hello" is stored at the memory locations that start at addresses 1702, we can represent the previous declaration as:


It is important to indicate that terry contains the value 1702, and not 'h' nor "hello", although 1702 indeed is the address of both of these.

The pointer terry points to a sequence of characters and can be read as if it was an array (remember that an array is just like a constant pointer). For example, we can access the fifth element of the array with any of these two expression:
1
2
*(terry+4)
terry[4]

Both expressions have a value of 'o' (the fifth element of the array).

Pointer arithmetics

To conduct arithmetical operations on pointers is a little different than to conduct them on regular integer data types. To begin with, only addition and subtraction operations are allowed to be conducted with them, the others make no sense in the world of pointers. But both addition and subtraction have a different behavior with pointers according to the size of the data type to which they point.

When we saw the different fundamental data types, we saw that some occupy more or less space than others in the memory. For example, let's assume that in a given compiler for a specific machine, char takes 1 byte, short takes 2 bytes and long takes 4.

Suppose that we define three pointers in this compiler:
1
2
3
char *mychar;
short *myshort;
long *mylong;

and that we know that they point to memory locations 1000, 2000 and 3000 respectively.

So if we write:
1
2
3
mychar++;
myshort++;
mylong++;

mychar, as you may expect, would contain the value 1001. But not so obviously, myshort would contain the value 2002, and mylong would contain 3004, even though they have each been increased only once. The reason is that when adding one to a pointer we are making it to point to the following element of the same type with which it has been defined, and therefore the size in bytes of the type pointed is added to the pointer.



This is applicable both when adding and subtracting any number to a pointer. It would happen exactly the same if we write:
1
2
3
mychar = mychar + 1;
myshort = myshort + 1;
mylong = mylong + 1;

Both the increase (++) and decrease (--) operators have greater operator precedence than the dereference operator (*), but both have a special behavior when used as suffix (the expression is evaluated with the value it had before being increased). Therefore, the following expression may lead to confusion:
 
*p++

Because ++ has greater precedence than *, this expression is equivalent to *(p++). Therefore, what it does is to increase the value of p (so it now points to the next element), but because ++ is used as postfix the whole expression is evaluated as the value pointed by the original reference (the address the pointer pointed to before being increased).

Notice the difference with:
(*p)++

Here, the expression would have been evaluated as the value pointed by p increased by one. The value of p (the pointer itself) would not be modified (what is being modified is what it is being pointed to by this pointer).

If we write:
 
*p++ = *q++; 

Because ++ has a higher precedence than *, both p and q are increased, but because both increase operators (++) are used as postfix and not prefix, the value assigned to *p is *q before both p and q are increased. And then both are increased. It would be roughly equivalent to:
1
2
3
*p = *q;
++p;
++q;

Like always, I recommend you to use parentheses () in order to avoid unexpected results and to give more legibility to the code.
 

Pointers to pointers

C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or even to other pointers). In order to do that, we only need to add an asterisk (*) for each level of reference in their declarations:

1
2
3
4
5
6
char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;

This, supposing the randomly chosen memory locations for each variable of 7230, 8092 and 10502, could be represented as:

The value of each variable is written inside each cell; under the cells are their respective addresses in memory.

The new thing in this example is variable c, which can be used in three different levels of indirection, each one of them would correspond to a different value:
  • c has type char** and a value of 8092
  • *c has type char* and a value of 7230
  • **c has type char and a value of 'z'

void pointers

The void type of pointer is a special type of pointer. In C++, voidrepresents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).

This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.

One of its uses may be to pass generic parameters to a function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// increaser
#include <iostream>
using namespace std;

void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{ char* pchar; pchar=(char*)data; ++(*pchar); }
else if (psize == sizeof(int) )
{ int* pint; pint=(int*)data; ++(*pint); }
}

int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}
y, 1603

sizeof is an operator integrated in the C++ language that returns the size in bytes of its parameter. For non-dynamic data types this value is a constant. Therefore, for example, sizeof(char) is 1, because char type is one byte long.

Null pointer

A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type.
1
2
int * p;
p = 0; // p has a null pointer value

Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere", while a void pointer is a special type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer itself and the other to the type of data it points to.

Pointers to functions

C++ allows operations with pointers to functions. The typical use of this is for passing a function as an argument to another function, since these cannot be passed dereferenced. In order to declare a pointer to a function we have to declare it like the prototype of the function except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// pointer to functions
#include <iostream>
using namespace std;

int addition (int a, int b)
{ return (a+b); }

int subtraction (int a, int b)
{ return (a-b); }

int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}

int main ()
{
int m,n;
int (*minus)(int,int) = subtraction;

m = operation (7, 5, addition);
n = operation (20, m, minus);
cout <<n;
return 0;
}
8

In the example, minus is a pointer to a function that has two parameters of type int. It is immediately assigned to point to the function subtraction, all in a single line:
 
int (* minus)(int,int) = subtraction;


http://www.cplusplus.com/doc/tutorial/pointers/

Pointer (1)

Pointer merupakan suatu variabel yang mempunyai harga alamat dari variabel lain atau elemen array. Pointer banyak digunakan dalam pemrograman C++, misalkan untuk mengirimkan informasi dari dan ke fungsi. Terutama pointer sangat berguna untuk mengirimkan data yang terdiri lebih dari satu harga dari dan ke fungsi. Untuk memahami pointer kita perlu pengetahuan tentang bagaimana komputer menyimpan informasi di dalam memori. Memori di dalam PC yang dikenal sebagai RAM (Random Access Memory) terdiri dari sederetan sel memori dan setiap sel memori mempunyai alamat tersendiri.



Sewaktu kita mendefinisikan variabel, C++ akan memberikan sel memori dengan address tertentu yang tak terpakai untuk menyimpan variabel itu. Bila program kita menggunakan nama variabel tersebut, otomatis akan menggunakan alamat dari sel memori yang berhubungan dengan variabel tersebut. Suatu misal ketika kita mendefinisikan variabel lebar dengan harga awal 25 dan dimisalkan C++ memberikan alamat 1004 untuk variabel lebar, hal ini dapat digambarkan sebagai berikut :

Alamat Memori Variabel
1001
1002
1003
1004 25 lebar

Jika kita mengetahui alamat dari suatu variabel, maka kita dapat menciptakan variabel kedua yang menyimpan alamat dari variabel pertama. Misalkan kita mendefinisikan variabel kedua plebar yang menyimpan alamat dari variabel pertama lebar. Karena plebar memuat alamat dari lebar, ini berarti plebar menunjukkan lokasi penyimpanan di dalam memori. Dalam pergertian ini berarti plebar menunjuk ke lebar atau sebagai pointer ke lebar. Misalkan plebar mempunyai alamat 1001, hal ini dapat digambarkan sebagai berikut :

Alamat Memori Variabel
1001 1004 Plebar
1002
1003
1004 25 Lebar

Kesimpulan : suatu pointer adalah suatu variabel yang memuat atau menyimpan alamat dari variabel lain, termasuk elemen array.

Deklarasi Pointer
Variabel pointer sama seperti variabel yang lain harus dideklarasikan sebelum digunakan didalam program C++. Nama variabel pointer mengikutim atuaran yang sama seperti variabel lain. Variabel pointer dideklarasikan dengan membubuhi tanda asteriks ( * ) didepan nama variabel pointer. Tipe data yang dituliskan pada deklarasi pointer menunjukkan tipe data dari data yang alamatnya disimpan di dalam pointer dan bukan tipe data dari pointer itu sendiri. Bentuk umum deklarasi variabel pointer adalah :
tipe data *variabel_pointer ;

Berikut ini beberapa contoh deklarasi pointer :
int *radius; atau int * radius; atau int* radius;
float *volume; atau float * volume; atau float* volume;

Operator Alamat ( & )
Dari gambar penjelasan sebelumnya, alamat dari lokasi memori variabel lebar dapat ditentukan dengan ekspresi &lebar, dimana & adalah operator unary yang disebut juga sebagai operator alamat. Disini &lebar adalah alamat dari variabel lebar yaitu 1004. Jadi plebar adalah sama dengan &lebar.

Operator Dereferensi ( * )
Data yang disimpan di dalam variabel lebar dari penjelasan sebelumnya, dapat dibaca dari variabel pointer plebar dengan menggunakan ekspresi *plebar, dimana tanda asterik ( * ) adalah operator unary, yang disebut operator dereferensi. Operator dereferensi ( * ) ini hanya digunakan untuk variabel pointer. Jadi *plebar dan lebar adalah sama, yakni menunjukkan harga variabel lebar 25.

Contoh :

#include
#include

void main()
{
int panjang, lebar, luas;
int *p_panjang, *p_lebar, *p_luas;

p_panjang = &panjang;
p_lebar = &lebar;
p_luas = &luas;

cout << "Panjang : "; cin >> panjang;
cout << "Lebar : "; cin >> lebar;

luas = panjang * lebar;

cout << endl << endl;
cout << "Data yang diinputkan ke panjang : " << panjang <<
endl;
cout << "Data yang diinputkan ke lebar : " << lebar << endl;
cout << "Data yang dihasilkan oleh luas : " << luas << endl
<< endl;
cout << "Data yang disimpan oleh *p_panjang : " << *p_panjang
<< endl;
cout << "Data yang disimpan oleh *p_lebar : " << *p_lebar <<
endl;
cout << "Data yang disimpan oleh *p_luas : " << *p_luas <<
endl << endl;
cout << "Data alamat variabel panjang : " << &panjang << endl;
cout << "Data alamat variabel lebar : " << &lebar << endl;
cout << "Data alamat variabel luas : " << &luas << endl <<
endl;
cout << "Data alamat variabel p_panjang : " << p_panjang <<
endl;
cout << "Data alamat variabel p_lebar : " << p_lebar <<
endl;
cout << "Data alamat variabel p_luas : " << p_luas << endl
<< endl;
getch();
}

Keluaran programnya :

Panjang : 8
Lebar : 6

Data yang diinputkan ke panjang : 8
Data yang diinputkan ke lebar : 6
Data yang dihasilkan oleh luas : 48

Data yang disimpan oleh *p_panjang : 8
Data yang disimpan oleh *p_lebar : 6
Data yang disimpan oleh *p_luas : 48


Data alamat variabel panjang : 0x8f5efff4
Data alamat variabel lebar : 0x8f5efff2
Data alamat variabel luas : 0x8f5efff0

Data alamat variabel p_panjang : 0x8f5efff4
Data alamat variabel p_lebar : 0x8f5efff2
Data alamat variabel p_luas : 0x8f5efff0

Perhatikan bahwa p_panjang adalah pointer ke variabel panjang, p_lebar adalah pointer ke variabel lebar dan p_luas adalah pointer ke variabel luas. Isi dari p_panjang adalah alamat dari variabel panjang, isi dari p_lebar adalah alamat dari variabel lebar dan isi dari p_luas adalah alamat dari variabel luas.

Mengirimkan Pointer ke Fungsi
Pointer sering digunakan sebagai argumen dari suatu fungsi. Hal ini memungkinkan pertukaran informasi atau data dari fungsi yang satu ke fungsi yang lain. Bila digunakan pointer, maka alamat dari variabel dikirimkan ke fungsi, sedangkan bila digunakan variabel biasa, maka informasi atau data disalin ke fungsi yang dipanggil.

Jadi perubahan suatu data di dalam fungsi tidak berpengaruh terhadap fungsi lain, karena yang diubah hanyalah salinan dari informasi atau data. Bila yang dikirimkan adalah alamat dari suatu variabel pointer, maka perubahan harga dari variabel yang alamatnya dikirimkan tersebut akan berpengaruh terhadap fungsi lain yang menggunakan alamat tersebut.

Contoh :

#include
#include

void input_data (float *pr1, float *pr2, float *pr3, float *pi);
void hitung_data (float *pr1, float *pr2, float *pr3,
float *pi,float *prs, float *prp, float *pvs, float *pvp);
void tampilkan (float *prs, float *prp, float *pi, float *pvs,
float *pvp);
void main()
{
float i, r1, r2, r3;
float rs, rp, vs, vp;
float *pi, *pr1, *pr2, *pr3;
float *prs, *prp, *pvs, *pvp;
clrscr();

input_data (&r1, &r2, &r3, &i);
hitung_data (&r1, &r2, &r3, &i, &rs, &rp, &vs, &vp);
tampilkan (&rs, &rp, &i, &vs, &vp);
getch();
}

void input_data (float *pr1, float *pr2, float *pr3, float *pi)
{
cout << "Masukkan Data Tegangan dan Arusnya :" << endl;
cout << "Data R1 : ";
cin >> *pr1;
cout << "Data R2 : ";
cin >> *pr2;
cout << "Data R3 : ";
cin >> *pr3;
cout << "Data i : ";
cin >> *pi;
cout << endl;
}

void hitung_data (float *pr1, float *pr2, float *pr3, float *pi, float *prs, float *prp, float *pvs, float *pvp)
{
float paralel;

*prs = *pr1 + *pr2 + *pr3;
paralel = (1 / *pr1)+(1 / *pr2)+(1 / *pr3);
*prp = 1/paralel;
*pvs = *pi * *prs;
*pvp = *pi * *prp;
}

void tampilkan (float *prs, float *prp, float *pi, float *pvs,
float *pvp)
{
cout.precision(2);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout << "Data total hambatan dan tegangan (seri/paralel) serta
arusnya :" << endl;
cout << "Total hambatan seri (Rs) : " << *prs << endl;
cout << "Total hambatan paralel (Rp) : " << *prp << endl;
cout << "Arus yang melaluinya (i) : " << *pi << endl;
cout << "Tegangan Seri (Vs) : " << *pvs << endl;
cout << "Tegangan paralel (Vp) : " << *pvp << endl;
}

Keluaran programnya :

Masukkan Data Tegangan dan Arusnya :
Data R1 : 1.5
Data R2 : 3.7
Data R3 : 6.3
Data i : 0.45

Data total hambatan dan tegangan (seri/paralel) serta arusnya :
Total hambatan seri (Rs) : 11.50
Total hambatan paralel (Rp) : 0.91
Arus yang melaluinya (i) : 0.45
Tegangan Seri (Vs) : 5.17
Tegangan paralel (Vp) : 0.41

Pada Contoh diatas fungsi main hanya berfungsi sebagai pengendali terhadap tiga fungsi buatan yaitu input_data, hitung_data dan tampilkan. Ketiga fungsi tersebut memiliki parameter formal berupa pointer yang mengambil dan mengirimkan nilai dari alamat yang diberikan oleh parameter aktual yang ada di fungsi main.

Pada fungsi input_data terdapat variabel pointer yang nantinya akan menerima data yang diinput dari keyboard. Karena fungsi main memanggil fungsi input_data dengan alamat maka nilai atau data yang ada pada fungsi tersebut bisa diakses oleh fungsi main. Dengan demikian fungsi main sekarang memiliki nilai atau data r1, r2, r3 dan i yang sama dengan nilai atau data yang ada di fungsi input_data.

Selanjutnya fungsi main memanggil fungsi hitung_data agar menghitung jumlah hambatan dan tegangan seri-paralel. Fungsi hitung_data akan mengerjakan proses tersebut sesuai dengan nilai r1, r2, r3 dan i yang dikirimkan oleh fungsi main dan juga mengembalikan hasilnya rs, rp, vs dan vp kepada fungsi tersebut.

Sedangkan fungsi tampilkan yang dipanggil oleh fungsi main akan menampilkan nilai yang didapat oleh fungsi main dari fungsi input_data yaitu : i dan fungsi hitung_data yaitu : rs, rp, vs dan vp.


Program berikut ini adalah modifikasi dari contoh program sebelumnya yaitu dengan menghilangkan fungsi tampilkan dan isi program fungsi tersebut diletakan pada fungsi main.


#include
#include

void input_data (float *pr1, float *pr2, float *pr3, float *pi);
void hitung_data (float *pr1, float *pr2, float *pr3,
float *pi,float *prs, float *prp, float *pvs, float *pvp);

void main()
{
float i, r1, r2, r3;
float rs, rp, vs, vp;
float *pi, *pr1, *pr2, *pr3;
float *prs, *prp, *pvs, *pvp;
clrscr();

prs = &rs;
prp = &rp;
pi = &i;
pvs = &vs;
pvp = &vp;

input_data (&r1, &r2, &r3, &i);
hitung_data (&r1, &r2, &r3, &i, &rs, &rp, &vs, &vp);
cout.precision(2);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout << "Data total hambatan dan tegangan (seri/paralel) serta
arusnya :" << endl;
cout << "Total hambatan seri (Rs) : " << *prs << endl;
cout << "Total hambatan paralel (Rp) : " << *prp << endl;
cout << "Arus yang melaluinya (i) : " << *pi << endl;
cout << "Tegangan Seri (Vs) : " << *pvs << endl;
cout << "Tegangan paralel (Vp) : " << *pvp << endl;
getch();
}

void input_data (float *pr1, float *pr2, float *pr3, float *pi)
{
cout << "Masukkan Data Tegangan dan Arusnya :" << endl;
cout << "Data R1 : ";
cin >> *pr1;
cout << "Data R2 : ";
cin >> *pr2;
cout << "Data R3 : ";
cin >> *pr3;
cout << "Data i : ";
cin >> *pi;
cout << endl;
}

void hitung_data (float *pr1, float *pr2, float *pr3, float *pi,
float *prs, float *prp, float *pvs, float *pvp)
{
float paralel;

*prs = *pr1 + *pr2 + *pr3;
paralel = (1 / *pr1)+(1 / *pr2)+(1 / *pr3);
*prp = 1/paralel;
*pvs = *pi * *prs;
*pvp = *pi * *prp;
}

Keluaran programnya :

Masukkan Data Tegangan dan Arusnya :
Data R1 : 1.5
Data R2 : 3.7
Data R3 : 6.3
Data i : 0.45

Data total hambatan dan tegangan (seri/paralel) serta arusnya :
Total hambatan seri (Rs) : 11.50
Total hambatan paralel (Rp) : 0.91
Arus yang melaluinya (i) : 0.45
Tegangan Seri (Vs) : 5.17
Tegangan paralel (Vp) : 0.41

Pada contoh program diatas hampir sama dengan contoh program sebelumnya yaitu dengan menambahkan pernyataan prs = &rs, prp = &rp, pi = &i, pvs = &vs dan pvp = &vp sebagai penunjuk alamat bagi variabel pointer *prs, *prp, *pvs, *pvp dan *pi yang akan menampilkan nilainya.

Dengan demikian dari contoh kedua program diatas diperoleh kesimpulan bahwa pengiriman nilai melalui fungsi dengan menggunakan pointer maka perubahan nilai atau data yang terjadi pada fungsi tersebut akan berpengaruh terhadap fungsi lainnya.

Array dan Pointer
Hingga saat ini array dianggap sebagai daftar nilai. Ini merupakan pengertian array secara konsep. Secara internal nama array adalah pointer ke elemen pertama dalam array. Sewaktu kita mendefinisikan array seperti ini :

int umur[] = { 32, 45, 42, 19, 67 }

Misalkan ingin menampilkan elemen pertama dan kedua array tersebut.

cout << “Nilai elemen kesatu : “ << umur[0];
cout << “Nilai elemen kedua : “ << umur[1];

Berikut ini juga akan menampilkan nilai elemen pertama dan kedua dengan menggunakan pointer.

cout << “Nilai elemen kesatu : “ << *(umur + 0);
cout << “Nilai elemen kedua : “ << *(umur + 1);

Kedua pernyataan cout tersebut akan menghasilkan nilai yang sama yaitu angka 32 dan 45. Perhatikan bahwa bentuk berikut ini adalah ekuivalen :

umur[3], *(umur + 3), *(umur + 0)[3], *(umur + 1)[2], *(umur + 2)[1] dan *(umur + 3)[0]

Contoh :

#include
#include

void main()
{
int i;
float nilai[3] = { 11.1, 22.2, 33.3 };
clrscr();

cout.precision(1);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);

cout << "Bentuk array yang menggunakan subscript :" << endl;
for (i = 0; i < 3; i++)
{ cout << nilai[i] << ' '; }

cout << endl << endl;
cout << "Bentuk array yang menggunakan pointer:" << endl;
for (i = 0; i < 3; i++)
{ cout << *(nilai + i) << ' '; }

cout << endl << endl;
cout << "Bentuk array kombinasi:" << endl;
cout << (nilai + 0)[0] << ' ';
cout << (nilai + 1)[0] << ' ';
cout << (nilai + 0)[1] << ' ';
cout << (nilai + 1)[1] << ' ';
cout << (nilai + 2)[1] << ' ';
cout << (nilai + 1)[2] << ' ';
getch();
}

Keluaran programnya :

Bentuk array yang menggunakan subscript :
11.1 22.2 33.3

Bentuk array yang menggunakan pointers:
11.1 22.2 33.3

Bentuk array kombinasi:
11.1 22.2 22.2 33.3 33.3 33.3

Array Pointer
Anda dapat mendefenisikan sebuah array yang menampung tipe data apa saja, termasuk pointer. Berikut merupakan cara menginisialisasi array semacam itu :

char *kota[5] = { “Jakarta”, “Bandung”, “Semarang” };

Ingatlah bahwa C++ memperlakukan literal string sebagai sebuah alamat. Dengan kata lain C++ menyimpan tiga nama kota pada suatu tempat dalam memori yang bebas. Kemudian C++ menugaskan alamat masing-masing literal string itu ke masing-masing elemen array kota.

Contoh :

#include
#include

void main()
{
int i;
clrscr();

char *kota[5] = { "Jakarta", "Bandung", "Semarang" };

//Menampilkan tiga nama kota yang diisikan pada program
cout << "Berikut ini adalah kota tersebut"<< endl;
for (i = 0; i < 3; i++)
{ cout << kota[i] << “, “; }
cout << endl;

//Mengganti nama kota diatas dengan yang lainnya
kota[0] = "Yogyakarta";
kota[1] = "Surabaya";
kota[2] = "Bali";

//Menampilkan nama kota dengan notasi pointer
cout << endl << "Berikut ini adalah kota tersebut" << endl;
for (i = 0; i < 3; i++)
{ cout << *(kota + i) << “, “; }
cout << endl;
getch();
}

Keluaran programnya :

Berikut ini adalah kota tersebut
Jakarta, Bandung, Semarang,

Berikut ini adalah kota tersebut
Yogyakarta, Surabaya, Bali,

Setelah menugaskan pointer ke nama-nama kota, loop for pertama pada contoh program diatas akan menampilkan 3 kota menggunakan notasi subscribt. Kemudian variabel kota diisikan dengan data string yang baru melalui masing-masing elemen array. Fungsi strcpy() tidak akan berkerja dengan baik pada penugasan kalau literal string baru lebih panjang daripada string yang akan ditunjuk. Loop for kedua menampilkan nama ketiga kota yang baru memakai dereferensi pointer.

Contoh 8.6 :

#include
#include
#include

void menu_tampilan();
int informasi();
void tampilan_properti(char *kode[], float harga[],
char *alamat[], float komisi[]);
void pencarian_properti(char *kode[], float harga[],
char *alamat[], float komisi[]);

void main()
{
int hasil;
char *kode[3] = { "11A", "22B", "33C" };
float harga[3] = { 15000, 25000, 50000};
char *alamat[3] = { "Jl. Akses UI Depok 12264",
"Jl. Pondok Indah Jakarta 12223",
"Jl. Ciputat Raya Jakarta 12241" };
float komisi[3] = { 0.15, 0.20, 0.30 };
clrscr();

do
{
clrscr();
menu_tampilan();
hasil = informasi();

switch (hasil)
{
case (1) :
{ tampilan_properti(kode, harga, alamat, komisi);
break; }
case (2) :
{ pencarian_properti(kode, harga, alamat, komisi);
break; }
case (3) :
{ return;
break; }
}
} while (hasil != 3);
}
void menu_tampilan()
{
cout << endl << endl;
cout << "** Property Menu Database **" << endl << endl;
cout << "Menu yang bisa dipilih:" << endl << endl;
cout << "1. Melihat data properti" << endl;
cout << "2. Mencari data dengan indeks kode" << endl;
cout << "3. Keluar program" << endl;
cout << endl << "Anda memilih menu (1/2/3) ? ";
}

int informasi()
{
int pilih;
cin >> pilih;
cin.ignore(30,'\n');
return (pilih);
}

void tampilan_properti(char *kode[], float harga[],
char *alamat[], float komisi[])
{
int i;

cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);

for (i = 0; i < 3; i++)
{
cout << endl ;
cout << "Kode : " << kode[i] << endl;
cout << "Harga : Rp " << harga[i] << endl;
cout << "Alamat : " << alamat[i] << endl;
cout << "Persen komisi : "<< komisi[i] * 100.0 << "%"
<< endl << endl;
}
cout << "Tekan tombol enter untuk lanjut...";
cin.ignore(30,'\n');
}

void pencarian_properti(char *kode[], float harga[],
char *alamat[], float komisi[])
{
int i;
int ketemu = 0;
char buf[6];

cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);

cout << endl << "Saya akan mencari data yang kita inginkan"
<< endl;
cout << "Tuliskan kode properti dari data yang diinginkan : ";
cin.getline(buf, 6);
for (i = 0; i < 3; i++)
{
if (!strcmp(kode[i], buf))
{
cout << endl ;
cout << "Kode : " << kode[i] << endl;
cout << "Harga : Rp " << harga[i] << endl;
cout << "Alamat : " << alamat[i] << endl;
cout << "Persen komisi : " << komisi[i]*100.0 << "%"
<< endl << endl;
ketemu = 1;
cout << "Tekan sembarang tombol untuk kembali ke
menu......" << endl;
getch();
break;
}
}

if (!ketemu)
{
cout << endl << "Data dengan kode : " << buf << " tidak
ditemukan" << endl << endl;
cout << "Tekan sembarang tombol untuk kembali ke
menu......" << endl;
getch();
}
}

Keluaran programnya :

** Property Menu Database **

Menu yang bisa dipilih:

1. Melihat data properti
2. Mencari data dengan indeks kode
3. Keluar program

Anda memilih menu (1/2/3) ? 1

Kode : 11A
Harga : Rp 15000.00
Alamat : Jl. Akses UI Depok 12264
Persen komisi : 15.00%

Kode : 22B
Harga : Rp 25000.00
Alamat : Jl. Pondok Indah Jakarta 12223
Persen komisi : 20.00%

Kode : 33C
Harga : Rp 50000.00
Alamat : Jl. Ciputat Raya Jakarta 12241
Persen komisi : 30.00%

Tekan tombol enter untuk lanjut...

Pada contoh program diatas dengan menggunakan variabel pointer, maka kita dapat mengakses data dengan alamatnya dan bukan melalui nama variabel. Prototipe string.h digunakan untuk fungsi strcmp (membandingkan isi string). Empat fungsi yang dideklarasikan diatas, dua fungsi tanpa parameter dan dua lagi menggunakan parameter.

Variabel kode dan alamat pada parameter fungsi tampilan_properti serta pencarian_properti dideklarasikan sebagai array pointer agar dapat menangani data yang berisi string. Pada fungsi main variabel kode, harga, alamat dan komisi diisikan langsung pada kode program. Untuk memilih menu dilakukan dengan menggunakan pernyataan do-while yang mana pernyataan ini akan selalu berulang-ulang apabila kita memberikan nilai tidak sama dengan 3. Sedangkan untuk mengakhiri tampilan menu ini kita dapat memberikan input dengan menekan tombol angka 3.

Didalam pernyataan do-while, untuk memilih menu yang memanggil salah satu fungsi digunakan pernyataan switch(). Jadi pemanggilan fungsi yang dilakukan didalam pernyataan switch() membuat agar fungsi-fungsi tersebut tidak harus dijalankan secara serentak seperti pada contoh program 8.2 tetapi hanya fungsi yang ditunjuk oleh pernyataan switch() yang akan bekerja. Fungsi menu_tampilan berfungsi sebagai tampilan yang memandu kita untuk bisa melanjutkan proses berikutnya apabila kita mengisikan data yang sesuai dengan keterangan yang diberikan dalam menu tersebut. Fungsi ini akan dijalankan pertama kali oleh fungsi main yang terdapat pada pernyataan do-while.

Fungsi informasi berfungsi sebagai kelanjutan proses berikutnya yaitu menuju salah satu case yang sesuai pada pernyataan switch(). Pada fungsi ini pilihan angka yang tersedia agar dapat menuju salah satu case yang terdapat pada fungsi switch() adalah 1, 2 dan 3. Bila kita menginputkan dengan menekan tombol angka 1, 2 atau 3 maka data tersebut disimpan kedalam variabel hasil yang mana data tersebut dikembalikan ke fungsi pemanggil yaitu fungsi main menggunakan pernyataan return.

Jadi fungsi informasi mengembalikan nilai yang disimpannya untuk diisikan ke dalam pernyataan pemanggil fungsi pada variabel hasil dan nilai yang ada pada variabel ini selanjutnya akan menuju ke case yang cocok. Kalau cocok maka akan memanggil salah satu fungsi yang berada pada case tersebut. Bila tidak maka pernyataan yang ada didalam do-while akan diulang kembali. Pernyataan cin.ignore (30. ‘\n’) berfungsi sebagai penunggu tombol yang akan ditekan oleh pemakai. Sedangkan pernyataan break berfungsi sebagai pencegah agar C++ tidak mengeksekusi kode program berikutnya.

Fungsi tampilan_properti berfungsi menampilkan data-data yang sudah diisikan pada kode program yang berada di fungsi main. Perhatikan bahwa parameter yang ada di fungsi ini kebetulan namanya dibuat sama dengan parameter yang ada di pernyataan pemanggil fungsi. Pemanggilan fungsi disini sebenarnya hanya melewatkan nilai bukan dengan referensi atau pointer. Sedangkan parameter yang terlihat pada fungsi tampilan_properti atau pencarian_properti bertanda asterik (*) adalah data yang dilewatkan berupa string. Anda tak dapat melewatkan data string pada variabel array biasa, jadi variabel berjenis array pointer-lah yang harus kita gunakan.

Fungsi pencarian_properti berfungsi sebagai fungsi yang menangani proses pencarian sekelompok data pada elemen array yang berbeda tetapi bernomor indeks sama. Melalui peryataan strcmp() inilah maka variabel buf yang diinputkan berupa kode akan dibandingkan dengan kode yang tersimpan pada setiap elemen array.Bila hasil dari pernyataan strcmp() ini sesuai yaitu string pada variabel buf sama dengan string kode[i] maka pernyataan ini akan dijalankan dan akan menampilkan data yang ada di elemen array yang sama pada variabel yang berbeda. Bila data string yang dibandingkan tadi berbeda atau tidak ada yang cocok maka akan menjalankan pernyataan berikutnya yaitu if ( !ketemu ) maksudnya jika tidak ketemu bernilai benar maka peryataan inilah yang akan dieksekusi.

Saturday, January 2, 2010

Computer Program



Dedicated to Dosen Dody Sanjaya

Computer Program

 

Computer programs (also software programs, or just programs) are instructions for a computer. A computer requires programs to function, typically executing the program's instructions in a central processor. The program has an executable form that the computer can use directly to execute the instructions. The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled), enables a programmer to study and develop its algorithms.

Computer source code is often written by professional computer programmers. Source code is written in a programming language that usually follows one of two main paradigms: imperative or declarative programming. Source code may be converted into an executable file (sometimes called an executable program or a binary) by a compiler. Alternatively, computer programs may be executed by a central processing unit with the aid of an interpreter, or may be embedded directly into hardware.

Computer programs may be categorized along functional lines: system software and application software. And many computer programs may run simultaneously on a single computer, a process known as multitasking.



Main article: Computer programming

#include

int main(void)

{


puts("Hello world!");

return 0;


}

Source code of a program written in the C programming language

Computer programming is the iterative process of writing or editing source code. Editing source code involves testing, analyzing, and refining, and sometimes coordinating with other programmers on a jointly developed program. A person who practices this skill is referred to as a computer programmer or software developer. The sometimes lengthy process of computer programming is usually referred to as software development. The term software engineering is becoming popular as the process is seen as an engineering discipline.

 

Paradigms

Computer programs can be categorized by the programming language paradigm used to produce them. Two of the main paradigms are imperative and declarative.

Programs written using an imperative language specify an algorithm using declarations, expressions, and statements. A declaration couples a variable name to a datatype. For example: var x: integer; . An expression yields a value. For example: 2 + 2 yields 4. Finally, a statement might assign an expression to a variable or use the value of a variable to alter the program's control flow. For example: x := 2 + 2; if x = 4 then do_something(); One criticism of imperative languages is the side-effect of an assignment statement on a class of variables called non-local variables.

Programs written using a declarative language specify the properties that have to be met by the output and do not specify any implementation details. Two broad categories of declarative languages are functional languages and logical languages. The principle behind functional languages (like Haskell) is to not allow side-effects, which makes it easier to reason about programs like mathematical functions. The principle behind logical languages (like Prolog) is to define the problem to be solved — the goal — and leave the detailed solution to the Prolog system itself. The goal is defined by providing a list of subgoals. Then each subgoal is defined by further providing a list of its subgoals, etc. If a path of subgoals fails to find a solution, then that subgoal is backtracked and another path is systematically attempted.

The form in which a program is created may be textual or visual. In a visual language program, elements are graphically manipulated rather than textually specified.

 

Compilation or Interpretation

A computer program in the form of a human-readable, computer programming language is called source code. Source code may be converted into an executable image by a compiler or executed immediately with the aid of an interpreter.

Either compiled or interpreted programs might be executed in a batch process without human interaction, but interpreted programs allow a user to type commands in an interactive session. In this case the programs are the separate commands, whose execution is chained together. When a language is used to give commands to a software application (such as a shell) it is called a scripting language.

Compiled computer programs are commonly referred to as executables, binary images, or simply as binaries — a reference to the binary file format used to store the executable code. Compilers are used to translate source code from a programming language into either object code or machine code. Object code needs further processing to become machine code, and machine code is the Central Processing Unit's native code, ready for execution.

Interpreted computer programs -in a batch or interactive session- are either decoded and then immediately executed or are decoded into some efficient intermediate representation for future execution. BASIC, Perl, and Python are examples of immediately executed computer programs. Alternatively, Java computer programs are compiled ahead of time and stored as a machine independent code called bytecode. Bytecode is then executed upon request by an interpreter called a virtual machine.

The main disadvantage of interpreters is computer programs run slower than if compiled. Interpreting code is slower than running the compiled version because the interpreter must decode each statement each time it is loaded and then perform the desired action. On the other hand, software development may be quicker using an interpreter because testing is immediate when the compilation step is omitted. Another disadvantage of interpreters is the interpreter must be present on the computer at the time the computer program is executed. By contrast, compiled computer programs need not have the compiler present at the time of execution.

No properties of a programming language require it to be exclusively compiled or exclusively interpreted. The categorization usually reflects the most popular method of language execution. For example, BASIC is thought of as an interpreted language and C a compiled language, despite the existence of BASIC compilers and C interpreters. Some systems use Just-in-time compilation (JIT) whereby sections of the source are compiled 'on the fly' and stored for subsequent executions.

 

Self-modifying Programs

A computer program in execution is normally treated as being different from the data the program operates on. However, in some cases this distinction is blurred when a computer program modifies itself. The modified computer program is subsequently executed as part of the same program. Self-modifying code is possible for programs written in Machine code, assembly language, Lisp, COBOL, PL/1 and Prolog, among others.

 

Execution and Storage

Typically, computer programs are stored in non-volatile memory until requested either directly or indirectly to be executed by the computer user. Upon such a request, the program is loaded into random access memory, by a computer program called an operating system, where it can be accessed directly by the central processor. The central processor then executes ("runs") the program, instruction by instruction, until termination. A program in execution is called a process. Termination is either by normal self-termination or by error — software or hardware error.

 

Embedded Programs





The microcontroller on the right of this USB flash drive is controlled with embedded firmware.

Some computer programs are embedded into hardware. A stored-program computer requires an initial computer program stored in its read-only memory to boot. The boot process is to identify and initialize all aspects of the system, from CPU registers to device controllers to memory contents. Following the initialization process, this initial computer program loads the operating system and sets the program counter to begin normal operations. Independent of the host computer, a hardware device might have embedded firmware to control its operation. Firmware is used when the computer program is rarely or never expected to change, or when the program must not be lost when the power is off.

Manual Programming





Switches for manual input on a Data General Nova

Computer programs historically were manually input to the central processor via switches. An instruction was represented by a configuration of on/off settings. After setting the configuration, an execute button was pressed. This process was then repeated. Computer programs also historically were manually input via paper tape or punched cards. After the medium was loaded, the starting address was set via switches and the execute button pressed.

Automatic Program Generation

Generative programming is a style of computer programming that creates source code through generic classes, prototypes, templates, aspects, and code generators to improve programmer productivity. Source code is generated with programming tools such as a template processor or an Integrated Development Environment. The simplest form of source code generator is a macro processor, such as the C preprocessor, which replaces patterns in source code according to relatively simple rules.

Software engines output source code or markup code that simultaneously become the input to another computer process. The analogy is that of one process driving another process, with the computer code being burned as fuel. Application servers are software engines that deliver applications to client computers. For example, a Wiki is an application server that allows users to build dynamic content assembled from articles. Wikis generate HTML, CSS, Java, and Javascript which are then interpreted by a web browser.

 

Simultaneous Execution

Many operating systems support multitasking which enables many computer programs to appear to be running simultaneously on a single computer. Operating systems may run multiple programs through process scheduling — a software mechanism to switch the CPU among processes frequently so that users can interact with each program while it is running. Within hardware, modern day multiprocessor computers or computers with multicore processors may run multiple programs.

 

Functional Categories

Computer programs may be categorized along functional lines. These functional categories are system software and application software. System software includes the operating system which couples the computer's hardware with the application software. The purpose of the operating system is to provide an environment in which application software executes in a convenient and efficient manner. In addition to the operating system, system software includes utility programs that help manage and tune the computer. If a computer program is not system software then it is application software. Application software includes middleware, which couples the system software with the user interface. Application software also includes utility programs that help users solve application problems, like the need for sorting.