Subscribe to Zinmag Tribune
Subscribe to Zinmag Tribune
Subscribe to Zinmag Tribune by mail
http://3.bp.blogspot.com/-V-tXIPtY54I/TakAGJvMVdI/AAAAAAAAApU/ylfI6u_wiT8/s1600/banner_amikom.gif
STMIK AMIKOM Towards a Research University
http://3.bp.blogspot.com/-JeQbICNKuDw/TajVRfH_5pI/AAAAAAAAAoc/UH3JfuWLKdw/s320/_jet_computer_3.jpg
Computer as a Communication Tool World
http://4.bp.blogspot.com/-uiRNTeYb4yo/TajViViTNqI/AAAAAAAAApM/NNRF2xYz7Ec/s320/social-media-people.jpg
Build a Future Assets
http://3.bp.blogspot.com/-DhJA4vl55VM/TakGBr3WLPI/AAAAAAAAApc/4xX1ktwGq-k/s1600/566_americas_next_top_model_468.jpg
Top Asian Model

Business

Run The Berfect Business
http://1.bp.blogspot.com/-V1kE1NVt4OE/TajVSIvoZ_I/AAAAAAAAAog/ndIhAnN1_Tg/s320/business.jpg

General Computer

Resurrection Of The Future With Advances In Technology
http://3.bp.blogspot.com/-2iRsMjjVGDA/TajVYs797qI/AAAAAAAAAow/1dTU39kWTqA/s200/computer_data_180_1441.jpg

Business

Run The Berfect Business
http://1.bp.blogspot.com/-0eCoyyQLq58/TajVgM_Cd_I/AAAAAAAAApE/x5Heuo13qBU/s1600/karte_nova_media_en.png

BusinessE

Run The Berfect Business
http://1.bp.blogspot.com/-CThUuBoGlh8/TajVUvfNjvI/AAAAAAAAAok/Q-t_-UYzqEE/s320/business-plan-picture.jpg

Free CD of Linux Ubuntu 10:10

2:53 AM Reporter: fendhy


I'll tell you my experience of trying to get free ubuntu cd from linux.Pertama of all I was interested in the Ubuntu OS 10.10.Saya want to experience something new in my life saya.Akhirnya browsing here and there to search for Linux iso files ubuntu.Tapi, I was surprised to learn that the file has a size that besar.Saya iso.nya think to cancel my intention to use the OS that one ini.Tapi I finally found a blog article from a neighbor, whose title "Ubuntu Free CD of Linux. " sudden I became optimistic again,
know of any program for free Ubuntu CD from Linux.Saya even went to the url = http://www.ubuntu.com/desktop/get-ubuntu/download there I select the desktop edition, then do the registration, after successfully registering, which should we do next is to confirm our email address , go to yahoo or gmail email in accordance with what we wear, there will be a message from the contents linux confirmation code, copy it and paste the code in the form "enter the confirmation code", after all we are doing it in later in order to fill the form information about the data themselves kita.Isikan all formnya with benar.Agar delivery to destination which can then click "Send Request" later on there will be notification "Request is accepted .. ". Please allow 4 to 6 weeks ahead, order your cd will arrive in the hands anda.Saya ubuntu cd is also still waiting for my order, I'll be posting articles about the ubuntu after CD dapatkan.Oh .. yes I almost forgot, delivery costs borne by recipient other blog2 word does it cost only 0.7 dollars.
# Indonesia Go Open Source

Read more...

Array 1

2:40 AM Reporter: fendhy
Arrays as parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation.

In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For example, the following function:



void procedure (int arg[ ])



accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:



int myarray [40];



it would be enough to write a call like this:



procedure (myarray);



Here you have a complete example:

// arrays as parameters
#include
using namespace std;

void printarray (int arg[ ], int length) {
for (int n=0; n<length; n++)
    cout << arg[n] << " ";
  cout << "\n";
}


int main ()
{
int firstarray[ ] = {5, 10, 15};
int secondarray[ ] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}


Run:
5    10     15
2     4       6     8     10



