06 Desember, 2009

Friend Function

Concept 
When a function needs to operate on private data in objects two different classes, the function can be declared as a friend in each of the classes, taking objects of the two classes as arguments.
// A common friend function to exchange the private values of two classes
#include <iostream.h>
class A;
class B; 

class A 

  private:
    int value1;
  public: 
    void in(int a)
    {
       value1=a;
    }
   void display()
   {
       cout<< value1;
   }
   friend void exchange(A&, B&); 
 }; 

class B 

   private:
     int value2;
   public:
     void in(int a) 
     {
        value2=a; 
     } 
     void display()
     {
        cout<< value2; 
     }
     friend void exchange (A&, B&); 
}; 

void exchange(A& x, B& y) 
{
   int temp=x.value1;
   x.value1=y.value2; 
   y.value2=temp; 


int main()

   A obj1;
   B obj2;
   obj1.in(1000);
   obj2.in(2000);
   cout<<"\n Before";
   obj1.display();
   obj2.display();
   cout<<"\n After";
   exchange(obj1, obj2);
   obj1.display();
   obj2.display();
   return 0;
}


Example
The following is an example of friend function's usage. The function show() is a friend of classes A and B which is used to display the private members of A and B. Instead of writing a separate function in each of the classes only one friend function can be used to display the data items of both the classes.
//Example - 1
#include<iostream.h>  
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 

class A 
{
  private: 
    int a;
  public: A() 
  { 
    a=0; 
  } 
  friend void show(A& x, B& y); 
}; 

class B 

   private: 
     int b; 
   public:
    B()
    {
      b=6;
    }
    friend void show(A& x, B& y);
}; 
void show(A& x, B& y) 
{
   cout << "A::a=" << x.a << endl;
   cout << "B::b=" << y.b << endl;
}

