Latest Post

Say Hello To The World

Written By ockyism on Senin, 17 Desember 2012 | 10.39

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam pharetra, tellus sit amet congue vulputate, nisi erat iaculis nibh, vitae feugiat sapien ante eget mauris. Cras elit nisl, rhoncus nec iaculis ultricies, feugiat eget sapien. Pellentesque ac felis tellus. Aenean sollicitudin imperdiet arcu, vitae dignissim est posuere id. Duis placerat justo eu nunc interdum ultrices.

Morbi eget sem at eros fermentum pulvinar non quis risus. Etiam eu tortor vel dolor congue lobortis at sed arcu. Sed eget nibh libero, vitae imperdiet orci. Sed elit risus, sodales nec vehicula eget, pharetra non justo. Nunc fringilla porttitor tincidunt. Suspendisse hendrerit egestas dolor a mattis. Sed at elit et nunc tristique accumsan at a libero. Mauris dolor purus, consequat sed tempus in, tempus id magna.

Integer commodo, leo nec porttitor congue, dui arcu semper lectus, ac dictum lacus velit sit amet mauris. Praesent et molestie dui. Vestibulum vulputate, nisl id interdum malesuada, massa leo eleifend velit, nec malesuada velit massa et magna. Aliquam auctor tortor sed lacus rhoncus fringilla. Sed gravida erat nec quam posuere fermentum. Donec et tempor erat. Quisque faucibus hendrerit erat, ac suscipit libero porta et.

Curabitur ligula justo, tincidunt nec interdum elementum, iaculis nec lorem. Maecenas ultricies faucibus magna, vel feugiat ante vehicula quis. Integer semper quam ac ligula ultricies pretium.


Created with Artisteer

Building Warm Relations

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam pharetra, tellus sit amet congue vulputate, nisi erat iaculis nibh, vitae feugiat sapien ante eget mauris. Cras elit nisl, rhoncus nec iaculis ultricies, feugiat eget sapien. Pellentesque ac felis tellus. Aenean sollicitudin imperdiet arcu, vitae dignissim est posuere id. 

Duis placerat justo eu nunc interdum ultrices. Phasellus elit dolor, porttitor id consectetur sit amet, posuere id magna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pharetra auctor pharetra. Nunc a sollicitudin est.

Curabitur ullamcorper gravida felis, sit amet scelerisque lorem iaculis sed. Donec vel neque in neque porta venenatis sed sit amet lectus. Morbi tristique posuere consequat.


Created with Artisteer

What is in My Blog?

Your blog is your personal online diary which combines the text, images and other media, and links to other blogs, web pages related to topics described in posts.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam pharetra, tellus sit amet congue vulputate, nisi erat iaculis nibh, vitae feugiat sapien ante eget mauris. Cras elit nisl, rhoncus nec iaculis ultricies, feugiat eget sapien. Pellentesque ac felis tellus. Aenean sollicitudin imperdiet arcu, vitae dignissim est posuere id. Duis placerat justo eu nunc interdum ultrices. Phasellus elit dolor, porttitor id consectetur sit amet, posuere id magna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pharetra auctor pharetra. Nunc a sollicitudin est. 


Created with Artisteer

Bilangan Biner, Oktal & Hexadesimal

Written By ockyism on Sabtu, 15 Desember 2012 | 08.20

BILANGAN BINER 
 
           Sistem bilangan biner atau sistem bilangan basis dua adalah sebuah sistem penulisan angka dengan menggunakan dua simbol yaitu 0 dan 1. Sistem bilangan biner modern ditemukan oleh Gottfried Wilhelm Leibniz pada abad ke-17. Sistem bilangan ini merupakan dasar dari semua sistem bilangan berbasis digital. Dari sistem biner, kita dapat mengkonversinya ke sistem bilangan Oktal atau Hexadesimal. Sistem ini juga dapat kita sebut dengan istilah bit, atau Binary Digit. Pengelompokan biner dalam komputer selalu berjumlah 8, dengan istilah 1 Byte/bita. Dalam istilah komputer, 1 Byte = 8 bit. Kode-kode rancang bangun komputer, seperti ASCII, American Standard Code for Information Interchange menggunakan sistem peng-kode-an 1 Byte.

20=1
21=2
22=4
23=8
24=16
25=32
26=64
dst

