Tuesday 30 August 2016

7. Pengambilan Keputusan C# (Basic/Dasar)

Hello guys kali ini kita akan membahas tentang pengambilan keputusan dalam pemrograman, pengambilan keputusan dalam bahasa pemrograman. Pengambilan keputusan sangatlah penting dalam dunia pemrograman dan ini paling banyak dipakai saat melakukan pengecekan kondisi dan menjalankan logika ketika program berjalan.

Yang paling umum dipakai dalam bahasa pemrograman adalah syntax:

if(kondisi) // jika kondisi benar maka jalankan
{
    jalankan logika
}
else if(kondisi yang lainnya) // jika kondisi benar maka jalankan
{
    jalankan logika dengan kondisi yang lainnya
}
else // jika kondisi tidak ada yang benar maka jalankan
{
    jalankan logika yang lain jika tidak termasuk dalam kondisi sebelumnya
}

Secara umum bisa diilustrasikan sebagai berikut:


1. IF Statement



IF statement adalah untuk melakukan pengecekan hanya pada satu kondisi tertentu tanpa ada alternatif kondisi yang lain.

if(kondisi)
{
    jalankan logika
}

Contoh program untuk simulasi kondisi if:

using System;
namespace DecisionMaking
{
   class Program
   {
      static void Main(string[] args)
      {
         /* local variable definition */
         int a = 10;
         /* check the boolean condition using if statement */
         if (a < 20)
         {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 20");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

Hasil program ketika dijalankan:

a is less than 20;
value of a is : 10

2. IF ... ELSE Statement


If ... else statement digunakan untuk melakukan pengecekan pada beberapa alternatif kondisi, jika kondisi pertama tidak ada maka jalankan pengecekan pada kondisi yang lainnya.

if(kondisi_1)
{
    jalankan logika 1
}
else if(kondisi_2)
{
    jalankan logika 2
}
else
{
    jalankan logika jika tidak termasuk salah satu dari kondisi sebelumnya
}

Berikut adalah contoh untuk statement if ... else:

using System;
using System;
namespace DecisionMaking
{
   class Program 
   {
      static void Main(string[] args)
      {
         /* local variable definition */
         int a = 100;
         
         /* check the boolean condition */
         if (a == 10)
         {
            /* if condition is true then print the following */
            Console.WriteLine("Value of a is 10");
         }
         
         else if (a == 20)
         {
            /* if else if condition is true */
            Console.WriteLine("Value of a is 20");
         }
         
         else if (a == 30)
         {
            /* if else if condition is true  */
            Console.WriteLine("Value of a is 30");
         }
         
         else
         {
            /* if none of the conditions is true */
            Console.WriteLine("None of the values is matching");
         }
         Console.WriteLine("Exact value of a is: {0}", a);
         Console.ReadLine();
      }
   }
}

Setelah program dijalankan akan mendapatkan hasil sebagai berikut:

None of the values is matching
Exact value of a is: 100

3. IF Statement di dalam IF (Bersarang)

Kondisi if bersarang adalah pengecekan dimana kita melakukan pengecekan lagi dengan kondisi if didalam blok if.

if(kondisi_1)
{
    jalankan logika

    if(kondisi_3)
    {
        jalankan logika
    }
}
else if(kondisi_2)
{
    jalankan logika

    if(kondisi_4)
    {
        jalankan logika
    }
}
else
{
    jalankan logika
}

Berikut adalah contoh program untuk kondisi bersarang:

using System;
namespace DecisionMaking
{
   class Program
   {
      static void Main(string[] args)
      {
         //* local variable definition */
         int a = 100;
         int b = 200;
         
         /* check the boolean condition */
         if (a == 100)
         {
            /* if condition is true then check the following */
            if (b == 200)
            {
               /* if condition is true then print the following */
               Console.WriteLine("Value of a is 100 and b is 200");
            }
         }
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.WriteLine("Exact value of b is : {0}", b);
         Console.ReadLine();
      }
   }
}

Hasil setelah program dijalankan:

Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

4. SWITCH Statement


Switch statement digunakan untuk melakukan pengecekan untuk beberapa kondisi sekaligus, jika kondisi sudah di temukan maka akan keluar dari blok switch dengan statement break.

switch(ekspresi)
{
    case konstanta-ekspresi:
        jalankan logika
        break;

    case kontanta-ekspresi:
        jalankan logika
        break;

    default:
        jalankan logika jika tidak ada yang cocok dengan konstanta-ekspresi
}

Dari format diatas terdapat default, fungsi default disini adalah sama dengan kondisi else pada statement if ... else.

Contoh program untuk kondisi switch:

using System;
namespace DecisionMaking
{
   class Program
   {
      static void Main(string[] args)
      {
         /* local variable definition */
         char grade = 'B';
         
         switch (grade)
         {
            case 'A':
               Console.WriteLine("Excellent!");
               break;
            case 'B':
            case 'C':
               Console.WriteLine("Well done");
               break;
            case 'D':
               Console.WriteLine("You passed");
               break;
            case 'F':
               Console.WriteLine("Better try again");
               break;
               default:
            Console.WriteLine("Invalid grade");
               break;
         }
         Console.WriteLine("Your grade is  {0}", grade);
         Console.ReadLine();
      }
   }
}

Setelah program dijalankan akan mengeluarkan hasil sebagai berikut:

Well done
Your grade is B

5. SWITCH Statement di dalam SWITCH (Bersarang)

Pada dasarnya sama seperti switch statement hanya saja ada pengecekan dengan switch lagi.

Berikut adalah contoh program untuk switch bersarang:

using System;
namespace DecisionMaking
{
   class Program 
   {
      static void Main(string[] args)
      {
         int a = 100;
         int b = 200;
         
         switch (a) 
         {
            case 100: 
            Console.WriteLine("This is part of outer switch ");
            switch (b)
            {
               case 200:
               Console.WriteLine("This is part of inner switch ");
               break;
            }
            break;
         }
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.WriteLine("Exact value of b is : {0}", b);
         Console.ReadLine();
      }
   }
} 

Hasil setelah program dijalankan:

This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

Kita juga bisa melakukan kombinasi antara kondisi if else dengan switch untuk mendapatkan hasil pengambilan keputausan yang baik.

Operator (kondisi) ? (jalankan logika)  : (jalankan logika lainnya):

Operator ? : adalah operator untuk shortcut kondisi if ... else, biasanya digunakan untuk pengecekan yang tidak memerlukan statement logika yang panjang.

ekspresi_1 ? ekspresi_2 : ekspresi_3;

Akan melakukan pengecekan pada ekspresi_1 jika ekspresi_1 bernilai benar maka jalankan ekspresi_2 jika tidak maka jalankan ekspresi_3.

Contoh program untuk simulasi (kondisi) ? (jalankan logika)  : (jalankan logika lainnya):

namespace DecisionMaking
{
   class Program 
   {
      static void Main(string[] args)
      {
         bool m_bool = true;

         // melakukan pengecekan jika m_bool bernilai benar maka isi a dengan 100
         // tetapi jika m_bool bernilai salah maka isi a dengan 50
         int a = m_bool ? 100 : 50;
         
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

Hasil keluaran program akan seperti berikut:

Exact value of a is : 100

Ok guys selamat berkarya dan belajar, sampai ketemu lagi di next tutorial Loot/Pengulangan.

Monday 29 August 2016

6. Variabel, Konstanta dan Operator C# (Basic/Dasar)

1. Variabel

Variabel tidak lain adalah untuk menyimpan data pada program kita sehingga program dapat memanipulasi data tersebut. Variabel akan menyimpan tipe data berdasarkan besar ukuran dan layout memori. Berikut adalah daftar kategori dan tipe data dalam C#:

TypeExample
Integral typessbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point typesfloat and double
Decimal typesdecimal
Boolean typestrue or false values, as assigned
Nullable typesNullable data types
Selain tipe data diatas juga terdapat tipe data enum dan class tetapi tidak akan kita bahas dalam bab ini guys.

Mendefinisikan Variabel

Untuk mendefinisikan variable dalam C# menggunakan format syntax sebagai berikut:

<data_type> <variable_list>;

data_type merupakan tipe data yang valid dalam C#, termasuk int, char, float, double atau tipe yang lain. Sedangkan variable_list merupakan nama dari variabel yang dipisahkan dengan koma jika lebih dari satu.

Contoh:

int i, j, k;
char c, ch;
float f, salary;
double d;

Kita dapat menginisialisasi nilai variabel dengan cara:

int i = 100;

Menginisialisasi Variabel

Menginisialisasi variabel atau bahasa gampangnya mengisi variabel dengan suatu nilai adalah dengan menggunakan tanda samadengan (=) kemudian diikuti dengan nilai yang akan di masukkan. Format untuk inisialisasi variabel adalah sebagai berikut:

variable_name = value;

Variabel juga bisa diinisalisasi ketika mendeklarasikan variabel tersebut, dengan format sebagai berikut:

<data_type> <variable_name> = value;

sebagai contoh:

int d = 3, f = 5;    /* menginisialisasi d and f. */
byte z = 22;         /* menginisialisasi z. */
double pi = 3.14159; /* mendeklarasikan nilai pi. */
char x = 'x';        /* mengisi nilai dengan karakter 'x'. */

berikut adalah contoh program untuk mensimulasikan inisialisasi variabel:

using System;
namespace VariableDefinition 
{
   class Program 
   {
      static void Main(string[] args) 
      {
         short a;
         int b ;
         double c;

         /* actual initialization */
         a = 10;
         b = 20;
         c = a + b;
         Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
         Console.ReadLine();
      }
   }
}

setelah program dijalankan akan memberikan keluaran sebagai berikut:

a = 10, b = 20, c = 30

Menerima Masukan Dari User kemudian diisikan ke dalam Variabel

Dalam library C# terdapat fungsi Readline di dalam class Console tepatnya di dalam System.Console.Readline(). Yang dapat digunakan untuk mendapatkan input dari user untuk mengisi nilai variabel.

sebagai contoh:

int num;
num = Convert.ToInt32(Console.ReadLine());

kita perlu mengkonversi input dari user berupa kedalam tipe int, karena tipe dari variabel num adalah int. Yang perlu diingat adalah hasil dari Console.Readline() adalah sebuah string.

2. Konstanta

Konstanta adalah sebuah nilai yang tidak dapat diubah, konstanta berisi tipe data yang valida dalam bahasa pemrograman, seperti int, float, string atau class. Nilai yang tidak dapat diubah ubah ini sering disebut sebagai literals.

Konstanta sebenernya sama dengan varibel hanya saja nilainya tidak dapat diubah ubah.

Integer Literals

Integer literals dapat berupa konstanta desimal atau hexadesimal. Awalan pada pendefinisian akan menunjukkan apakah itu desimal atau hexadesimal. Untuk hexadesimal akan diawali dengan 0x atau 0X, sedangkan untuk nilai desimal tidak ada awalan pada saat pendefinisian.

Integer literals juga bisa memiliki akhiran untuk mendefinisikan tipe data, misalnya U dan L untuk mendefinisikan Unsigned Long. Akhiran ini bisa dalam huruf besar atau kecil.

berikut adalah contoh integer literals:

212         /* Legal */
215u        /* Legal */
0xFeeL      /* Legal */
85         /* decimal */
0x4b       /* hexadecimal */
30         /* int */
30u        /* unsigned int */
30l        /* long */
30ul       /* unsigned long */

Floating Point Literals

Floating point literals terdiri dari integer, desimal, pecahan dan juga perpangkatan atau eksponensial. Kita dapat mendefinisikan floating point dengan menggunakan desimal atau eksponensial.

berikut contoh ekspresi untuk floating point literals:

3.14159       /* Legal */
314159E-5L    /* Legal */
510E          /* Illegal: incomplete exponent */
210f          /* Illegal: no decimal or exponent */
.e55          /* Illegal: missing integer or fraction */

Character Literals

Karakter literals menggunakan single quote 'x' untuk meninisialisasi nilai. Dapat berupa karanter murni seperti 'a', 'b', 'z'. Berupa escape sequence '\t', '\n', '\r' atau universal karakter seperti '\u02C0'.

Seperti pada bahasa pemrograman umumnya escape sequence memiliki arti dalam C#:

Escape sequenceMeaning
\\\ character
\'' character
\"" character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\xhh . . .Hexadecimal number of one or more digits
Berikut adalah contoh untuk escape karakter:

using System;
namespace EscapeChar 
{
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Hello\tWorld\n\n");
         Console.ReadLine();
      }
   }
}

Setelah program dijalankan akan memberikan output:

Hello   World

String Literals

String literals ditandai dengan double quote "" atau @"". String literals terdiri dari urutan karakter bisa berupa plain, escape sequence atau universal character.

Kita dapat memecah string yang panjang menjadi beberapa baris dengan menggunakan whitespaces.

Berkut adalah contoh pendefinisian string literals:

"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
@"hello dear"

Mendefinisikan Konstanta

Konstanta didefinisikan dengan menggunakan keyword const, syntax untuk mendefinisikan konstanta adalah sebagai berikut:

const <data_type> <constant_name> = value;

Berikut adalah contoh program untuk mensimulasikan konstanta:

using System;
namespace DeclaringConstants
{
    class Program
    {
        static void Main(string[] args)
        {
            const double pi = 3.14159;   
            
            // constant declaration 
            double r;
            Console.WriteLine("Enter Radius: ");
            r = Convert.ToDouble(Console.ReadLine());
            double areaCircle = pi * r * r;
            Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
            Console.ReadLine();
        }
    }
}

Ketika program dijalankan akan memberikan hasil sebagai berikut:

Enter Radius: 
3
Radius: 3, Area: 28.27431

3. Operator

Operator adalah simbol untuk memberitahukan kedapada compiler untuk menjalankan operasi metematika atau manipulasi logika. Semua bahasa pemrograman sudah pasti punya built-in operator, berikut adalah built-in operator pada C#:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators
Arithmetic Operators

Berikut adalah arithmetic operator yang ada dalam C#, sebagai contoh variabel A berisi nilai 10 dan variabel B berisi nilai 20.

OperatorDescriptionExample
+Adds two operandsA + B = 30
-Subtracts second operand from the firstA - B = -10
*Multiplies both operandsA * B = 200
/Divides numerator by de-numeratorB / A = 2
%Modulus Operator and remainder of after an integer divisionB % A = 0
++Increment operator increases integer value by oneA++ = 11
--Decrement operator decreases integer value by oneA-- = 9
Berikut adalah contoh program untuk mensimulasikan arithmetic operators:

using System;
namespace OperatorsAppl 
{
   class Program 
   { 
      static void Main(string[] args) 
      { 
         int a = 21;
         int b = 10;
         int c;

         c = a + b;
         Console.WriteLine("Line 1 - Value of c is {0}", c);
         c = a - b;
         Console.WriteLine("Line 2 - Value of c is {0}", c);
         c = a * b;
         Console.WriteLine("Line 3 - Value of c is {0}", c);
         c = a / b;
         Console.WriteLine("Line 4 - Value of c is {0}", c);
         c = a % b;
         Console.WriteLine("Line 5 - Value of c is {0}", c);
         c = a++;
         Console.WriteLine("Line 6 - Value of c is {0}", c);
         c = a--;
         Console.WriteLine("Line 7 - Value of c is {0}", c);
         Console.ReadLine();
      }
   }
}

Hasil keluaran program ketika dijalankan:

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 22
Line 7 - Value of c is 20

Relational Operators

Tabel berikut memnunjukkan relational operators yang disuport oleh C#, kita asumsikan kalau variabel A bernilai 10 dan variable B bernilai 20.

OperatorDescriptionExample
==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.
Berikut adalah contoh program untuk mensimulasikan relational operators:

using System;
class Program
{
   static void Main(string[] args)
   {
      int a = 21;
      int b = 10;
      
      if (a == b)
      {
         Console.WriteLine("Line 1 - a is equal to b");
      }
      else 
      {
         Console.WriteLine("Line 1 - a is not equal to b");
      }
      
      if (a < b)
      {
         Console.WriteLine("Line 2 - a is less than b");
      }
      else
      {
         Console.WriteLine("Line 2 - a is not less than b");
      }
      
      if (a > b)
      {
         Console.WriteLine("Line 3 - a is greater than b");
      }
      else
      {
         Console.WriteLine("Line 3 - a is not greater than b");
      }
      /* Lets change value of a and b */
      a = 5;
      b = 20;
      
      if (a <= b) 
      { 
         Console.WriteLine("Line 4 - a is either less than or equal to  b");
      }
      
      if (b >= a)
      {
         Console.WriteLine("Line 5-b is either greater than or equal to b");
      }
   }
}

Ketika program dijalankan akan memberikan hasil sebagai berikut:

Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

Logical Operators

Digunakan untuk melakukan operasi logik, kita asumsikan A berniai boolean true sedangkan B bernilai boolean false. Untuk tabel pembuktian adalah sebagai berikut:

OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non zero then condition becomes true.(A && B) is false.
||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.
Berikut adalah contoh program untuk logical operators:

using System;
namespace OperatorsAppl 
{
   class Program 
   {
      static void Main(string[] args) 
      {
         bool a = true; 
         bool b = true;
         
         if (a && b)
         {
            Console.WriteLine("Line 1 - Condition is true");
         }
         
         if (a || b)
         {
            Console.WriteLine("Line 2 - Condition is true");
         }
         /* lets change the value of  a and b */
         a = false;
         b = true;
         
         if (a && b)
         {
            Console.WriteLine("Line 3 - Condition is true");
         }
         else
         {
            Console.WriteLine("Line 3 - Condition is not true");
         }
         
         if (!(a && b))
         {
            Console.WriteLine("Line 4 - Condition is true");
         }
         Console.ReadLine();
      }
   }
}

Keluaran program adalah sebagai berikut:

Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Bitwise Operators

Operasi bitwise adalah operasi logical tetapi dilakukan pada level bit per bit. Tabel kebenaran untuk operasi & (AND), | (OR)  dan ^ (XOR).

pqp & qp | qp ^ q
00000
01011
11110
10011
Kita asumsikan jika A = 60; dan B = 13; kemidian kita operasikan dalam level binary format seperti contoh berikut:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

Tabel dibawah ini akan menunjukkan tabel untuk operasi bitwise, dengan asumsi A = 60 dan B = 13.

OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) = 12, which is 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) = 61, which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) = 49, which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) = 61, which is 1100 0011 in 2's complement due to a signed binary number.
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 = 240, which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 = 15, which is 0000 1111
Berikut adalah contoh untuk mensimulasikan bitwise operator:

using System;
namespace OperatorsAppl
{
   class Program
   {
      static void Main(string[] args)
      {
         int a = 60;            /* 60 = 0011 1100 */ 
         int b = 13;            /* 13 = 0000 1101 */
         int c = 0; 
         
         c = a & b;             /* 12 = 0000 1100 */ 
         Console.WriteLine("Line 1 - Value of c is {0}", c );
         
         c = a | b;             /* 61 = 0011 1101 */
         Console.WriteLine("Line 2 - Value of c is {0}", c);
         
         c = a ^ b;             /* 49 = 0011 0001 */
         Console.WriteLine("Line 3 - Value of c is {0}", c);
         
         c = ~a;                /*-61 = 1100 0011 */
         Console.WriteLine("Line 4 - Value of c is {0}", c);
         
         c = a << 2;      /* 240 = 1111 0000 */
         Console.WriteLine("Line 5 - Value of c is {0}", c);
         
         c = a >> 2;      /* 15 = 0000 1111 */
         Console.WriteLine("Line 6 - Value of c is {0}", c);
         Console.ReadLine();
      }
   }
}

Keluaran program ketika dijalankan:

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Assignment Operators

Tabel berikut menunjukkan assignment operator pada C#:

OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B assigns value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2
Berikut adalah contoh program untuk mensimulasikan assignment operator:

using System;
namespace OperatorsAppl 
{
   class Program
   {
      static void Main(string[] args)
      {
         int a = 21;
         int c;
         c = a;
         Console.WriteLine("Line 1 - =  Value of c = {0}", c);
         
         c += a;
         Console.WriteLine("Line 2 - += Value of c = {0}", c);
         
         c -= a;
         Console.WriteLine("Line 3 - -=  Value of c = {0}", c);
         
         c *= a;
         Console.WriteLine("Line 4 - *=  Value of c = {0}", c);
         
         c /= a;
         Console.WriteLine("Line 5 - /=  Value of c = {0}", c);
         
         c = 200;
         c %= a;
         Console.WriteLine("Line 6 - %=  Value of c = {0}", c);
         
         c <<= 2;
         Console.WriteLine("Line 7 - <<=  Value of c = {0}", c);
         
         c >>= 2;
         Console.WriteLine("Line 8 - >>=  Value of c = {0}", c);
         
         c &= 2;
         Console.WriteLine("Line 9 - &=  Value of c = {0}", c);
         
         c ^= 2;
         Console.WriteLine("Line 10 - ^=  Value of c = {0}", c);
         
         c |= 2;
         Console.WriteLine("Line 11 - |=  Value of c = {0}", c);
         Console.ReadLine();
      }
   }
}

Keluaran program setelah dijalankan:

Line 1 - = Value of c = 21
Line 2 - += Value of c = 42
Line 3 - -= Value of c = 21
Line 4 - *= Value of c = 441
Line 5 - /= Value of c = 21
Line 6 - %= Value of c = 11
Line 7 - <<= Value of c = 44
Line 8 - >>= Value of c = 11
Line 9 - &= Value of c = 2
Line 10 - ^= Value of c = 0
Line 11 - |= Value of c = 2

Operator Lain yang penting dalam C#:

OperatorDescriptionExample
sizeof()Returns the size of a data type.sizeof(int), returns 4.
typeof()Returns the type of a class.typeof(StreamReader);
&Returns the address of an variable.&a; returns actual address of the variable.
*Pointer to a variable.*a; creates pointer named 'a' to a variable.
? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y
isDetermines whether an object is of a certain type.If( Ford is Car) // checks if Ford is an object of the Car class.
asCast without raising an exception if the cast fails.Object obj = new StringReader("Hello");
StringReader r = obj as StringReader;

Berikut adalah contoh program untuk mensimulasikan operator diatas:

using System;
namespace OperatorsAppl 
{
   class Program
   {
      static void Main(string[] args)
      {
         /* example of sizeof operator */
         Console.WriteLine("The size of int is {0}", sizeof(int));
         Console.WriteLine("The size of short is {0}", sizeof(short));
         Console.WriteLine("The size of double is {0}", sizeof(double));
         
         /* example of ternary operator */
         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);
         Console.ReadLine();
      }
   }
}