int main() 
{
   A a;
   B b;
   show(a,b);


//Example - 2
#include<iostream.h>
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 

class A 
{
  private:
    int a;
  public: 
    A() 
    {
       a=0; 
     } 
     void show(A& x, B& y); 
}; 

class B 
{
   private:
     int b;
   public:
     B()
     {
       b=6;
     }
     friend void A::show(A& x, B& y);
};

void A::show(A& x, B& y)
{
   cout << "A::a=" << x.a << endl;
   cout << "B::b=" << y.b << endl;
}

int main()
{
   A a;
   B b;
   a.show(a,b);
   return 0;
}

24 Oktober, 2009

constructor

Constructor merupakan suatu method yang akan memberikan nilai awal pada saat suatu objek dibuat. Pada saat program dijalankan, constructor akan langsung memberikan nilai awal pada saat perintah new, membuat suatu objek
Pada saat kita bekerja dengan constructor, hal mendasar yang perlu diperhatikan, yaitu:

1. Nama Constructor sama dengan nama Class.
2. Tidak ada return type yang diberikan kedalam Constructor Signature.
3. Tidak ada return stetement, didalam tubuh constructor.

class Lat801
{
float nilakhir;

Lat801(int nilai_akhir)
{
nilakhir = nilai_akhir;
}

public String grade()
{
String nilgrade;
if(nilakhir >= 80)
nilgrade = "A";
else if(nilakhir >= 68)
nilgrade = "B";
else if(nilakhir >= 56)
nilgrade = "C";
else if(nilakhir >= 49)
nilgrade = "D";
else
nilgrade = "E";

return nilgrade;
}

public void cetak()
{
System.out.println("Grade Nilainya = " + grade());
}

public static void main(String[] args)
{
Lat801 hasil = new Lat801(67);
hasil.cetak();
}
}


Constructor Overloading

Overloading adalah suatu cara membuat lebih dari constructor pada suatu class. Supaya pengaksesan constructor tersebut lancar, maka sebagai pembedanya adalah tipe parameter dan atau jumlah parameternya

class Lat802
{
float nilakhir, a;

Lat802(int nilai_akhir){
nilakhir = nilai_akhir;
}

Lat802(int nil1, int nil2){
nilakhir = ab + ac;
}

public String grade()
{
String nilgrade;
if(nilakhir >= 80)
nilgrade = "A";
else if(nilakhir >= 68)
nilgrade = "B";
else if(nilakhir >= 56)
nilgrade = "C";
else if(nilakhir >= 49)
nilgrade = "D";
else
nilgrade = "E";

return nilgrade;
}

public void cetak()
{
System.out.println("Grade Nilainya = " + grade());
}

public static void main(String[] args)
{
Lat802 hasil = new Lat802(67);
hasil.cetak();
Lat802 hasilnya = new Lat802(45, 35);
hasilnya.cetak();
}
}


Method Overloading

Method Overloading adalah suatu cara membuat lebih dari method pada suatu class. Supaya pengaksesan method tersebut lancar, maka sebagai pembedanya adalah tipe parameter dan atau jumlah parameternya. Untuk lebih jelasnya anda bisa lihat program dibawah ini :

class Perhitungan
{
static public int hitung(int a, int b)
{
return a + b;
}

static public double hitung(double a, double b, double c)
{
return (a + b)/c;
}
}

public class Lat803
{
public static void main(String[] args)
{
Perhitungan Ngitung = new Perhitungan();

int hitung;
double bagi;

hitung = Ngitung.hitung(4, 8);
bagi = Ngitung.hitung(55, 69, 2);

System.out.println("Hasil Perhitungan = " + hitung);
System.out.println("Hasil Pembagian = " + bagi);
}
}

konsep encapsulation

Encapsulation merupakan salah satu konsep yang sangat penting dalam pemrograman berorientasi obyek.
Konsep dasarnya sangat sederhana, yaitu memproteksi setiap atribut dari suatu class. Dalam hal ini atribut dari suatu class tidak boleh diakses secara langsung dari luar class. Maka tidak mengherankan bila setiap atribut lalu diberi visibility private. Lalu bagaimana bila suatu saat nilai dari atribut tersebut ingin diakses ataupun ingin diubah? Jawabannya sederhana saja, dengan menggunakan accessor dan mutator. Untuk melakukan akses terhadap nilai dari suatu atribut kita dapat menggunakan accessor, sedangkan untuk menlakukan pengubahan terhadap nilai dari suatu atribut kita dapat menggunakan mutator. Untuk lebih jelasnya dapat melihat contoh sederhana berikut ini.

//class dengan nama Kemeja
class Kemeja {
//atribut warna bertipe data String
private String warna;
//mutator untuk atribut warna
public void setWarna(String warna) {
this.warna = warna; //penggunaan kata kunci this
}
//accessor untuk atribut warna
public String getWarna() {
return warna;
}
}

Accessor secara konvensi akan selalu diawali dengan kata get dan diikuti dengan nama atribut yang akan diakses. Oleh karenanya accessor seringkali dikenal dengan nama getter.
Sedangkan mutator secara konvensi akan selalu diawali dengan kata set dan diikuti dengan nama atribut yang akan diubah nilainya. Oleh karenanya mutator seringkali dikenal dengan nama setter.
Pada setter seringkali juga digunakan kata kunci this. Penggunaan kata kunci this pada setter ini dibutuhkan ketika ada kesamaan antara nama parameter yang digunakan dengan nama atribut yang akan diubah nilainya. Kata kunci this digunakan untuk membedakan antara nama atribut dengan nama parameter.
Lalu apa konsekuensi dari penerapan encapsulation ini? Konsekuensinya sederhana saja. Misalkan kita akan membuat suatu objek dari class Kemeja.

Kemeja kemejaku = new Kemeja();

Maka ketika kita ingin memberi nilai "hijau" pada atribut kemejaku, kita tidak bisa melakukan hal semacam ini

kemejaku.warna = "biru";

Mengapa? Karena visibility dari atribut warna adalah private sehingga atribut tersebut tidak dapat diakses dari luar class. Yang dapat kita lakukan adalah dengan menggunakan setter seperti berikut ini

kemejaku.setWarna("biru");

Dan bila kita ingin mencetak nilai atrubut warna, kita dapat melakukannya dengan cara

System.out.println(kemejaku.getWarna());

20 Oktober, 2009

Typedef

typedef adalah keyword untuk membuat suatu tipe data baru dari tipe data yang sudah ada, atau lebih mudah disebut membuat alias.
typedef : type definition

jadi untuk membuat nama lain dari suatu tipe data, gunakan typedef.

misal, kita ingin membuat nama lain dari tipe data integer

typedef int intku;

maka kita bisa membuat variabel dengan tipe data integer dengan menggunakan intku.

intku nilai;
nilai = 10;

jadi variabel nilai adalah bertipe integer juga, dengan proses pembuatan menggunakan nama alias intku.

struct mahasiswa {
char nim[10];
}mhs, mhs2;

begitu juga dengan struct. 'struct mahasiswa' diatas adalah satu tipe data baru buatan kita sendiri. agar kita tidak terlalu panjang mendefinisikan variabel, lengkapi saja dengan typedef sehingga proses pembuatan variabel bisa langsung dengan nama struct tanpa dilengkapi keyword 'struct'

versi 1:
struct mahasiswa {
char nim[10];
};

//deklarasi variabel
struct mahasiswa mhs;

versi 2:
typedef struct mahasiswa{
char nim[10];
};

atau

typedef struct {
char nim[10];
}mahasiswa;

//deklarasi variabel
mahasiswa mhs;

Nested Struct

Di dalam sebuah struct dapat dimungkinkan terdapat sebuah struct lagi. Jadi hal ini dapat diartikan struct di dalam struct. Hampir mirip nested loop, yaitu for di dalam for.

Contoh :

struct tanggal {
int hari;
int bulan;
int tahun;
};

struct karyawan {
char NIP [10];
char nama [20];
struct tanggal tgl_masuk;
float gaji;
};


13 Oktober, 2009

The 11 Standard Template Library (STL) Headers

Headers for the STL "sequence containers"

<deque>

This header provides a double-ended queue container, with fast insertion and deletion at both ends and (somewhat counterintuitively to the abstract notion of queueness) direct access to any element.

<list>

This header provides a sequence container with fast performance when adding elements to, or removing elements from, any point in the sequence, but with only sequential access to any particular element.

<vector>

This header provides the vector container, which is best thought of as a generalized array, capable of "growing and shrinking" as the occasion demands. Vectors provide fast insertion and deletion at one end, and direct access to any element.

Headers for the STL "associative containers"

<map>

This header provides map and multimap classes which store key-value pairs. The map requires unique keys, but the multimap permits duplicate keys.

<set>

This header provides set and multiset classes which store keys. The set can store only unique keys, but the multiset permits duplicate keys.

Headers for the STL "container adaptors"

<queue>

This header provides containers which are actually "adapted" sequential containers and provide the usual FIFO behavior of a standard queue structure, as well as "priority queue" behavior.

<stack>

This header provides a container which is actually one of the above containers "adapted" to provide the usual LIFO behavior of a stack structure.

Headers for the STL algorithms

<algorithm>

This header provides a large number (about 70, depending on how you count) generic algorithm function templates for operating on iterators, as well as some other objects such as "function objects" that help algorithms to perform their tasks. It is part of the genius, power and flexibility of the STL that these algorithms do not operate on containers directly, but on iterators that point to containers. This means that under quite general conditions, the same algorithm can operate on several different containers, and in a variety of ways, which is, of course, the whole point of "generic programming".

<numeric>

This header declares a small number (four) of function templates specifically for numerical algorithms.

Headers for the STL iterators and function objects

<iterator>

This header provides classes and templates for defining and using iterators, though it does not have to be included if you are just using one or more of the sequential and/or associative containers and their associated iterators, since those iterators will be available from the container classes themselves.

<functional>

This header defines several function objects. These may also be called functionals, or functors. A function object is an object of a class that implements operator(). This permits the function object to be "called", using the same syntax as a function, to help an algorithm perform its task. But, because it is an object, it is more versatile than a function.

Miscellaneous STL headers

<memory>

This header declares functions and class templates for allocating and using memory. The average programmer will not need to include this header, since the default container "allocators" are perfectly adequate most of the time. Programmers who are developing their own containers, iterators and algorithms will be more inclined to find a use for what's in this header.

<utility>

This header declares the pair<> template, which is essential when using maps and multimaps, but also finds many uses in everyday programming. Though it may or may not be of interest to the average programmer, this header also defines the rel-ops namespace, which in turn defines relational operators in terms of == and <.

The 10 "stream-related" headers

<fstream>

This header declares some classes and other types for performing I/O with external files, as well as member functions for opening and closing files and testing whether a file is open. Under this header, class names are shown as they would appear in a typical object declaration, and member functions are presented in "typical usage" format.

fstream file;
Declare an fstream object file that can be used for reading input and/or writing output
fstream file(c_string_value);
Declare an fstream object file, connect it to the physical file whose name is in the C-string c_string_value, and open it for reading input and/or writing output
fstream file(c_string_value, openmode_value);
Declare an fstream object file, connect it to the physical file whose name is in the C-string c_string_value, and open it using the specific value of type openmode specified in openmode_value [See under <ios> for the definition of the openmode type.]

ifstream inFile;
Declare an ifstream object inFile that can be used for reading input
ifstream inFile(c_string_value);
Declare an ifstream object inFile, connect it to the physical file whose name is in the C-string c_string_value, and open it for reading input
ifstream inFile(c_string_value, openmode_value);
Declare an ifstream object inFile, connect it to the physical file whose name is in the C-string c_string_value, and open it using the specific value of type openmode specified in openmode_value [See under <ios> for the definition of the openmode type.]

ofstream outFile;
Declare an ofstream object outFile that can be used for writing output
ofstream outFile(c_string_value);
Declare an ofstream object outFile, connect it to the physical file whose name is in the C-string c_string_value, and open it for writing output
ofstream outFile(c_string_value, openmode_value);
Declare an ofstream object outFile, connect it to the physical file whose name is in the C-string c_string_value, and open it using the specific value of type openmode specified in openmode_value [See under <ios> for the definition of the openmode type.]

In each of the three groupings immediately above, the first form just declares a file stream object, while the other two both declare a file stream object and open a physical file attached to that object. However, if the first form is used to declare a file stream object, then the actual file has to be opened later via a call to the open function, which is what the two forms shown below provide.

anyFileStream.open(c_string_value)
Connect the file stream object anyFileStream with the physical file whose name is in the C-string c_string_value, open it in a default mode which will depend on the actual class type of anyFileStream, and return the this pointer if successful or a NULL pointer if unsuccessful
anyFileStream.open(c_string_value, openmode_value)
Connect the file stream object anyFileStream with the physical file whose name is in the C-string c_string_value, open it in a mode determined by openmode_value, and return the this pointer if successful or a NULL pointer if unsuccessful [See under <ios> for the definition of the openmode type.]

anyFileStream.is_open()
Return true if the file stream object anyFileStream is open, and otherwise false
anyFileStream.close()
Close the physical file associated with the file stream object anyFileStream, and disconnect the two

<iomanip>

This header declares the I/O manipulators that take parameters. They are presented in "typical usage" format.


The following three manipulators provide one mechanism for setting (or "unsetting") the format-state flags. There are member functions under <ios> that accomplish the same purpose.

setbase(int_value)
Set the base (or conversion radix) for a stream to int_value, which must be one of the following values, since any other value will be interpreted as 0: 10 (for decimal), 8 (for octal), or 16 (for hex)
setiosflags(fmtflags_value)
Set the format-state flags specified explicitly in fmtflags_value and leave the remaining flags unchanged (equivalent to stream.setf(fmtflags_value) under <ios>) [See <ios> as well for the definition of the fmtflags type.]
resetiosflags(fmtflags_value)
Clear the format-state flags specified explicitly in fmtflags_value and leave the remaining flags unchanged (equivalent to stream.unsetf(fmtflags_value) under <ios>) [See <ios> as well for the definition of the fmtflags type.]

The next three manipulators provide one mechanism for setting the format-state parameters. There are member functions under <ios> that accomplish the same purpose.

setfill(int_value)
Set the "fill" format-state parameter that determines the "fill character" when numerical values are output to the character whose internal integer code is int_value
setprecision(int_value)
Set the "precision" format-state parameter to int_value places for floating-point values
setw(int_value)
Set the "width" format-state parameter to int_value

<ios>

This header declares the classes, types, and manipulators that form the foundation of the C++ I/O library. A class called ios_base is the base class for all I/O stream classes, and a class template called basic_ios derives from ios_base and declares the behavior that is common to all I/O streams.
All manipulators and member functions in this subsection are presented in "typical usage" format.


The types in the following list are referred to in various places later under this header and elsewhere on this web page. When you encounter such a reference (as the type of a function parameter, say), you may want to look back here at one of these type definitions to verify that a parameter of that type makes sense for that function (for example).
This list gives only a high-level description of each typedef, which is further constrained by the fact that each actual type is implementation-defined. For further information, check this site's page on C++ Input/Output. The ellipsis (...) that appears in each list item is the placeholder for the actual type name.

fmtflags
An implementation-defined integer, enumerated, or bitmask type that represents formatting flags for I/O [Constant values of this type are: boolalpha, dec, fixed, hex, internal, left, oct, right, scientific, showbase, showpoint, showpos, skipws, unitbuf, uppercase, adjustfield, basefield, floatfield]
iostate
An implementation-defined integer, enumerated, or bitmask type that represents the status (error state, if you like) of an I/O stream [Constant values of this type are: badbit, eofbit, failbit, goodbit = iostate(0)]
openmode
An implementation-defined integer, enumerated, or bitmask type that defines the mode for opening a file [Constant values of this type are: app, ate, binary, in, out, trunc]
seekdir
An implementation-defined enumerated type that specifies the origin for seeking (moving the "read pointer" or "write pointer") to a new file position [Constant values of this type are: beg, cur, end]
streamoff
An implementation-defined type that represents a signed offset in a stream [Values of type streammoff may be converted to values of type streamsize without losing information.]
streamsize
An implementation-defined signed integral type used to represent the size of various stream entities, such as the number of characters to read or write in an I/O operation [Values of type streamsize may be converted to values of type streamoff without losing information.]

The following is a list of parameterless manipulators available from this header.

left
Left-justify all output
right
Right-justify all output
internal
Left-justify sign or base indicator, and right-justify rest of number
dec
Display integers in base 10 (decimal) format
oct
Display integers in base 8 (octal) format
hex
Display integers in base 16 (hexadecimal) format
fixed
Use fixed point notation when displaying floating-point numbers (the usual convention)
scientific
Use exponential (i.e., scientific) notation when displaying floating-point numbers
showbase
noshowbase
Show (or don't show) base indicator when displaying integer output
showpoint
noshowpoint
Show (or don't show) decimal point when displaying floating-point numbers (default is 6 significant digits)
showpos
noshowpos
Show (or don't show) a leading plus sign (+) when displaying positive numbers
uppercase
nouppercase
Use (or don't use) uppercase E when displaying exponential numbers, and uppercase letters when displaying hexadecimal numbers
boolalpha
noboolalpha
Use (or don't use) textual rather than numerical format to read and write boolean values (i.e., use, or don't use, true and false rather than 1 and 0)
skipws
noskipws
Skip (or don't skip) whitespace on input
unitbuf
nounitbuf
Flush (or don't flush) output buffer after each insertion (which really has nothing to do with formatting)

stream.clear()
Clear all stream error flags

stream.good()
Return true if no error has occurred (i.e., the next three functions all return false)
stream.eof()
Return true if end-of-file has been encountered while attempting an input operation
stream.fail()
Return true if an input or output operation failed
stream.bad()
Return true if input or output error was so severe that recovery is unlikely

stream.flags()
Return a value of type fmtflags that contains the current values of all format-state flags
stream.flags(fmtflags_value)
Return a value of type fmtflags that contains the current values of all format-state flags, set all flags in fmtflags_value, and clear all flags not mentioned in fmtflags_value
stream.setf(fmtflags_value)
Set format-state flags specified in fmtflags_value, leave all other format-state flags unchanged, and return a value of type fmtflags that contains the previous state of all flags
stream.setf(fmtflags_value, fmtflags_group)
Set format-state flags specified in fmtflags_value as the new flags for the flag group identified by fmtflags_group, leave all other format-state flags unchanged, and return a value of type fmtflags that contains the previous state of all flags Typical uses of the two-parameter version of this function look like this:
stream.setf(ios::left, ios::adjustfield)
stream.setf(0, ios::floatfield)
That last version clears all flags in the ios::floatfield bit field.
stream.unsetf(fmtflags_value)
Clear format-state flags specified in fmtflags_value and leave all other format-state flags unchanged

stream.fill()
Return current fill character format-state parameter value as a value of type char
stream.fill(char_value)
Return current fill character format-state parameter value as a value of type char, and set fill character format-state parameter to new value in char_value
stream.precision()
Return current precision format-state parameter value as a value of type streamsize
stream.precision(streamsize_value)
Return current precision format-state parameter value as a value of type streamsize, and set precision format-state parameter to new value in streamsize_value
stream.width()
Return current fieldwidth format-state parameter value as a value of type streamsize
stream.width(streamsize_value)
Return current fieldwidth format-state parameter value as a value of type streamsize, and set fieldwidth format-state parameter to new value in streamsize_value

<iosfwd>

This header provides forward declarations of the various I/O-related classes and templates, but can be ignored by most programmers most of the time. In any case, this header is included by <ios>.


<iostream>

This header declares the following four "standard stream objects". They are all initialized and "set up for business" before the main program begins, and are not destroyed during normal program execution, so they can be used throughout the life of a program. You can tell from the class of each object which member functions are available for use with that object by checking the class type of the object and looking under the header containing that class heading elsewhere in this subsection of the current web page.


extern istream cin
The "standard input stream"
extern ostream cout
The "standard output stream"
extern ostream cerr
The "standard error stream"
extern ostream clog
The "standard log stream"

<istream>

This header declares the input stream classes and templates, and one input manipulator. In addition to the member functions given below, the extraction operator, operator>>, is of course overloaded to permit reading primitive values into variables, as well as the reading of characters into C-style string variables and C++ string objects.


istream inStream;
Declare an istream object that can be used for reading input
iostream ioStream;
Declare an istream object that can be used for reading input and/or writing output

ws
A manipulator that causes whitespace characters to be skipped

inStream.peek()
Return integer code of next character to be read without changing stream position (i.e., without actually reading the character and removing it from the stream), or return the integer code for end-of-file if there is no such character
inStream.ignore()
Ignore the next character in the stream, if there is one, and return *this
inStream.ignore(positive_integer_value)
Ignore positive_integer_value characters, or all characters up to the end-of-file, whichever comes first, and return *this
inStream.ignore(positive_integer_value, char_delimiter_value)
Ignore positive_integer_value characters, or all characters up to, and including, the character in character_delimiter_value, whichever comes first, and return *this [The most generally useful form of this function looks something like this: inStream.ignore(80, '\n'), which is often used to ignore everything on the rest of a line of input.]

inStream.get()
Read and return the integer code of the next single character from inStream, or return the integer code for end-of-file if there are no more characters to be read
inStream.get(char_variable)
Read the next single character from inStream into char_variable, and return *this
inStream.putback(char_value)
Try to put the character in char_value back into inStream so that it will be the next character read from the input stream, and return *this
inStream.unget(char_value)
Same as inStream.putback(char_value) (see immediately above)

In the following list, note that the difference between get() and getline() is simply that get() leaves the delimiter in the input stream, while getline() removes it. Also, a technical point that can cause some confusion if it actually occurs, and should thus be noted, is this: In the case of getline(), if the maximum number of characters to be read is exactly the same as the number of characters available before the delimiter, then the delimiter is not actually "encountered", and is therefore left in the input stream on such an occasion. The +1 in the n+1 parameter value can be thought of as an allowance for the extra space to accommodate the terminating null character ('\0') that the C-style string variable (into which the characters are being read) must contain.

inStream.get(c_string_variable, n+1)
Read up to n characters (or up to the newline character, whichever comes first) into c_string_variable
inStream.get(c_string_variable, n+1, char_delimiter_value)
Read up to n characters (or up to the first occurrence of char_delimiter_value, whichever comes first) into c_string_variable
inStream.getline(c_string_variable, n+1)
Read up to n characters (or up to the newline character, whichever comes first) into c_string_variable
inStream.getline(c_string_variable, n+1, char_delimiter_value)
Read up to n characters (or up to the first occurrence of char_delimiter_value, whichever comes first) into c_string_variable

inStream.read(c_string_variable, streamsize_value)
Read up to streamsize_value characters, place them in c_string_variable, and return *this [Note that no null character is appended to c_string_variable.]
inStream.gcount()
Return the number of characters returned from the stream by the most recent call to an unformatted member function (get(), getline(), ignore(), peek(), putback(), read() or unget())

inStream.tellg()
Return current position in an input stream as a value of type streamoff [The name tellg is short for "tell get", i.e., "tell" the position at which you may "get" a value.]
inStream.seekg(streamoff_value)
Move the "read pointer" in an input stream to the explicit position, or "offset" (measured by default from the beginning of the stream) specified by streamoff_value [The name seekg is short for "seek get", i.e., "seek a (new) position at which you may "get" a value.]
inStream.seekg(streamoff_value, seekdir_value)
Move the "read pointer" in an input stream in a direction determined by seekdir_value and a distance specified by streamoff_value

<ostream>

This header declares the output stream class templates, specializations and manipulators. See <fstream> for derived classes that write to files, <sstream> for derived classes that write to strings, and <ios> for base-class declarations. In addition to the member functions given below, the insertion operator, operator<<, is of course overloaded to permit output of primitive values, as well as C-style strings and C++ string objects.


ostream outStream;
Declare an ostream object that can be used for writing output

endl
Insert newline and flush the output stream
ends
Insert a null character
flush
Flush an output stream

outStream.flush()
Flush the output buffer and return *this

outStream.put(char_value)
Write the character in char_value to the stream and return *this

outStream.write(c_string_value, streamsize_value)
Write streamsize_value characters from c_string_value to the output stream and return *this

outStream.tellp()
Return current position in an output stream as a value of type streamoff [The name tellp is short for "tell put", i.e., "tell the position at which you may "put", or write, a value.]
outStream.seekp(streamoff_value)
Move the "write pointer" in an output stream to the explicit position, or "offset" (measured by default from the beginning of the stream) specified by streamoff_value [The name seekp is short for "seek put", i.e., "seek" a (new) position at which you may "put", or write, a value.]
outStream.seekp(streamoff_value, seekdir_value)
Move the "write pointer" in an output stream in a direction determined by seekdir_value and a distance specified by streamoff_value

<sstream>

This header declares classes, templates and other types for reading from and writing to string objects in memory in the same manner as reading from and writing to files.


The following declarations parallel the analogous declarations for file streams under <fstream>. In each case a string buffer is created in memory, which can then be used for input and/or output, as the case may be.

istringstream inStringStream;
Declare an istringstream object which is initially empty, but which can be used for input (after something is placed in it, of course)
istringstream inStringStream(string_variable);
Declare an istringstream object which has its buffer initialized with the contents of string_variable and which can be used for input
ostringstream outStringStream;
Declare an ostringstream object which is initially empty, but which can be used for output
ostringstream outStringStream(string_variable);
Declare an ostringstream object which has its buffer initialized with the contents of string_variable and which can be used for output
stringstream ioStringStream;
Declare a stringstream object which is initially empty, but which can be used for either input or output
stringstream ioStringStream(string_variable);
Declare a stringstream object which has its buffer initialized with the contents of string_variable and which can be used for either input or output

anyStringStream.str()
Return the contents of the string buffer associated with the stream as a string value
anyStringStream.str(string_variable)
Deallocate the current buffer and replace it with the contents of string_variable

<streambuf>

This header declares the basic_streambuf class template and its streambuf specialization, which provides a stream buffer object to manage low-level access to a sequence of characters. This header is not normally needed in day-to-day programming.


<strstream>

This header declares classes, templates and other types for reading from, and writing to, character arrays in memory, in the same manner as reading from and writing to files. This header and its classes are actually deprecated in the Standard, another hint that programmers should really be using C++ string objects and the facilities from <sstream> instead.

Big-O

Does Big-O tell the whole story?
• Tx(n) = Ty(n) = O(lg n)

T1(n)=50+3n+(10+5+15)n = 50+33n
setup of algorithm -- takes 50 time units
read n elements into array -- 3 units/element
for i in 1..n loop
do operation1 on A[i] -- takes 10 units
do operation2 on A[i] -- takes 5 units
do operation3 on A[i] -- takes 15 units

T2(n)=200+3n+(10+5)n = 200+18n
setup of algorithm -- takes 200 time units
read n elements into array -- 3 units/element
for i in 1..n loop
do operation1 on A[i] -- takes 10 units
do operation2 on A[i] -- takes 5 units

Linear Search
• If data distributed randomly
– Average case:
• N/2 comparisons needed
– Best case:
• values is equal to first element tested
– Worst case:
• value not in list -> N comparisons needed
Linear Search is O(N)

Binary Search
• Can be performed on
– Sorted arrays
– Full and balanced BSTs
• Compares and cuts half the work
– We cut work in ½ each time
– How many times can we cut in half?
Binary Search is O(Log N)

Insertion to a Sorted Array
• Sorted Array
– Finding the right spot – O(Log N)
– Performing the shuffle – O(N)
– Performing the insertion - O(1)
Total work: O(Log N + N + 1) = O(N)

Insertion into a F&B BST
• Finding the right spot – O(Log N)
• Performing the insertion – O(1)
Total work: O(Log N + 1) = O(Log N)

Insertion Sort – O(N2)
• Assume you are sorting 250,000,000 item
N = 250,000,000 N^2 = 6.25 * 10^16
Assume you can do 1 operation/nanosecond
-> 6.25 * 10^7 seconds
= 1.98 years

Merge Sort – O(N * Log N)
• Assume you are sorting 250,000,000 item
N = 250,000,000
N*Log N = 250,000,000 * 28
Assume you can do 1 operation/nanosecond
-> 7.25 seconds

Function Definitions & Function Prototypes

Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}

– Function-name: any valid identifier
– Return-value-type: data type of the result (default int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares parameters
• A type must be listed explicitly for each parameter unless, the parameter is of type int
– Definitions and statements: function body (block)
• Variables can be defined inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace
• If something returned
– return expression;

Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after use in program
– The function with the prototype
int maximum( int x, int y, int z );
• Takes in 3 ints
• Returns an int
• Promotion rules and conversions
– Converting to lower types can lead to errors


15 September, 2009

Dasar-dasar C++

C++ adalah sebuah bahasa pemrograman yang memiliki banyak dialek, seperti bahasa orang yang banyak memiliki dialek. Dalam C++, dialek bukan disebabkan oleh karena si pembicara berasal dari Jepang atau Indonesia, melainkan karena bahasa ini memiliki beberapa kompiler yang berbeda. Ada empat kompiler umum yaitu : C++ Borland, C++ Microsoft Visual, C/386 Watcom, dan DJGPP. Anda dapat mendownload DJGPP atau mungkin saja anda telah memiliki kompiler lain.

Setiap kompiler ini agak berbeda. Setiap kompiler akan dapat menjalankan fungsi fungsi standar C++ ANSI/ISO, tetapi masing masing kompiler juga akan dapat menjalankan fungsi fungsi nonstandard (fungsi fungsi ini, agak mirip dengan ucapan yang tidak standar yang diucapkan orang diberbagai pelosok negeri. Sebagai contoh, di New Orleans kata median disebut neutral ground). Kadang kadang pemakaian fungsi nonstandard akan menimbulkan masalah pada saat anda hendak mengkompilasi kode sumber data (source code) (yaitu program berbahasa C++ yang ditulis oleh seorang programer) mempergunakan kompiler yang berbeda. Tutorial ini tidak terlepas dari masalah seperti itu.

Bila anda belum mempunyai sebuah kompiler, disarankan agar anda segera memiliki sebuah kompiler. Sebuah kompiler sederhana sudah cukup untuk dipergunakan oleh anda dalam mengikuti tutorial ini.

Bahasa pemrograman C++ adalah bahasa yang amat berbeda. Untuk kompiler C++ berbasis DOS, akan memerlukan beberapa kata kunci (keywords); keyword sendiri tidak cukup untuk difungsikan sebagai input dan output. Walau hampir semua fungsi dalam file library tampaknya bias diakses oleh header filenya. Coba kita lihat program sesungguhnya :
#include
int main()
{cout<<”HEY, you, I’m alive! Oh, and Hello World!”;
return 0;}

Marilah kita lihat elemen dari program diatas. Tanda #include adalah sebuah prosesor pengarah yang mengatakan kepada kompiler untukmeletakan kode dari header file iostream.h kedalam program. Dengan menyertakan header file, anda dapat mengakses banyak fungsi fungsi berbeda. Dalam contoh diatas, fungsi cout memerlukan file iostream.h.

Pada baris berikutnya yang penting adalah int main(). Baris ini mengatakan kepada kompiler bahwa ada sebuah fungsi bernama main, yang mana fungsi itu mengembalikan sebuah integer, sehingga diberi tanda int. Tanda kurung ({ dan }) menandakan awal dan akhir fungsi dalam program diatas dan menghentikan kode lainnya. Jika anda memakai bahasa Pascal, anda akan mempergunakan perintah BEGIN dan END.

Baris berikutnya dari program diatas agak aneh. Jika anda menulis sebuah program mempergunakan bahasa lain, anda akan mengetahui bahwa perintah print akan menampilkan text di layar monitor. Dalam bahasa C++ tidaklah demikian, pemakaian fungsi cout dipakai untuk menampilkan text di layar monitor anda. Itu juga memakai tanda atau symbol <;<; , yang diketahui sebagai operator pemasukan ( insertion operators). Tanda tersebut mengatakan kepada kompiler agar segera menghasilkan output sesuai dengan input anda. Tanda semicolon ditambahkan kedalam bagian akhir dari semua fungsi yang dipanggil dalam bahasa C++; tanda seterusnya memperlihatkan variable yang anda deklarasikan.

Pada baris itu juga ada kode yang memerintahkan fungsi main kembali ke 0. Pada saat satu kali kembali diproses, itu dilakukan melalui system operasi. Sebagai catatan, pendeklarasian fungsi main yang tidak diinginkan memiliki proses kembali, dapa ditambahkan – void main() – dan biasanya itu berfungsi dengan baik; namun cara ini merupakan cara yang kurang baik.
Tanda kurung terakhir berperan sebagai penutup agar fungsi dihentikan. Anda bisa mencoba mengoperasikan fungsi ini didalam sebuah kompiler. Anda dapat melakukan cut dan paste kode diatas kedalam sebuah file, dan menyimpannya sebagai file.cpp, dan kemudian anda buka file itu dari dalam kompiler anda. Jika anda memakai baris perintah kompiler seperti yang ada dalam Borland C++ 5.5, sebaiknya anda membaca dahulu instruksi kompiler tentang bagaimana cara melakukan kompilasi (how to compile).

Comment atau komentar sering dipakai dalam penulisan program. Ketika anda mengatakan kepada kompiler bahwa sebuah bagian dari program anda adalah tex komentar, kompiler tidak akan memasukan itu sebagai perintah pemrograman. Untuk membua sebuah komentar dipergunakan tanda //, yang mengaakan kepada kompiler bahwa baris berikut adalah komentar, atau memakai tanda /* dan kemudian diakhiri tanda */ untuk menandai bahwa segala yang ada antara kedua tanda ini adalah komentar. Beberapa kompiler akan mengubah warna area komentar, tetapi beberapa kompiler lain tidak. Berhati hatilah dalam menulis program anda agar kode program anda tidak dianggap sebagai komentar oleh kompiler karena dapat mempengaruhi output program yang anda buat.

Selanjutnya anda harus dapa menuliskan program sederhana untuk menampilkan informasi yang anda ketikan kedalamnya. Selain itu, program juga bisa dibuat untuk menerima input. Fungsi yang dipakai adalah cin, dan diikuti dengan tanda >>.

Tentu saja sebelum anda mencoba menerima input, anda harus memiliki tempat penyimpan input. Dalam pemrograman, input dan data disimpan dalam variable. Ada beberapa jenis variable. Pada saat anda ingin mengatakan kepada kompiler sebuah variable yang anda deklarasikan, anda harus menyertakan tipe data dan nama dari variable itu. Beberapa cara dasar adalah dengan menuliskan include char, int, dan float.

Sebuah variabel char menyimpan sebuah karakter tunggal; variabel int akan menyimpan integer (bukan bilangan desimal), dan variables float akan menyimpan bilangan desimal. Setiap variable – char, int, dan float – merupakan sebuah kata kunci (keyword) yang and pergunakan pada saat anda mendeklarasikan sebuah variabel. Untuk mendeklarasikan sebuah variable anda memakai syntax type . Ini diijinkan untuk mendeklarasikan variable multiple dari jenis variable yang sama pada baris yang sama; masing masing variabelnya dipisahkan dengan tanda koma. Deklarasi sebuah variable atau sekelompok variabel dapat diikuti tanda semicolon (Catatan, tanda ini sama dengan yang diterapkan pada prosedur dimana anda akan memanggil sebuah fungsi).

Jika anda tidak memakai sebuah variable yang dideklarasikan sebelumnya. program anda tidak akan dapat dioperasikan (atau di run), dan anda akan menerima pesan error yang memberitahu anda bahwa anda telah melakukan kesalahan.

Berikut adalah beberapa contoh deklarasi variable:
int x;
int a, b, c, d;
char letter;
float the_float;

sumber

Bahasa Pemrograman C++

Sejarah C++
Mulai awal tahun 1980, Bjarne Stroustrup dari AT & T Bell Laboratories mulai mengembangkan bahasa C. Pada tahun 1985, lahirlah secara resmi bahasa baru hasil pengembangan C yang dikenal dengan nama C++. Sebenarnya bahasa C++ mengalami dua tahap evolusi. C++ yang pertama, dirilis oleh AT&T Laboratories, dinamakan cfront. C++ versi kunoini hanya berupa kompiler yang menterjemahkan C++ menjadi bahasa C. Pada evolusi selanjutnya, Borland International Inc. mengembangkan kompiler C++ menjadi sebuah kompiler yang mampu mengubah C++ langsung menjadi bahasa mesin (assembly). Sejak evolusi ini, mulai tahun 1990 C++ menjadi bahasa berorientasi obyek yang digunakan oleh sebagian pemrogram profesional.


Kelebihan C++

  1. Merupakan induk dari bahasa pemrograman perl, php, phyton, visual basic, gambas, java, C#
  2. Compiler bahasa C++ terdapat di semua platform
  3. Untuk pengembangan visual dijejali dengan platform yang sangat banyak seperti OWL, MFC, Cocoa, QT, GTK, dll
  4. Merupakan pemrograman berorientasi objek.
  5. Penanganan kompleksitas dengan OOP
  6. Bahasa C++ tersedia hampir di semua jenis komputer.
  7. Kode bahasa C++ dengan portabilitas dan fleksibilitas yang tinggi untuk semua jenis komputer.
  8. Bahasa C++ hanya menyediakan sedikit kata-kata kunci (hanya terdapat 48 kata kunci).
  9. Proses eksekusi program bahasa C++ lebih cepat. Dengan demikian, aplikasi yang dibuat dengan bahasa C++ akan menjadi aplikasi yang efisien dan kompetitif.
  10. Dukungan pustaka fungsi dan kelas yang banyak sehingga memungkinkan pembuatan aplikasi makro.
  11. C++ adalah bahasa yang terstruktur, dengan demikian akan lebih mendukung OOP.
  12. Bahasa C++ termasuk bahasa tingkat menengah dan lebih dekat dengan bahasa mesin.
  13. Kode program bersifat reuseable, sehingga dapat digunakan kembali pada project lain dengan hanya menggunakan library dan file header.
  14. C++ dapat membuat aplikasi graphic processor berkualitas tinggi.

Kekurangan C++

  1. C++ tidak murni OOP sehingga kurang cocok untuk mengajarkan Konsep OOP karena kaidah-kaidah OOP dapat dilanggar. Dan di C++ ada konsep pointer yang sangat membingunkan, ini salah satu alasan mengapa C++ menjadi momok yg paling tidak disukai.
  2. C++ walapun tidak terpengaruh oleh Sistem Operasi tetapi tool untuk developmentnya harus spesific pada salah satu sistem operasi contoh Visual Studio hanya dapat berjalan di Windows. Alasan ini juga nantinya akan dapat menurunkan minat terhadap sistem operasi yang lain contohnya Linux. Apabila dalam praktiknya menggunakan Visual Studio maka otomatis akan menggunakannya juga dan pada akhirnya malas untuk mencoba sistem operasi yang lain.
  3. Implementasi C++ dalam teknologi IT pada saat sekarang sudah sangat sedikit sekali.
  4. "susah" untuk membuat sesuatu dengan C++ sehingga kepeminatannya dalam memperdalam Programming akhirnya harus kandas kecuali dengan inisitif sendiri mempelajari bahasa/teknologi lain.
  5. Bahasa ini cukup sulit untuk dipelajari dan dipahami.
  6. Banyaknya operator serta fleksibilitas penulisan program kadang-kadang membingungkan pemakai.
  7. Bagi pemula pada umumnya akan kesulitan menggunakan pointer.

Aplikasi C++

  1. Sebagai bahasa pemrograman di Windows, UNIX, Linux.
  2. Visual C++ dapat dibuat aplikasi apa saja seperti database.
  3. Bahasa untuk pembuatan system operasi, game, system kendali,pembuatan aplikasi
  4. Untuk membuat bahasa baru atau membuat compiler bahasa baru
  5. Untuk menulis komponen dan file-file pustaka bahasa lain.

Contoh
//my first program in C++
#include
int main()
{ cout << “Selamat pagi dunia!”; return 0;} Hasil :

Selamat pagi dunia!

sumber1
sumber2
sumber3