As you can see, the first parameter (int arg[ ]) accepts any array whose elements are of type int, whatever its length. For that reason we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the passed array without going out of range.

In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:



base_type[][depth][depth]



for example, a function with a multidimensional array as argument could be:


void procedure (int myarray[][3][4])



Notice that the first brackets [ ] are left blank while the following ones are not. This is so because the compiler must be able to determine within the function which is the depth of each additional dimension.

Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors for novice programmers. I recommend the reading of the chapter about Pointers for a better understanding on how arrays operate.


Multidimensional arrays


Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type.


jimmy represents a bidimensional array of 3 per 5 elements of type int. The way to declare this array in C++ would be:

int jimmy [3][5];


and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be:

jimmy[1][3]



(remember that array indices always begin by zero).

Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. But be careful! The amount of memory needed for an array rapidly increases with each dimension. For example:

char century [100][365][24][60][60];


declares an array with a char element for each second in a century, that is more than 3 billion chars. So this declaration would consume more than 3 gigabytes of memory!

Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a simple array just by putting a factor between its indices:

1
2
int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 


With the only difference that with multidimensional arrays the compiler remembers the depth of each imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result. One uses a bidimensional array and the other one uses a simple array:

Multidimensional Array
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];int n,m;
int main ()
{
  for (n=0;n<HEIGHT;n++)
    for (m=0;m<WIDTH;m++)
    {
      jimmy[n][m]=(n+1)*(m+1);
    }
  return 0;
}

Pseudo-Multidimensional Array
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT * WIDTH];int n,m;int main ()
{
  for (n=0;n<HEIGHT;n++)
    for (m=0;m<WIDTH;m++)
    {
      jimmy[n*WIDTH+m]=(n+1)*(m+1);
    }
  return 0;
}
None of the two source codes above produce any output on the screen, but both assign values to the memory block called jimmy in the following way:


We have used "defined constants" (#define) to simplify possible future modifications of the program. For example, in case that we decided to enlarge the array to a height of 4 instead of 3 it could be done simply by changing the line:

#define HEIGHT 3 

to:
#define HEIGHT 4 


with no need to make any other modifications to the program.


Source Of Cplusplus

Read more...

SMS Free

7:09 PM Reporter: fendhy

Make Widget

Read more...

Functions

9:08 AM Reporter: fendhy
Ex 1 : 
 
// function example
#include <iostream>
using namespace std;

int addition (int a, int b)
{
  int r;
  r=a+b;
  return (r);
}

int main ()
{
  int z;
  z = addition (5,3);
  cout << "The result is " << z;
  return 0;
}
 
Run :  8
 
 
Info
  


In order to examine this code, first of all remember something said at 
the beginning of this tutorial: a C++ program always begins its 
execution by the main function. So we will begin there.



We can see how the main function begins by declaring the variable z of type int. 
Right after that, we see a call to a function called addition.
 Paying attention we will be able to see the similarity between the 
structure of the call to the function and the declaration of the 
function itself some code lines above: 


 



The parameters and arguments have a clear correspondence. 
Within the main function we called to addition passing two values: 5 and 3, 
that correspond to the int a and int b parameters declared for function addition.
At the point at which the function is called from within main,
 the control is lost by main and passed to function addition. 
The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and 
int b within the function.
Function addition declares another local variable (int r), 
and by means of the expression r=a+b, it assigns to r the result of a plus b. 
Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.
The following line of code:

return (r);

statement in function finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows its regular course from the same point at which it was interrupted by the call to addition. But additionally, because the returnaddition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call.




So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8).

The following line of code in main is:


cout << "The result is " << z;

Ex 2:
 // function example
#include <iostream>
using namespace std;

int subtraction (int a, int b)
{
  int r;
  r=a-b;
  return (r);
}

int main ()
{
  int x=5, y=3, z;
  z = subtraction (7,2);
  cout << "The first result is " << z << '\n';
  cout << "The second result is " << subtraction (7,2) << '\n';
  cout << "The third result is " << subtraction (x,y) << '\n';
  z= 4 + subtraction (x,y);
  cout << "The fourth result is " << z << '\n';
  return 0;
}
 
