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.

No comments:

Post a Comment