Wednesday, July 25, 2012

pengenalan algoritma dasar (tugas)



Variable (computer science)
in computer programming, a variable is a storage location and an associated symbolic name which 


contains some known or unknown quantity or information, a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents.[dubious  discuss] A variable name in computer source code is an identifier that can be bound to a value during run time, and the value may change during the course of program execution.
Variables in programming may not directly correspond to the concept of variables in mathematics. The value of a computing variable is not necessarily part of an equation or formula as in mathematics. In computing, a variable may be employed in a repetitive process: assigned a value in one place, then used elsewhere, then reassigned a new value and used again in the same way (see iteration). Variables in computer programming are frequently given long names to make them relatively descriptive of their use, whereas variables in mathematics often have terse, one- or two-character names for brevity in transcription and manipulation.
Compilers have to replace variables' symbolic names with the actual locations of the data. While a variable's name, type, and location often remain fixed, the data stored in the location may be changed during program execution.

Actions on a variable

In imperative programming languages, values can generally be accessed or changed at any time. However, in pure functional and logic languages, variables are bound to expressions and keep a single value during their entire lifetime due to the requirements of referential transparency. In imperative languages, the same behavior is exhibited by constants, which are typically contrasted with normal variables.
Depending on the type system of a programming language, variables may only be able to store a specified datatype (e.g. integer or string). Alternatively, a datatype may be associated only with the current value, allowing a single variable to store anything supported by the programming language.

Identifiers referencing a variable

An identifier referencing a variable can be used to access the variable in order to read out the value, or alter the value, or edit the attributesof the variable, such as access permission, locks, semaphores, etc.
For instance, a variable might be referenced by the identifier "total_count" and the variable can contain the number 1956. If the same variable is referenced by the identifier "x" as well, and if using this identifier "x", the value of the variable is altered to 2009, then reading the value using the identifier "total_count" will yield a result of 2009 and not 1956.
If a variable is only referenced by a single identifier, that can simply be called the name of the variable. Otherwise, we can speak of one of the names of the variable. For instance, in the previous example, the "total_count" is a name of the variable in question, and "x" is another name of the same variable.

 

Scope and extent

The scope of a variable describes where in a program's text, the variable may be used, while the extent (or lifetime) describes when in a program's execution a variable has a (meaningful) value. The scope of a variable is actually a property of the name of the variable, and the extent is a property of the variable itself.
A variable name's scope affects its extent.
Scope is a lexical aspect of a variable. Most languages define a specific scope for each variable (as well as any other named entity), which may differ within a given program. The scope of a variable is the portion of the program code for which the variable's name has meaning and for which the variable is said to be "visible". Entrance into that scope typically begins a variable's lifetime and exit from that scope typically ends its lifetime. For instance, a variable with "lexical scope" is meaningful only within a certain block of statements or subroutine. Variables only accessible within a certain functions are termed "local variables". A "global variable", or one with indefinite scope, may be referred to anywhere in the program.
Extent, on the other hand, is a runtime (dynamic) aspect of a variable. Each binding of a variable to a value can have its own extent at runtime. The extent of the binding is the portion of the program's execution time during which the variable continues to refer to the same value or memory location. A running program may enter and leave a given extent many times, as in the case of a closure.
Unless the programming language features garbage collection, a variable whose extent permanently outlasts its scope can result in amemory leak, whereby the memory allocated for the variable can never be freed since the variable which would be used to reference it for deallocation purposes is no longer accessible. However, it can be permissible for a variable binding to extend beyond its scope, as occurs in Lisp closures and C static local variables; when execution passes back into the variable's scope, the variable may once again be used. A variable whose scope begins before its extent does is said to be uninitialized and often has an undefined, arbitrary value if accessed (seewild pointer), since it has yet to be explicitly given a particular value. A variable whose extent ends before its scope does may become adangling pointer and deemed uninitialized once more since its value has been destroyed. Variables described by the previous two cases may be said to be out of extent or unbound. In many languages, it is an error to try to use the value of a variable when it is out of extent. In other languages, doing so may yield unpredictable results. Such a variable may, however, be assigned a new value, which gives it a new extent.
For space efficiency, a memory space needed for a variable may be allocated only when the variable is first used and freed when it is no longer needed. A variable is only needed when it is in scope, but beginning each variable's lifetime when it enters scope may give space to unused variables. To avoid wasting such space, compilers often warn programmers if a variable is declared but not used.
It is considered good programming practice to make the scope of variables as narrow as feasible so that different parts of a program do not accidentally interact with each other by modifying each other's variables. Doing so also prevents action at a distance. Common techniques for doing so are to have different sections of a program use different namespaces, or to make individual variables "private" through eitherdynamic variable scoping or lexical variable scoping.
Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.