Run : 
 
The first result is  : 5
The second result is : 5
The third result is  : 2
The fourth result is : 6
 
In this case we have created a function called subtraction. 
The only thing that this function does is to subtract both passed parameters and to return the result.
Nevertheless, if we examine function main we will see that we have made several calls to function subtraction. 
We have used some different calling methods so that you see other ways or moments when a function can be called. 
In order to fully understand these examples you must consider once again
 that a call to a function could be replaced by the value that the 
function call itself is going to return. For example, the first case 
(that you should already know because it is the same pattern that we 
have used in previous examples):


z = subtraction (7,2);
cout << "The first result is " << z;


If we replace the function call by the value it returns (i.e., 5), we would have:


z = 5;
cout << "The first result is " << z;


As well as


cout << "The second result is " << subtraction (7,2);


has the same result as the previous call, but in this case we made the call to subtraction directly as an insertion parameter for cout. Simply consider that the result is the same as if we had written:


cout << "The second result is " << 5;


since 5 is the value returned by subtraction (7,2).

In the case of:

cout << "The third result is " << subtraction (x,y);


The only new thing that we introduced is that the parameters of subtraction are variables instead of constants. That is perfectly valid. In this case the values passed to function subtraction are the values of x and y, that are 5 and 3 respectively, giving 2 as result.


The fourth case is more of the same. Simply note that instead of:

z = 4 + subtraction (x,y);


we could have written:

z = subtraction (x,y) + 4;


with exactly the same result. I have switched places so you can see that the semicolon sign (;) goes at the end of the whole statement. It does not necessarily have to go right after the function call. The explanation might be once again that you imagine that a function can be replaced by its returned value:

z = 4 + 2;
z = 2 + 4;
 
Ex 3 :
 
// void function example
#include <iostream>
using namespace std;

void printmessage ()
{
  cout << "I'm a function!";
}

int main ()
{
  printmessage ();
  return 0;
} 
 
Run : I'm a function! 
 
 
 
 
void can also be used in the function's parameter list to 
explicitly specify that we want the function to take no actual 
parameters when it is called. For example, function printmessage could have been declared as:





void printmessage (void)
{
  cout << "I'm a function!";
}


Although it is optional to specify void in the parameter list. In C++, a parameter list can simply be left blank if we want a function with no parameters.

What you must always remember is that the format for calling a function includes specifying its name and enclosing its parameters between parentheses. The non-existence of parameters does not exempt us from the obligation to write the parentheses. For that reason the call to printmessage is:

printmessage ();


The parentheses clearly indicate that this is a call to a function and not the name of a variable or some other C++ statement. The following call would have been incorrect:
printmessage;
 
 
Source Of Cplusplus 

Read more...

Operator

8:22 AM Reporter: fendhy
Once we know of the existence of variables and constants, we can begin to operate with them. For that purpose, C++ integrates operators. Unlike other languages whose operators are mainly keywords, operators in C++ are mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++ code shorter and more international, since it relies less on English words, but requires a little of learning effort in the beginning.

You do not have to memorize all the content of this page. Most details are only provided to serve as a later reference in case you need it.

Assignment (=)

The assignment operator assigns a value to a variable.


a = 5;


This statement assigns the integer value 5 to the variable a. The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, the result of an operation or any combination of these.
The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from right to left, and never the other way:

a = b;


This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was stored until this moment in a is not considered at all in this operation, and in fact that value is lost.

Consider also that we are only assigning the value of b to a at the moment of the assignment operation. Therefore a later change of b will not affect the new value of a.

For example, let us have a look at the following code - I have included the evolution of the content stored in the variables as comments:



// assignment operator

#include <iostream>
using namespace std;