Perhitungan

Desimal Biner (8 bit)
0 0000 0000
1 0000 0001
2 0000 0010
3 0000 0011
4 0000 0100
5 0000 0101
6 0000 0110
7 0000 0111
8 0000 1000
9 0000 1001
10 0000 1010
11 0000 1011
12 0000 1100
13 0000 1101
14 0000 1110
15 0000 1111
16 0001 0000

             Perhitungan dalam biner mirip dengan menghitung dalam sistem bilangan lain. Dimulai dengan angka pertama, dan angka selanjutnya. Dalam sistem bilangan desimal, perhitungan mnggunakan angka 0 hingga 9, sedangkan dalam biner hanya menggunakan angka 0 dan 1.
contoh: mengubah bilangan desimal menjadi biner
desimal = 10.
           Berdasarkan referensi diatas yang mendekati bilangan 10 adalah 8 (23), selanjutnya hasil pengurangan 10-8 = 2 (21). sehingga dapat dijabarkan seperti berikut
10 = (1 x 23) + (0 x 22) + (1 x 21) + (0 x 20).
           dari perhitungan di atas bilangan biner dari 10 adalah 1010
dapat juga dengan cara lain yaitu 10 : 2 = 5 sisa 0 (0 akan menjadi angka terakhir dalam bilangan biner), 5(hasil pembagian pertama) : 2 = 2 sisa 1 (1 akan menjadi angka kedua terakhir dalam bilangan biner), 2(hasil pembagian kedua): 2 = 1 sisa 0(0 akan menjadi angka ketiga terakhir dalam bilangan biner), 1 (hasil pembagian ketiga): 2 = 0 sisa 1 (1 akan menjadi angka pertama dalam bilangan biner) karena hasil bagi sudah 0 atau habis, sehingga bilangan biner dari 10 = 1010
atau dengan cara yang singkat
10:2=5(0),
5:2=2(1),
2:2=1(0),
1:2=0(1) sisa hasil bagi dibaca dari belakang menjadi 1010
Cuma mau berbagi informasi tentang Sistem Bilangan. Berikut ini uraiannya. Bahwa ada beberapa sistem bilangan yang digunakan dalam sistem digital, yaitu : Bilangan Biner (Sistem Bilangan Basis Dua), Bilangan Oktal (Sistem Bilangan Basis Delapan), Bilangan Desimal (Sistem Bilangan Basis Sepuluh) dan Bilangan Heksadesimal (Sistem Bilangan Basis Enam Belas).
Kulik sistem bilangan biner terlebih dahulu yuuukkk…….
BILANGAN BINER
binary_numeral_system
Bilangan Biner merupakan bilangan yang memiliki radiks/basis 2, dengan notasi : (n)2;
Sistem bilangan biner adalah sebuah sistem penulisan angka dengan menggunakan dua simbol yaitu 0 dan 1. Untuk simbol angka 0 (nol) maka berarti False dan untuk simbol angka 1 (satu) maka berarti True. Ternyata Sistem bilangan biner modern ini ditemukan oleh Gottfried Wilhelm Leibniz pada abad ke-17. Dan Sistem bilangan ini merupakan dasar dari semua sistem bilangan berbasis digital.
Berikut tabel yang berupa contoh nilai bilangan desimal yang dinyatakan sebagai bilangan biner :
Desimal Biner (8 bit)

0 0000 0000
1 0000 0001
2 0000 0010
3 0000 0011
4 0000 0100
5 0000 0101
6 0000 0110
7 0000 0111
8 0000 1000
9 0000 1001
10 0000 1010
11 0000 1011
12 0000 1100
13 0000 1101
14 0000 1110
15 0000 1111
16 0001 0000
Catatan:
20=1, 21=2, 22=4, 23=8, 24=16, 25=32, 26=64 dst
Pembahasan sistem bilangan biner tuh gak hanya sampai di catatan terakhir diatas ?, tapii…… bilangan biner bisa mengalami konversi kebentuk bilangan oktal, bilangan desimal, dan bilangan heksadesimal. Nah, berikut merupakan pembahasan untuk pengkonversian bilangan biner ke bilangan lainnya.
KONVERSI DARI BINER KE OKTAL
Kalo’ bilangan biner itu radiks/basis nya 2, nah… sekarang akan dibahas konversi dari bilangan biner ke bilangan oktal yang memiliki radiks/basis 8 (Notasi : (n)8  dengan bilangan 0, 1, 2, 3, 4, 5, 6, dan 7).