Typing

Main article: Type system
See also: Datatype
In statically typed languages such as Java or ML, a variable also has a type, meaning that only certain kinds of values can be stored in it. For example, a variable of type "integer" is prohibited from storing text values.
In dynamically typed languages such as Python, it is values, not variables, which carry type. In Common Lisp, both situations exist simultaneously: a variable is given a type (if undeclared, it is assumed to be T, the universal supertype) which exists at compile time. Values also have types, which can be checked and queried at runtime.
Typing of variables also allows polymorphisms to be resolved at compile time. However, this is different from the polymorphism used in object-oriented function calls (referred to as virtual functions in C++) which resolves the call based on the value type as opposed to the supertypes the variable is allowed to have.
Variables often store simple data, like integers and literal strings, but some programming languages allow a variable to store values of other datatypes as well. Such languages may also enable functions to be parametric polymorphic. These functions operate like variables to represent data of multiple types. For example, a function named length may determine the length of a list. Such a length function may be parametric polymorphic by including a type variable in its type signature, since the amount of elements in the list is independent of the elements' types.

Parameters

The formal parameters of functions are also referred to as variables. For instance, in this Python code segment,
 def addtwo(x):
    return x + 2
 
 addtwo(5)  # yields 7
The variable named x is a parameter because it is given a value when the function is called. The integer 5 is the argument which gives x its value. In most languages, function parameters have local scope. This specific variable named x can only be referred to within the addtwofunction (though of course other functions can also have variables called x).

Memory allocation