int main ()
{
  int a, b;         // a:?,  b:?
  a = 10;           // a:10, b:?
  b = 4;            // a:10, b:4
  a = b;            // a:4,  b:4
  b = 7;            // a:4,  b:7

  cout << "a:";
  cout << a;
  cout << " b:";
  cout << b;

  return 0;

Run:  
a:4 b:7


This code will give us as result that the value contained in a is 4 and the one contained in b is 7. Notice how a was not affected by the final modification of b, even though we declared a = b earlier (that is because of the right-to-left rule).

A property that C++ has over other programming languages is that the assignment operation can be used as the rvalue (or part of an rvalue) for another assignment operation. For example:


a = 2 + (b = 5);


is equivalent to:


b = 5;
a = 2 + b;


that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous assignment of b (i.e. 5), leaving a with a final value of 7.

The following expression is also valid in C++:

a = b = c = 5;
 
 

Arithmetic operators ( +, -, *, /, % )

+ ~> addition
- ~> subtraction
* ~> multiplication
/ ~> division
% ~> modulo



a = 11 % 3;


the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3.



Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

 

When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators:

expressionis equivalent to
value += increase;      value = value + increase;
a -= 5;a = a - 5;
a /= b;a = a / b;
price *= units + 1;price = price * (units + 1);

 and the same for all other operators. For example:












// compound assignment operators

#include <iostream>
using namespace std;

int main ()
{
  int a, b=3;
  a = b; 
  a+=2;             // equivalent to a=a+2
  cout << a;
  return 0;
}

Run :  5



Increase and decrease (++, - -)

Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:




c++;
c+=1;
c=c+1;


are all equivalent in its functionality: the three of them increase by one the value of c.

In the early C compilers, the three previous expressions probably produced different executable code depending on which one was used. Nowadays, this type of code optimization is generally done automatically by the compiler, thus the three expressions should produce exactly the same executable code.

A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.

Relational and equality operators ( ==, !=, >, <, >=, <= )


In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result.

We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++:

==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Here there are some examples:





(7 == 5)     // evaluates to false.
(5 > 4)      // evaluates to true.
(3 != 2)     // evaluates to true.
(6 >= 6)     // evaluates to true.
(5 < 5)      // evaluates to false. 


Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6,




(a == 5)     // evaluates to false since a is not equal to 5.
(a*b >= c)   // evaluates to true since (2*3 >= 6) is true. 
(b+4 > a*c)  // evaluates to false since (3+4 > 2*6) is false. 
((b=2) == a) // evaluates to true.  


Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first one is an assignment operator (assigns the value at its right to the variable at its left) and the other one (==) is the equality operator that compares whether both expressions in the two sides of it are equal to each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.

Logical operators ( !, &&, || )

 The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:




!(5 == 5)    // evaluates to false because the expression at its right (5 == 5) is true. 
!(6 <= 4)    // evaluates to true because (6 <= 4) would be false. 
!true        // evaluates to false
!false       // evaluates to true.  


The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a && b:

&& OPERATOR
a   b        a && b
true true     true
truefalse     false
false     true     false
falsefalse     false

The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results of a || b:

      || OPERATOR
a    b      a || b
true    true      true
true    false      true
false    true      true
false    false      false

For example:


( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ). 


When using the logical operators, C++ only evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest. Therefore, in this last example ((5==5)||(3>6)), C++ would evaluate first whether 5==5 is true, and if so, it would never check whether 3>6 is true or not. This is known as short-circuit evaluation, and works like this for these operators:

operatorshort-circuit
&&if the left-hand side expression is false, the combined result is false (right-hand side expression not evaluated).
||if the left-hand side expression is true, the combined result is true (right-hand side expression not evaluated).

This is mostly important when the right-hand expression has side effects, such as altering values:

if ((i<10)&&(++i<n)) { /*...*/ }


This combined conditional expression increases i by one, but only if the condition on the left of && is true, since otherwise the right-hand expression (++i<n) is never evaluated.


Conditional operator ( ? )


The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is:

condition ? result1 : result2

If condition is true the expression will return result1, if it is not it will return result2.




7==5 ? 4 : 3     // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3   // returns 4, since 7 is equal to 5+2.
5>3 ? a : b      // returns the value of a, since 5 is greater than 3.
a>b ? a : b      // returns whichever is greater, a or b. 



// conditional operator

#include <iostream>
using namespace std;

int main ()
{
  int a,b,c;

  a=2;
  b=7;
  c = (a>b) ? a : b;

  cout << c;

  return 0;
}
 
Run : 7

In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7.


Comma operator ( , )

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

For example, the following code:

a = (b=3, b+2);


Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.

Bitwise Operators ( &, |, ^, ~, <<, >> )


Bitwise operators modify variables considering the bit patterns that represent the values they store.

operatorasm equivalendescription
&AND                Bitwise AND
|OR                Bitwise Inclusive OR
^XOR                Bitwise Exclusive OR
~NOT                Unary complement (bit inversion)
<<SHL                Shift Left
>>SHR                Shift Right

Explicit type casting operator

Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):