Misal :
Ubahlah bilangan biner 11110011001 kedalam bilangan oktal
011 110 011 001
   3     6      3      1
Jadi hasil konversi bilangan biner 11110011001 adalah 3631.
Cara…nya…. A…da…lah…… (tu-wa-ga-pat :) ):
Karena biner nya 11 digit dan konversinya ke bilangan oktal, maka harus dikelompokkan masing-masing 3 digit, nah ternyata hasil pengelompokkan mengalami kekurangan digit jadii…… digit yang paling kiri ditambahkan digit 0 (nol) dan setelah dikelompokkan menjadi 3 digit, lalu perhitungannya dilakukan per kelompok dan memulai perhitungan per kelompoknya tetap dimulia dari lajur yang paling kanan ke kiri. Sehingga hasil konversinya adalah :
111100110012 = 36318;
Begitchuuu………
KONVERSI BINER KE HEXADESIMAL
Metode konversinya hampir sama dengan Biner ke Oktal. Namun pengelompokkannya sejumlah 4 bit. Empat kelompok bit paling kanan adalah posisi satuan, empat bit kedua dari kanan adalah puluhan, dan seterusnya.
Contohnya:
111000112 = …… 16
Solusi:
kelompok bit paling kanan: 0011 = 3
kelompok bit berikutnya: 1110 = E
Hasil konversinya adalah: E316.
KONVERSI DARI BINER KE DESIMAL

Misal :
0000 01012 (merupakan biner 8 digit) = …… 10
Cara menghitung:


Langkah 1 :
Let’s to know bahwa perhitungan untuk bilangan biner, harus dimulai dari lajur paling kanan ke kiri, nah perhitungannya seperti yang diuraikan dibawah ini nih…
0      0     0     0    0      1     0     1
27   26   25   24   23   22   21   20
Langkah 2 :
Yang angka biner 0 tidak dilakukan perhitungan sedangkan angka biner 1 dihitung, jadinya :
= (0×27)+(0×26)+(0×25)+(0×24)+(0×23)+(1×22)+(0×21)+(1×20)
= 0 + 0 + 0 + 0 + 0 + 4 + 0 + 1
= 510


Jadi bilangan biner dengan nilai 0000 01012 jika dikonversikan ke bilangan desimal maka nilai nya menjadi 510.
Jika bilangan biner nya 4 digit, maka konversi ke desimalnya juga menggunakan cara yang sama dengan bilangan biner 8 digit, yaitu menghitungnya dimulai dari lajur yang paling kanan ke kiri. Mudah kan…


Seperti pada bilangan desimal, dalam bilangan biner dapat dilakukan operasi aritmatika seperti penjumlahan, pengurangan, perkalian dan pembagian.

Penjumlahan Biner

Penjumlahan bilangan biner serupa dengan penjumlahan pada bilangan desimal. Dua bilangan yang akan dijumlahkan disusun secara vertikal dan digit-digit yang mempunyai signifikansi sama di tempatkan pada kolom yang sama. Digit-digit ini kemudian dijumlahkan dan jika jumlahnya lebih besar dari 1, maka ada bilangan yang disimpan, selanjutnya bilangan yang disimpan tersebut dijumlahkan dengan bilangan di sebelah kirinya.
Aturan dasar untuk penjumlahan pada bilangan biner adalah seperti berikut:
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 0, simpan 1

Sebagai contoh akan dijumlah dua bilangan biner 01012 + 00112 hasilnya 10002

tabel-penjumlahan 
Terkadang hasil penjumlahan bilangan lebih besar dari 2 jika hal tersebut terjadi, maka bilangan dapat disimpan lebih dari satu tempat, misalnya 1 + 1 + 1 +1 = 0 yang disimpan 10. Contoh soal 00012 + 00112 + 01012 + 01112 hasilnya 100002

tabel-penjumlahan-1