Berikut adalah keluaran program diatas jika dijalankan:

The size of int is 4
The size of short is 2
The size of double is 8
Value of b is 30
Value of b is 20

Urutan Prioritas Operasi Operator

Dalam pengoperasian operators mempunya urutan dan prioritas seperti halnya ketika kita belajar matematika di sekolah dasar. Misalnya ada ekpresi a = 2 + 4 * 2 - 5, maka operasi yang akan dilakukan terlebih dahulu adalah perkalian, kemudian penambahan baru kemudian pengurangan. Jika kita buat sebuah prioritas maka ekspresi tersebut akan menjadi a = ((2 + (4 * 2)) - 5).

Berikut adalah tabel untuk urutan prioritas operasi operator:

CategoryOperatorAssociativity
Postfix() [] -> . ++ - -Left to right
Unary+ - ! ~ ++ - - (type)* & sizeofRight to left
Multiplicative* / %Left to right
Additive+ -Left to right
Shift<< >>Left to right
Relational< <= > >=Left to right
Equality== !=Left to right
Bitwise AND&Left to right
Bitwise XOR^Left to right
Bitwise OR|Left to right
Logical AND&&Left to right
Logical OR||Left to right
Conditional?:Right to left
Assignment= += -= *= /= %=>>= <<= &= ^= |=Right to left
Comma,Left to right
Berikut adalah contoh program untuk mensimulasikan urutan prioritas operator:

using System;
namespace OperatorsAppl
{
   class Program
   {
      static void Main(string[] args)
      {
         int a = 20;
         int b = 10;
         int c = 15;
         int d = 5;
         int e;
         e = (a + b) * c / d;     // ( 30 * 15 ) / 5
         Console.WriteLine("Value of (a + b) * c / d is : {0}", e);

         e = ((a + b) * c) / d;   // (30 * 15 ) / 5
         Console.WriteLine("Value of ((a + b) * c) / d is  : {0}", e);

         e = (a + b) * (c / d);   // (30) * (15/5)
         Console.WriteLine("Value of (a + b) * (c / d) is  : {0}", e);

         e = a + (b * c) / d;    //  20 + (150/5)
         Console.WriteLine("Value of a + (b * c) / d is  : {0}", e);
         Console.ReadLine();
      }
   }
}

Berikut adalah keluaran program setelah dijalankan:

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is  : 90
Value of (a + b) * (c / d) is  : 90
Value of a + (b * c) / d is  : 50

Ok guys sampai ketemu di tutorial selanjutnya Pengambilan Keputusan.

5. Konversi Tipe Data C# (Basic/Dasar)

Konversi tipe data adalah mengkonversi dari satu tipe data ke tipe data yang lain. Dalam bahasa pemrograman hal ini biasa disebut dengan type casting (Casting). Type Casting terbagi menjadi dua macam yaitu:
  • Konversi Tipe secara Implisit - Konversi dengan cara ini akan dilakukan oleh C#. Sebagai contoh, menkonversi dari nilai tipe integral kecil ke nilai tipe integral yang lebih besar dan mengkonversi dari kelas turunan ke kelas dasar.
  • Konversi Tipe secara Explisit - Konversi dengan cara ini dilakukan oleh progammer menggunakan operator casting.

Berikut adalah contoh konversi secara eksplisit:

using System;
namespace TypeConversionApplication 
{
   class ExplicitConversion 
   {
      static void Main(string[] args) 
      {
         double d = 5673.74; 
         int i;
         
         // cast dari nilai double ke int.
         i = (int)d;
         Console.WriteLine(i);
         Console.ReadKey();
      }
   }
}

Keluaran dari program tersebut adalah sebagai berikut:

5673

C# juga menyediakan fungsi untuk mengkonversi tipe data sebagai berikut:

Sr.NoMethods & Description
1ToBoolean
Converts a type to a Boolean value, where possible.
2ToByte
Converts a type to a byte.
3ToChar
Converts a type to a single Unicode character, where possible.
4ToDateTime
Converts a type (integer or string type) to date-time structures.
5ToDecimal
Converts a floating point or integer type to a decimal type.
6ToDouble
Converts a type to a double type.
7ToInt16
Converts a type to a 16-bit integer.
8ToInt32
Converts a type to a 32-bit integer.
9ToInt64
Converts a type to a 64-bit integer.
10ToSbyte
Converts a type to a signed byte type.
11ToSingle
Converts a type to a small floating point number.
12ToString
Converts a type to a string.
13ToType
Converts a type to a specified type.
14ToUInt16
Converts a type to an unsigned int type.
15ToUInt32
Converts a type to an unsigned long type.
16ToUInt64
Converts a type to an unsigned big integer.
Berikut adalah contoh mengkonversi beberapa tipe data ke tipe string:

using System;
namespace TypeConversionApplication 
{
   class StringConversion
   {
      static void Main(string[] args)
      {
         int i = 75;
         float f = 53.005f;
         double d = 2345.7652;
         bool b = true;

         Console.WriteLine(i.ToString());
         Console.WriteLine(f.ToString());
         Console.WriteLine(d.ToString());
         Console.WriteLine(b.ToString());
         Console.ReadKey();
            
      }
   }
}

Ketika program diatas di compile dan dijalankan akan menghasilkan keluaran sebagai berikut:

75
53.005
2345.7652
True

Ok guys kita lanjut ke tutorial selanjutnya Variabel, Konstanta dan Operator.

Sunday 28 August 2016

4. Tipe Data C# (Basic/Dasar)

Pada tutorial sebelumnya Dasar Sintax saya sudah menyinggung apa itu variabel,  dalam C# variabel dapat di bagi menjadi tiga tipe yaitu:

  • Tipe Value
  • Tipe Reference
  • Tipe Pointer (Tidak semua bahasa modern ada tipe ini, kebanyakan bahasa pemrograman baru tidak menyertakan ini untuk mempermudah manajemen memori)
1. Tipe Value

Variabel dengan tipe value dapat di isi dengan nilai secara langsung,  Tipe data ini didefinisikan dalam class library System.ValueType.

Tipe value atau nilai akan secara langsung berisi sebuah data. Sebagai contoh int, char and float. Yang akan menyimpan angka, angka dan angka floating point. Ketika kita mendefinisikan tipe int secara otomatis sistem akan memsan sejumlah ruang memory untuk menyimpan nilai.

Berikut ini adalah daftar tipe value dalam C#.

TypeRepresentsRangeDefault Value
boolBoolean valueTrue or FalseFalse
byte8-bit unsigned integer0 to 2550
char16-bit Unicode characterU +0000 to U +ffff'\0'
decimal128-bit precise decimal values with 28-29 significant digits(-7.9 x 1028 to 7.9 x 1028) / 100 to 280.0M
double64-bit double-precision floating point type(+/-)5.0 x 10-324 to (+/-)1.7 x 103080.0D
float32-bit single-precision floating point type-3.4 x 1038 to + 3.4 x 10380.0F
int32-bit signed integer type-2,147,483,648 to 2,147,483,6470
long64-bit signed integer type-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8070L
sbyte8-bit signed integer type-128 to 1270
short16-bit signed integer type-32,768 to 32,7670
uint32-bit unsigned integer type0 to 4,294,967,2950
ulong64-bit unsigned integer type0 to 18,446,744,073,709,551,6150
ushort16-bit unsigned integer type0 to 65,5350
Untuk mendapatkan jumlah memory yang digunakan oleh tipe value kita dapat menggunakan method sizeof. Dengan memanggil method sizeof(Type) kita akan mendapatkan alokasi memori yang digunakan dalam bytes. Berikut adalah contoh code untuk menampilkan ukuran tipe int.


using System;
namespace DataTypeApplication
{
   class Program 
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Size of int: {0}", sizeof(int));
         Console.ReadLine();
      }
   }
}

Maka program akan memberikan output berupa ukuran dari tipe int. Keluaran program akan menghasilkan:

Size of int: 4

2. Tipe Reference

Tipe reference tidak menyimpan data asli tetapi menyimpan referensi ke variable yang lain. Dengan kata lain tipe reference akan menyimpan alamat memori dari variabel yang lain. Jika ada beberapa variabel menyimpan alamat memory yang sama, kemudian ada perubahan pada salah satu variabel maka varibel yang lain akan otomatis berubah juga. Contoh dari reference built-in adalah object, dynamic dan string.

2.1 Tipe Object

Tipe Object adalah bagian paling utama dalam bahasa pemrograman modern berbasis object (OOP). Dalam C# object didefinisikan dalam class libary System.Object. Tipe object dapat menyimpan tipe nilai yang lain, tipe value, tipe reference, tipe built-in atau tipe buatan user.

Ketika sebuah tipe dikonversikan ke object hal ini disebut sebagi boxing, sebaliknya mengkonversi dari tipe object ke tipe tertentu di sebut unboxing.

object obj;
obj = 100; // ini adalah boxing

2.2 Tipe Dynamic