The specifics of variable allocation and the representation of their values vary widely, both among programming languages and among implementations of a given language. Many language implementations allocate space for local variables, whose extent lasts for a single function call on the call stack, and whose memory is automatically reclaimed when the function returns. More generally, in name binding, the name of a variable is bound to the address of some particular block (contiguous sequence) of bytes in memory, and operations on the variable manipulate that block. Referencing is more common for variables whose values have large or unknown sizes when the code is compiled. Such variables reference the location of the value instead of storing the value itself, which is allocated from a pool of memory called the heap.
Bound variables have values. A value, however, is an abstraction, an idea; in implementation, a value is represented by some data object, which is stored somewhere in computer memory. The program, or the runtime environment, must set aside memory for each data object and, since memory is finite, ensure that this memory is yielded for reuse when the object is no longer needed to represent some variable's value.
Objects allocated from the heap must be reclaimed—especially when the objects are no longer needed. In a garbage-collected language (such as C#, Java, and Lisp), the runtime environment automatically reclaims objects when extant variables can no longer refer to them. In non-garbage-collected languages, such as C, the program (and the programmer) must explicitly allocate memory, and then later free it, to reclaim its memory. Failure to do so leads to memory leaks, in which the heap is depleted as the program runs, risking eventual failure from exhausting available memory.
When a variable refers to a data structure created dynamically, some of its components may be only indirectly accessed through the variable. In such circumstances, garbage collectors (or analogous program features in languages that lack garbage collectors) must deal with a case where only a portion of the memory reachable from the variable needs to be reclaimed.

Naming conventions

Unlike their mathematical counterparts, programming variables and constants commonly take multiple-character names, e.g. COST ortotal. Single-character names are most commonly used only for auxiliary variables; for instance, i, j, k for array index variables.
Some naming conventions are enforced at the language level as part of the language syntax and involve the format of valid identifiers. In almost all languages, variable names cannot start with a digit (0-9) and cannot contain whitespace characters. Whether, which, and when punctuation marks are permitted in variable names varies from language to language; many languages only permit the underscore ("_") in variable names and forbid all other punctuation. In some programming languages, specific (often punctuation) characters (known as sigils) are prefixed or appended to variable identifiers to indicate the variable's type.
Case-sensitivity of variable names also varies between languages and some languages require the use of a certain case in naming certain entities;[note 1] Most modern languages are case-sensitive; some older languages are not. Some languages reserve certain forms of variable names for their own internal use; in many languages, names beginning with 2 underscores ("__") often fall under this category.
However, beyond the basic restrictions imposed by a language, the naming of variables is largely a matter of style. At the machine code level, variable names are not used, so the exact names chosen do not matter to the computer. Thus names of variables identify them, for the rest they are just a tool for programmers to make programs easier to write and understand. Using poorly chosen variable names can make code more difficult to review than non-descriptive names, so names which are clear are often encouraged.[1]
Programmers often create and adhere to code style guidelines which offer guidance on naming variables or impose a precise naming scheme. Shorter names are faster to type but are less descriptive; longer names often make programs easier to read and the purpose of variables easier to understand. However, extreme verbosity in variable names can also lead to less comprehensible code.

Data type

In certain technical fields (especially computer programming and statistics), a data type is a classification identifying one of various types of data, such as real-valued, integer or Boolean, that determines the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.[1][2] Most data types in statistics have comparable types in computer programming, and vice-versa, as shown in the following table:
Statistics
Computer programming
count data (usually non-negative)
list or array
two-dimensional array
The rest of this article addresses data types from a computer science perspective. For their use in statistics, see statistical data type.
Overview
Data types are used within type systems, which offer various ways of defining, implementing and using them. Different type systems ensure varying degrees of type safety. Formally, a type can be defined as "any property of a programme we can determine without executing the program".[3]
Almost all programming languages explicitly include the notion of data type, though different languages may use different terminology. Common data types may include:
§  integers,
§  booleans,
§  characters,
§  floating-point numbers,
§  alphanumeric strings.
For example, in the Java programming language, the "int" type represents the set of 32-bit integers ranging in value from -2,147,483,648 to 2,147,483,647, as well as the operations that can be performed on integers, such as addition, subtraction, and multiplication. Colors, on the other hand, are represented by three bytes denoting the amounts each of red, green, and blue, and one string representing that color's name; allowable operations include addition and subtraction, but not multiplication.
Most programming languages also allow the programmer to define additional data types, usually by combining multiple elements of other types and defining the valid operations of the new data type. For example, a programmer might create a new data type named "complex number" that would include real and imaginary parts. A data type also represents a constraint placed upon the interpretation of data in a type system, describing representation, interpretation and structure of values or objects stored in computer memory. The type system uses data type information to check correctness of computer programs that access or manipulate the data.
Classes of data types
Machine data types
All data in computers based on digital electronics is represented as bits (alternatives 0 and 1) on the lowest level. The smallest addressable unit of data is usually a group of bits called a byte (usually an octet, which is 8 bits). The unit processed by machine code instructions is called a word (as of 2011, typically 32 or 64 bits). Most instructions interpret the word as a binary number, such that a 32-bit word can represent unsigned integer values from 0 to 2^{32}-1 or signed integer values from -2^{31} to 2^{31}-1. Because of two's complement, the machine language and machine doesn't need to distinguish between these unsigned and signed data types for the most part.
There is a specific set of arithmetic instructions that use a different interpretation of the bits in word as a floating-point number.
Machine data types need to be exposed or made available in systems or low-level programming languages, allowing fine-grained control over hardware. The C programming language, for instance, supplies integer types of various widths, such as short and long. If a corresponding native type does not exist on the target platform, the compiler will break them down into code using types that do exist. For instance, if a 32-bit integer is requested on a 16 bit platform, the compiler will tacitly treat it as an array of two 16 bit integers.
Several languages allow binary and hexadecimal literals, for convenient manipulation of machine data.
In higher level programming, machine data types are often hidden or abstracted as an implementation detail that would render code less portable if exposed. For instance, a generic numeric type might be supplied instead of integers of some specific bit-width.
The boolean type
The Boolean type represents the values: true and false. Although only two values are possible, they are rarely implemented as a single binary digit for efficiency reasons. Many programming languages do not have an explicit boolean type, instead interpreting (for instance) 0 as false and other values as true.
Numeric types
Such as:
§  The integer data types, or "whole numbers". May be subtyped according to their ability to contain negative values (e.g. unsigned in C and C++). May also have a small number of predefined subtypes (such as short and long in C/C++); or allow users to freely define subranges such as 1..12 (e.g. Pascal/Ada).
§  Floating point data types, sometimes misleadingly called reals, contain fractional values. They usually have predefined limits on both their maximum values and their precision.
§  Fixed point data types are convenient for representing monetary values. They are often implemented internally as integers, leading to predefined limits.
§  Bignum or arbitrary precision numeric types lack predefined limits. They are not primitive types, and are used sparingly for efficiency reasons.
String and text types
Such as
§  Alphanumeric character. A letter of the alphabet, digit, blank space, punctuation mark, etc.
§  Alphanumeric strings, a sequence of characters. They are typically used to represent words and text.
Character and string types can store sequences of characters from a character set such as ASCII. Since most character sets include the digits, it is possible to have a numeric string, such as "1234". However, many languages would still treat these as belonging to a different type to the numeric value 1234.
Character and string types can have different subtypes according to the required character "width". The original 7-bit wide ASCII was found to be limited, and superseded by 8 and 16-bit sets, which can encode a wide variety of non-Latin alphabets (Hebrew, Chinese) and other symbols. Strings may be either stretch-to-fit or of fixed size, even in the same programming language. They may also be subtyped by their maximum size.
Note: strings are not primitive in all languages, for instance C: they may be composed from arrays of characters.
Enumerations
The enumerated type. This has values which are different from each other, and which can be compared and assigned, but which do not necessarily have any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily. For example, the four suits in a deck of playing cards may be four enumerators named CLUB, DIAMOND, HEART, SPADE, belonging to an enumerated type named suit. If a variable V is declared having suit as its data type, one can assign any of those four values to it. Some implementations allow programmers to assign integer values to the enumeration values, or even treat them as type-equivalent to integers.
Derived types
Types can be based on, or derived from, the basic types explained above.
In some language, such as C, functions have a type derived from the type of their return value.
Pointers and references
The main non-composite, derived type is the pointer, a data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address. It is a primitive kind of reference. (In everyday terms, a page number in a book could be considered a piece of data that refers to another one). Pointers are often stored in a format similar to an integer; however, attempting to dereference or "look up" a pointer whose value was never a valid memory address would cause a program to crash. To ameliorate this potential problem, pointers are considered a separate type to the type of data they point to, even if the underlying representation is the same.
Composite types
Composite types are derived from more than one primitive type. This can be done in a number of ways. The ways they are combined are called data structures. Composing a primitive type into a compound type generally results in a new type, e.g. array-of-integer is a different type to integer.
§  An array stores a number of elements of the same type in a specific order. They are accessed using an integer to specify which element is required (although the elements may be of almost any type). Arrays may be fixed-length or expandable.
§  Record (also called tuple or struct) Records are among the simplest data structures. A record is a value that contains other values, typically in fixed number and sequence and typically indexed by names. The elements of records are usually called fields or members.
§  Union. A union type definition will specify which of a number of permitted primitive types may be stored in its instances, e.g. "float or long integer". Contrast with a record, which could be defined to contain a float and an integer; whereas, in a union, there is only one value at a time.
§  A tagged union (also called a variant, variant record, discriminated union, or disjoint union) contains an additional field indicating its current type, for enhanced type safety.
§  A set is an abstract data structure that can store certain values, without any particular order, and no repeated values. Values themselves are not retrieved from sets, rather one tests a value for membership to obtain a boolean "in" or "not in".
§  An object contains a number of data fields, like a record, and also a number of programme code fragments for accessing or modifying them. Data structures not containing code, like those above, are called plain old data structure.
Many others are possible, but they tend to be further variations and compounds of the above.
Abstract types
Any type that does not specify an implementation is an Abstract data type. For instance, a stack (which is an abstract type) can be implemented as an array (a contiguous block of memory containing multiple values), or as a linked list(a set of non-contiguous memory blocks linked by pointers).
Abstract types can be handled by code that does not know or "care" what underlying types are contained in them. Programming that is agnostic about concrete data types is called generic programming. Arrays and records can also contain underlying types, but are considered concrete because they specify how their contents or elements are laid out in memory.
Examples include:
§  A smart pointer is the abstract counterpart to a pointer. Both are kinds of reference
§  A hash or dictionary or map or Map/Associative array/Dictionary is a more flexible variation on a record, in which name-value pairs can be added and deleted freely.
§  A queue is a first-in first-out list. Variations are Deque and Priority queue.
§  A set can store certain values, without any particular order, and with no repeated values.
§  A stack is a last-in, first out.
§  A tree is a hierarchical structure.
§  A graph.
Utility types
For convenience, high-level languages may supply ready-made "real world" data types, for instance times, dates and monetary values, even where the language allows them to be built from primitive types.
Type systems
Main article: Type system
A type system associates types with each computed value. By examining the flow of these values, a type system attempts to prove that no type errors can occur. The type system in question determines what constitutes a type error, but a type system generally seeks to guarantee that operations expecting a certain kind of value are not used with values for which that operation does not make sense.
A compiler may use the static type of a value to optimize the storage it needs and the choice of algorithms for operations on the value. In many C compilers the float data type, for example, is represented in 32 bits, in accord with theIEEE specification for single-precision floating point numbers. They will thus use floating-point-specific microprocessor operations on those values (floating-point addition, multiplication, etc.).
The depth of type constraints and the manner of their evaluation affect the typing of the language. A programming language may further associate an operation with varying concrete algorithms on each type in the case of type polymorphism. Type theory is the study of type systems, although the concrete type systems of programming languages originate from practical issues of computer architecture, compiler implementation, and language design.
Type systems may be variously static or dynamic, strong or weak typing, and so forth.

Gerbang logika

Gerbang logika atau gerbang logik adalah suatu entitas dalam elektronika dan matematika Boolean yang mengubah satu atau beberapa masukan logik menjadi sebuah sinyal keluaran logik. Gerbang logika terutama diimplementasikan secara elektronis menggunakan diode atau transistor, akan tetapi dapat pula dibangun menggunakan susunan komponen-komponen yang memanfaatkan sifat-sifat elektromagnetik (relay), cairan, optik dan bahkan mekanik.

Ringkasan jenis-jenis gerbang logika

NamaFungsiLambang dalam rangkaianTabel kebenaran
IEC 60617-12US-NormDIN 40700 (sebelum 1976)
Gerbang-AND
(AND)
Y = A \wedge B


Y = A\cdot B


Y = A\,B
IEC AND label.svgLogic-gate-and-us.svgLogic-gate-and-de.png
ABY
000
010
100
111
Gerbang-OR
(OR)
Y = A \vee B


Y = A + B\!
IEC OR label.svgLogic-gate-or-us.pngLogic-gate-or-de.png
ABY
000
011
101
111
Gerbang-NOT
(NOT, Gerbang-komplemen, Pembalik(Inverter))
Y = \overline{A}


Y = \neg A
IEC NOT label.svgLogic-gate-inv-us.pngLogic-gate-inv-de.png\
AY
01
10
Gerbang-NAND
(Not-AND)
Y = \overline{A \wedge B}


Y = A \overline{\wedge} B


Y = \overline{A\,B}
IEC NAND label.svgLogic-gate-nand-us.pngLogic-gate-nand-de.png
ABY
001
011
101
110
Gerbang-NOR
(Not-OR)
Y = \overline{A \vee B}


Y = A \overline{\vee} B


Y = \overline{A + B}
IEC NOR label.svgLogic-gate-nor-us.pngLogic-gate-nor-de.png
ABY
001
010
100
110
Gerbang-XOR
(Antivalen, Exclusive-OR)
Y = A \,\underline{\lor}\, B


Y = A \oplus B
IEC XOR label.svgLogic-gate-xor-us.pngLogic-gate-xor-de.png
atau
Logic-gate-xor-de-2.png
ABY
000
011
101
110
Gerbang-XNOR
(Ekuivalen, Not-Exclusive-OR)
Y = \overline{A \,\underline{\lor}\, B}


Y = A \,\overline{\underline{\lor}}\, B


Y = \overline{A \oplus B}
IEC XNOR label.svgLogic-gate-xnor-us.pngLogic-gate-xnor-de.png
atau
Logic-gate-xnor-de-2.png
ABY
001
010
100
111
Operator logika
Dalam logika, dua kalimat dapat digabungkan dengan operator logika untuk membentuk kalimat gabungan. Nilai kebenaran kalimat gabungan ini ditentukan oleh nilai kebenaran kalimat-kalimat pembentuknya. Operator logika di sini bertindak sebagai fungsi.
Dalam bahasa sehari-hari, dua kalimat dapat digabungkan dengan konjungsi gramatik. Misalnya:
A: Hari ini cuaca mendung
B: Hari ini akan hujan
C: Hari ini cuaca mendung dan hari ini akan hujan
D: Hari ini cuaca mendung karena itu hari ini akan hujan
Kata dan dan karena itu adalah konjungsi gramatik yang menggabungkan kalimat (A) dan (B) untuk membentuk kalimat (C) dan (D).
Dalam bahasa logika, ada 16 operator logika:

No comments:

Post a Comment