Pada kolom ke 3, bilangan yang disimpan ada dua bilangan yang berasal dari hasil penjumlahan pada kolom ke 5 yang nilai penjumlahannya adalah (100) dan kolom ke 4 yang nilai penjumlahannya adalah (10). Sedangkan bilangan yang disimpan pada kolom 1 dan 2 merupakan bilangan hasil dari penjumlahan pada kolom 3 yang nilai penjumlahannya adalah (100).

Pengurangan Biner

Metode yang digunakan dalam pengurangan bilangan biner juga sama dengan metode yang digunakan untuk pengurangan pada bilangan desimal. Dalam metode ini, jika diperlukan sebuah angka diperbolehkan meminjam 1 dari kolom yang mempunyai derajat lebih tinggi atau yang biasanya berada di sebelah kiri.

Aturan dasar untuk pengurangan bilangan biner adalah sebagai berikut:

0 – 0 = 0
1 – 0 = 1
1 – 1 = 0
0 – 1 = 1, pinjam 1

Sebagai contoh terdapat dua bilangan biner x dan y bilangan x = 01012 , bilangan y = 00112. Jika dilakukan operasi pengurangan maka 0101200112 hasilnya 00102, berikut penjelasannya:

- Pengurangan pada digit ke 4 dari x – y adalah 1 – 1 hasilnya 0.
- Pengurangan pada digit ke 3 dari x – y adalah 0 – 1 hasilnya 1, setelah angka 0 dari bilangan x meminjam angka 1 dari digit ke 2 dari bilangan x, sehingga digit ke 2 bilangan x berubah menjadi 0.
- Pengurangan pada digit ke 2 dari x – y adalah 0 – 0 hasilnya 0
- Pengurangan pada digit ke 1 dari x – y adalah 0 – 0 hasilnya 0

Perkalian Biner

Metode yang digunakan dalam perkalian biner juga pada dasarnya sama dengan perkalian desimal, akan terjadi pergeseran ke kanan setiap dikalikan 1 bit pengali. Setelah proses perkalian masing-masing bit pengali selesai, dilakukan penjumlahan masing-masing kolom bit hasil.
Contoh :

perkalian
Pembagian Biner

Serupa dengan perkalian, pembagian pada bilangan biner juga menggunakan metode yang sama dengan pembagian desimal. Bit-bit yang dibagi diambil bit per bit dari sebelah kiri. Apabila nilainya lebih dari bit pembagi, maka bagilah bit-bit tersebut, tetapi jika setelah bergeser 1 bit nilainya masih dibawah nilai pembagi maka hasilnya adalah 0.
Contoh :



DOWNLOAD : PDF SIESTEM BILANGAN BINE, OKTAL & HEXA DI SINI

Coldplay - Paradise (Live 2012 from Paris)

Written By ockyism on Selasa, 11 Desember 2012 | 11.51


CONTROL STRUKTUR DARI LOOP C++

Written By ockyism on Minggu, 09 Desember 2012 | 08.57



A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }:

{ statement1; statement2; statement3; }

Most of the control structures that we will see in this section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block.


Conditional structure: if and else

The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:

if (condition) statement

Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:

1
2
if (x == 100)
  cout << "x is 100";


If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }:

1
2
3
4
5
if (x == 100)
{
   cout << "x is ";
   cout << x;
}


We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:

if (condition) statement1 else statement2

For example:

1
2
3
4
if (x == 100)
  cout << "x is 100";
else
  cout << "x is not 100";


prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):

1
2
3
4
5
6
if (x > 0)
  cout << "x is positive";
else if (x < 0)
  cout << "x is negative";
else
  cout << "x is 0";


Remember that in case that we want more than a single statement to be executed, we must group them in a block by enclosing them in braces { }.

Iteration structures (loops)


Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop

Its format is:

while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true.
For example, we are going to make a program to countdown using a while-loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// custom countdown using while

#include <iostream>
using namespace std;

int main ()
{
  int n;
  cout << "Enter the starting number > ";
  cin >> n;

  while (n>0) {
    cout << n << ", ";
    --n;
  }

  cout << "FIRE!\n";
  return 0;
}
Enter the starting number > 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!


When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script (beginning in main):

  1. User assigns a value to n
  2. The while condition is checked (n>0). At this point there are two possibilities:
    * condition is true: statement is executed (to step 3)
    * condition is false: ignore statement and continue after it (to step 5)
  3. Execute statement:
    cout << n << ", ";
    --n;
    (prints the value of n on the screen and decreases n by 1)
  4. End of block. Return automatically to step 2
  5. Continue the program right after the block: print FIRE! and end program.