Kita bisa menyimpan data kedalam tipe dynamic, pengecekan tipe data pada tipe dynamic akan dilakukan saat program dijalankan (run time).

Syntax untuk mendeklarasikan  tipe dynamic:

dynamic  = value;

Contoh:

dynamic d = 20;

Tipe dynamic pada dasarnya sama dengan tipe Object, yang membedakan adalah waktu konversi data. Tipe object akan dikonversi pada saat compile program sedangkan tipe dynamic akan dilakukan saat program berjalan (run time).

2.3 Tipe String

Tipe string akan menyimpan semua data yang bertipe string. Pada C# tipe string akan ditangani oleh System.String. Untuk mendeklarasikan string kita bisa menggunakan quoted atau @quoted

Sebagai contoh:

String str = "Seniman Koding";

atau:

String str = @"Seniman Koding";

Sedangkan untuk tipe user-defined adalah class, interface atau delegate, yang akan kita bahas pada bab selanjutnya.

3. Tipe Pointer

Tipe data pointer adalah tipe yang akan menyimpan alamat memori dari tipe data yang lain. Pinter pada C# sama halnya pointer pada C/C++.

Syntax untuk mendeklarasikan pointer adalah sebagai berikut:

type* identifier;

Contoh:

char* cptr;
int* iptr;

Kita akan mendiskusikan pointer pada bab selanjutnya "Unsafe Code". Mari guys kita lanjutkan ke tutorial selanjutnya Konversi Tipe Data.