int i;
float f = 3.14;
i = (int) f;


The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses:

i = int ( f );


Both ways of type casting are valid in C++.

sizeof()

This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object:

a = sizeof (char);


This will assign the value 1 to a because char is a one-byte long type.
The value returned by sizeof is a constant, so it is always determined before program execution.

Other operators

Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the specifics for object-oriented programming. Each one is treated in its respective section.

Precedence of operators

When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression:

a = 5 + 7 % 2


we may doubt if it really means:


a = 5 + (7 % 2)    // with a result of 6, or
a = (5 + 7) % 2    // with a result of 0 


The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows:

LevelOperatorDescriptionGrouping
1::scopeLeft-to-right
2() [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeidpostfixLeft-to-right
3++ -- ~ ! sizeof new deleteunary (prefix)Right-to-left
* &indirection and reference (pointers)
+ -unary sign operator
4(type)type castingRight-to-left
5.* ->*pointer-to-memberLeft-to-right
6* / %multiplicativeLeft-to-right
7+ -additiveLeft-to-right
8<< >>shiftLeft-to-right
9< > <= >=relationalLeft-to-right
10== !=equalityLeft-to-right
11&bitwise ANDLeft-to-right
12^bitwise XORLeft-to-right
13|bitwise ORLeft-to-right
14&&logical ANDLeft-to-right
15||logical ORLeft-to-right
16?:conditionalRight-to-left
17= *= /= %= += -= >>= <<= &= ^= |=assignmentRight-to-left
18,commaLeft-to-right

Grouping defines the precedence order in which operators are evaluated in the case that there are several operators of the same level in an expression.

All these precedence levels for operators can be manipulated or become more legible by removing possible ambiguities using parentheses signs ( and ), as in this example:

a = 5 + 7 % 2;


might be written either as:

a = 5 + (7 % 2);

or
a = (5 + 7) % 2;


depending on the operation that we want to perform.

So if you want to write complicated expressions and you are not completely sure of the precedence levels, always include parentheses. It will also make your code easier to read.


Source Of Cplusplus

Read more...

Constants

8:42 AM Reporter: fendhy
Literal adalah jenis yang paling jelas dari konstanta. Mereka digunakan untuk menyatakan nilai-nilai tertentu dalam kode sumber program. Kita telah digunakan sebelumnya ini untuk memberikan nilai konkrit untuk variabel atau untuk mengekspresikan pesan kami ingin program kami untuk mencetak, misalnya, ketika kita menulis:







a = 5;


5 dalam potongan kode ini adalah konstanta literal.
Literal konstanta dapat dibagi dalam angka Integer, Floating-Point angka, Karakter, String dan Boolean Nilai.





Integer Numerals

1
2
3
1776
707
-273


 
Mereka adalah konstanta numerik yang mengidentifikasi nilai desimal integer. Perhatikan bahwa untuk mengekspresikan numerik konstan kita tidak harus menulis tanda kutip (") maupun karakter khusus Tidak ada keraguan bahwa itu adalah konstan:. setiap kali kita menulis 1776 dalam sebuah program, kita akan mengacu ke nilai 1776.

Selain angka desimal (orang-orang bahwa kita semua digunakan untuk menggunakan setiap hari), C + + memungkinkan penggunaan angka oktal (basis 8) dan angka heksadesimal (basis 16) sebagai konstanta literal. Jika kita ingin mengekspresikan nomor oktal kita harus mendahului dengan 0 (karakter nol). Dan untuk mengekspresikan angka heksadesimal kita harus mendahului itu dengan karakter 0x (nol, x). Sebagai contoh, konstanta literal berikut adalah semua setara dengan satu sama lain:





1
2
3
75         // decimal
0113       // octal
0x4b       // hexadecimal 




Semua ini merupakan nomor yang sama: 75 (tujuh puluh lima) dinyatakan sebagai angka-10 base, angka angka oktal dan heksadesimal, masing-masing.

Konstanta Literal, seperti variabel, yang dianggap memiliki jenis data tertentu. Secara default, literal integer adalah tipe int. Namun, kami bisa memaksa mereka untuk baik akan unsigned dengan menambahkan karakter u untuk itu, atau panjang dengan menambahkan l:





1
2
3
4
75         // int
75u        // unsigned int
75l        // long
75ul       // unsigned long 



 Dalam kedua kasus, akhiran dapat ditentukan baik menggunakan huruf besar atau huruf kecil.
Floating Point Numbers
Mereka mengekspresikan angka dengan desimal dan / atau eksponen. Mereka dapat mencakup baik titik desimal, karakter e (yang mengekspresikan "oleh sepuluh pada ketinggian Xth", dimana X adalah nilai integer yang mengikuti karakter e), atau keduanya titik desimal dan karakter e:




1
2
3
4
3.14159    // 3.14159
6.02e23    // 6.02 x 10^23
1.6e-19    // 1.6 x 10^-19
3.0        // 3.0 




Ini adalah empat nomor yang valid dengan desimal disajikan dalam C + +. Nomor pertama adalah PI, yang kedua adalah jumlah Avogadro, yang ketiga adalah muatan listrik dari sebuah elektron (jumlah yang sangat kecil)-semuanya mendekati-dan yang terakhir adalah nomor tiga dinyatakan sebagai floating-point numerik literal.

Jenis default untuk literal floating point adalah double. Jika Anda secara eksplisit ingin mengekspresikan float atau long double numerik literal, Anda dapat menggunakan f atau akhiran l:



 
1
2
3.14159L   // long double
6.02e23f   // float 


Setiap huruf yang dapat menjadi bagian dari numerik konstanta floating-point (,l, e, f) dapat ditulis menggunakan huruf baik lebih rendah atau huruf besar tanpa perbedaan arti mereka.
Karakter dan string literal



Character and string literals

 
Ada juga konstanta non-numerik, seperti:

 
1
2
3
4
'z'
'p'
"Hello world"
"How do you do?" 


Dua yang pertama merupakan ekspresi konstanta karakter tunggal, dan dua berikut ini mewakili string literal terdiri dari beberapa karakter. Perhatikan bahwa untuk mewakili satu karakter kami lampirkan di antara tanda kutip tunggal (') dan untuk mengekspresikan string (yang umumnya terdiri dari lebih dari satu karakter) kami lampirkan di antara tanda kutip ganda (").

Saat menulis literal baik karakter tunggal dan string, perlu untuk menempatkan tanda kutip sekitar mereka untuk membedakan mereka dari identifier variabel yang mungkin atau kata kunci reserved. Perhatikan perbedaan antara dua ekspresi:





1
2
x
'x'


 x saja akan merujuk ke variabel yang identifier adalah x, sedangkan 'x' (yang dimasukkan dalam tanda kutip tunggal) akan mengacu pada konstanta karakter 'x'.

Karakter dan literal string memiliki kekhasan tertentu, seperti kode melarikan diri. Ini adalah karakter khusus yang sulit atau tidak mungkin untuk mengekspresikan dinyatakan dalam kode sumber dari program, seperti newline (\ n) atau tab (\ t). Semuanya didahului dengan backslash (\). Di sini Anda memiliki daftar beberapa kode melarikan diri seperti:







\n
newline
\r
carriage return
\t
tab
\v
vertical tab
\b
backspace
\f
form feed (page feed)
\a
alert (beep)
\'
single quote (')
\"
double quote (")
\?
question mark (?)
\\
backslash (\)




Contoh:
1
2
3
4
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree" 


 Selain itu, Anda dapat mengekspresikan setiap karakter ASCII dengan kode numerik dengan menulis karakter backslash (\) diikuti dengan kode ASCII dinyatakan sebagai oktal (basis-8) atau heksadesimal (basis-16) nomor. Dalam kasus pertama (oktal) digit harus segera mengikuti backslash (misalnya \ 23 atau \ 40), dalam kasus kedua (heksadesimal), karakter x harus ditulis sebelum digit sendiri (misalnya \ x20 atau \ x4A ).

String literal dapat memperpanjang untuk lebih dari satu baris kode dengan menempatkan tanda backslash (\) pada akhir setiap baris yang belum selesai.





1
2
"string expressed in \
two lines" 


Anda juga dapat menggabungkan beberapa string konstanta memisahkan mereka dengan satu atau beberapa ruang kosong, tabulasi, newline atau karakter kosong lain yang valid:





"this forms" "a single" "string" "of characters"


Akhirnya, jika kita ingin string literal untuk secara eksplisit terbuat dari karakter lebar (wchar_t type), , bukan karakter yang sempit (char type), kita dapat mendahului konstanta dengan L awalan:





L"This is a wide character string"


 

Karakter Wide digunakan terutama untuk mewakili set karakter non-Inggris atau eksotis.
 

Boolean literal
Hanya ada dua nilai Boolean yang valid: true dan false. Ini dapat dinyatakan dalam C + + sebagai nilai bool tipe dengan menggunakan Boolean literal benar dan salah.


Anda dapat menentukan nama Anda sendiri untuk konstanta yang anda gunakan sangat sering tanpa harus resor untuk variabel memakan memori, hanya dengan menggunakan direktif preprocessor # define. Formatnya adalah:




Defined constants (#define)



#define identifier value
For example:
1
2
#define PI 3.14159
#define NEWLINE '\n' 


Hal ini mendefinisikan dua konstanta baru: PI dan NEWLINE. Setelah mereka ditetapkan, Anda dapat menggunakannya di seluruh kode seolah-olah mereka yang lain biasa konstan, misalnya:










 












// defined constants: calculate circumference
 
#include <iostream>
using namespace std;
 
#define PI 3.14159
#define NEWLINE '\n'
 
int main ()
{
  double r=5.0;               // radius
  double circle;
 
  circle = 2 * PI * r;
  cout << circle;
  cout << NEWLINE;
 
  return 0;
}


Run: 


31.4159
 
 Bahkan satu-satunya yang preprocessor kompiler tidak ketika bertemu # define arahan adalah harfiah mengganti terjadinya mereka identifier (pada contoh sebelumnya, ini adalah PI dan NEWLINE) dengan kode yang mereka telah didefinisikan (3,14159 dan '\ n 'masing-masing).

The # define direktif bukan C + + pernyataan tetapi arahan untuk preprocessor, karena itu mengasumsikan seluruh baris sebagai patokan dan tidak membutuhkan tanda titik koma (;) di ujungnya. Jika anda menambah sebuah karakter titik koma (;) di akhir, itu juga akan ditambahkan dalam semua kejadian dari identifier dalam tubuh program yang preprocessor menggantikan.



Dideklarasikan konstanta (const)


Dengan prefix const Anda dapat mendeklarasikan konstanta dengan tipe tertentu dengan cara yang sama seperti yang Anda akan lakukan dengan variabel:


 


1 const int pathwidth = 100;
2 const char tabulator = '\t';


Di sini, pathwidth dan tabulasi adalah dua konstanta diketik. Mereka diperlakukan sama seperti variabel biasa kecuali bahwa nilai tidak dapat diubah setelah definisi mereka.


Source Of cplusplus.com 

Read more...

Labels

My Blog List

Followers