When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end.

Of course this is such a simple action for our computer that the whole countdown is performed instantly without any practical delay between numbers.

The do-while loop


Its format is:

do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// number echoer

#include <iostream>
using namespace std;

int main ()
{
  unsigned long n;
  do {
    cout << "Enter number (0 to end): ";
    cin >> n;
    cout << "You entered: " << n << "\n";
  } while (n != 0);
  return 0;
}
Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0


The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever.

The for loop


Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration.

It works in the following way:

  1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.
  2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed).
  3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
  4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop:

1
2
3
4
5
6
7
8
9
10
11
// countdown using a for loop
#include <iostream>
using namespace std;
int main ()
{
  for (int n=10; n>0; n--) {
    cout << n << ", ";
  }
  cout << "FIRE!\n";
  return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!


The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: for (;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop:

1
2
3
4
for ( n=0, i=100 ; n!=i ; n++, i-- )
{
   // whatever here...
}


This loop will execute for 50 times if neither n or i are modified within the loop:


n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

Jump statements.


The break statement


Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// break loop example

#include <iostream>
using namespace std;

int main ()
{
  int n;
  for (n=10; n>0; n--)
  {
    cout << n << ", ";
    if (n==3)
    {
      cout << "countdown aborted!";
      break;
    }
  }
  return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!


The continue statement


The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown:

1
2
3
4
5
6
7
8
9
10
11
12
13
// continue loop example
#include <iostream>
using namespace std;

int main ()
{
  for (int n=10; n>0; n--) {
    if (n==5) continue;
    cout << n << ", ";
  }
  cout << "FIRE!\n";
  return 0;
}
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!


The goto statement

goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).

Generally speaking, this instruction has no concrete use in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// goto loop example

#include <iostream>
using namespace std;

int main ()
{
  int n=10;
  loop:
  cout << n << ", ";
  n--;
  if (n>0) goto loop;
  cout << "FIRE!\n";
  return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!


The exit function


exit is a function defined in the cstdlib library.

The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:

 
void exit (int exitcode);


The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit code of 0 means that the program finished normally and any other value means that some error or unexpected results happened.

The selective structure: switch.

The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following:

switch (expression)
{
  case constant1:
     group of statements 1;
     break;
  case constant2:
     group of statements 2;
     break;
  .
  .
  .
  default:
     default group of statements
}

It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional).

Both of the following code fragments have the same behavior:

switch exampleif-else equivalent
switch (x) {
  case 1:
    cout << "x is 1";
    break;
  case 2:
    cout << "x is 2";
    break;
  default:
    cout << "value of x unknown";
  }
if (x == 1) {
  cout << "x is 1";
  }
else if (x == 2) {
  cout << "x is 2";
  }
else {
  cout << "value of x unknown";
  }

The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements -including those corresponding to other labels- will also be executed until the end of the switch selective block or a break statement is reached.

For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes it unnecessary to include braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example:

1
2
3
4
5
6
7
8
9
switch (x) {
  case 1:
  case 2:
  case 3:
    cout << "x is 1, 2 or 3";
    break;
  default:
    cout << "x is not 1, 2 nor 3";
  }


Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants.

If you need to check ranges or values that are not constants, use a concatenation of if and else if statements

Sumber : cplusplus.com

Cita - cita baruku

Written By ockyism on Rabu, 05 Desember 2012 | 10.39




Terdengar gila memang apabila mendengar dan melihat saya menulis di media sosial seperti facebook dan twitter

"saya ingin menjadi dosen" itu yang sering saya katakan. Hahaha...tapi itu lah tujuanku. Di mulai melihat uwa dari ibu saya yang sudah menjadi dosen puluhan tahun dan mengabdi ke pada nusa dan bangsa.

Keyakinan ini saya perkuat setelah melihat lagi ayah dari pacar saya yang juga seorang dosen, saya semakin ingin menjadi dosen.

Usaha dan do'a akan saya lakukan untuk berusaha menjadi dan meraih cita - cita ini dan Insya Allah suatu saat saya akan menjadi seorang dosen.
 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Ocky Hafidz Official - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger