+ Reply to Thread
Page 2 of 7 1 2 3 4 ...
Results 11 to 20 of 66

 

Thread: كتب c# باللغة الانجليزية

  • Thread Tools
  1. #11 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    Why Data Types Are Important
    Data types are especially important in C# because it is a strongly typed language. This means
    that all operations are type-checked by the compiler for type compatibility. Illegal operations
    will not be compiled. Thus, strong type-checking helps prevent errors and enhances reliability.
    To enable strong type-checking, all variables, expressions, and values have a type. There is no
    concept of a “typeless” variable, for example. Furthermore, the type of a value determines what
    operations are allowed on it. An operation allowed on one type might not be allowed on another.
    C#’s Value Types
    C# contains two general categories of built-in data types: value types and reference types. The
    difference between the two types is what a variable contains. For a value type, a variable holds
    an actual value, such 101 or 98.6. For a reference type, a variable holds a reference to the value.

    ---------- Post added at 09:06 PM ---------- Previous post was at 09:05 PM ----------

    The most commonly used reference type is the class, and a discussion of classes and reference
    types is deferred until later. The value types are described here.
    At the core of C# are the 13 value types shown in Table 2-1. Collectively, these are
    referred to as the simple types. They are called simple types because they consist of a single
    value. (In other words, they are not a composite of two or more values.) They form the
    foundation of C#’s type system, providing the basic, low-level data elements upon which
    a program operates. The simple types are also sometimes referred to as primitive types.
    C# strictly specifies a range and behavior for each simple type. Because of portability
    requirements and to support mixed-language programming, C# is uncompromising on this
    account. For example, an int is the same in all execution environments. There is no need to
    rewrite code to fit a specific platform. While strictly specifying the size of the simple types
    may cause a small loss of performance in some environments, it is necessary in order to
    achieve portability.
    NOTE
    In addition to the simple types, C# defines three other categories of value types. These
    are enumerations, structures, and nullable types, all of which are described later in
    this book.
    Integers
    C# defines nine integer types: char, byte, sbyte, short, ushort, int, uint, long, and ulong.
    However, the char type is primarily used for representing characters, and it is discussed later

    ---------- Post added at 09:11 PM ---------- Previous post was at 09:06 PM ----------

    Type Meaning
    bool Represents true/false values
    byte 8-bit unsigned integer
    char Character
    decimal Numeric type for financial calculations
    double Double-precision floating point
    float Single-precision floating point
    int Integer
    long Long integer
    sbyte 8-bit signed integer
    short Short integer
    uint Unsigned integer
    ulong Unsigned long integer
    ushort Unsigned short integer
    Table 2-1 The C# Simple Types

    ---------- Post added at 09:12 PM ---------- Previous post was at 09:11 PM ----------

    in this chapter. The remaining eight integer types are used for numeric calculations. Their bitwidth
    and ranges are shown here:
    Type Width in Bits Range
    byte 8 0 to 255
    sbyte 8 –128 to 127
    short 16 –32,768 to 32,767
    ushort 16 0 to 65,535
    int 32 –2,147,483,648 to 2,147,483,647
    uint 32 0 to 4,294,967,295
    long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    ulong 64 0 to 18,446,744,073,709,551,615
    As the table shows, C# defines both signed and unsigned versions of the various integer
    types. The difference between signed and unsigned integers is in the way the high-order bit of
    the integer is interpreted. If a signed integer is specified, the C# compiler will generate code
    that assumes the high-order bit of an integer is to be used as a sign flag. If the sign flag is 0,
    the number is positive; if it is 1, the number is negative. Negative numbers are almost always
    represented using the two’s complement approach. In this method, all bits in the number are
    reversed, and then 1 is added to this number.
    Signed integers are important for a great many algorithms, but they have only half the
    absolute magnitude of their unsigned relatives. For example, as a short, here is 32,767:
    0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

    ---------- Post added at 09:12 PM ---------- Previous post was at 09:12 PM ----------

    For a signed value, if the high-order bit were set to 1, the number would then be interpreted
    as –1 (assuming the two’s complement format). However, if you declared this to be a ushort,
    then when the high-order bit was set to 1, the number would become 65,535.
    Probably the most commonly used integer type is int. Variables of type int are often
    employed to control loops, to index arrays, and for general-purpose integer math. When you
    need an integer that has a range greater than int, you have many options. If the value you want
    to store is unsigned, you can use uint. For large signed values, use long. For large unsigned
    values, use ulong.
    Here is a program that computes the number of cubic inches contained in a cube that is
    1 mile long on each side. Because this value is so large, the program uses a long variable to
    hold it.
    // Compute the number of cubic inches in 1 cubic mile.
    using System;
    class Inches {
    static void Main() {
    long ci;
    long im;
    im = 5280 * 12;
    ci = im * im * im;
    Console.WriteLine("There are " + ci +
    " cubic inches in cubic mile.");
    }
    }
    Here is the output from the program:
    There are 254358061056000 cubic inches in cubic mile.
    Clearly, the result could not have been held in an int or uint variable.
    The smallest integer types are byte and sbyte. The byte type is an unsigned value between
    0 and 255. Variables of type byte are especially useful when working with raw binary data,
    such as a byte stream produced by some device. For small signed integers, use sbyte. Here is
    an example that uses a variable of type byte to control a for loop that produces the summation
    of the number 100:

    ---------- Post added at 09:13 PM ---------- Previous post was at 09:12 PM ----------

    // Use byte.
    using System;
    class Use_byte {
    static void Main() {
    byte x;
    int sum;
    sum = 0;
    for(x = 1; x <= 100; x++)
    sum = sum + x;
    Console.WriteLine("Summation of 100 is " + sum);
    }
    }
    The output from the program is shown here:
    Summation of 100 is 5050
    Since the for loop runs only from 0 to 100, which is well within the range of a byte, there is no
    need to use a larger type variable to control it. Of course, byte could not have been used to hold
    the result of the summation because 5050 is far outside its range. This is why sum is an int.
    When you need an integer that is larger than a byte or sbyte but smaller than an int or
    uint, use short or ushort.

    ---------- Post added at 09:13 PM ---------- Previous post was at 09:13 PM ----------

    Floating-Point Types
    As explained in Chapter 1, the floating-point types can represent numbers that have fractional
    components. There are two kinds of floating-point types, float and double, which represent
    single- and double-precision numbers, respectively. The type float is 32 bits wide and has a
    range of 1.5E–45 to 3.4E+38. The double type is 64 bits wide and has a range of 5E–324 to
    1.7E+308.
    Of the two, double is the most commonly used. One reason for this is that many of the
    math functions in C#’s class library (which is the .NET Framework library) use double values.
    For example, the Sqrt( ) method (which is defined by the System.Math class) returns a double
    value that is the square root of its double argument. Here, Sqrt( ) is used to compute the length
    of the hypotenuse given the lengths of the two opposing sides:
    /*
    Use the Pythagorean theorem to find the length of the hypotenuse
    given the lengths of the two opposing sides.
    */
    using System;
    class Hypot {
    static void Main() {
    double x, y, z;
    x = 3;
    y = 4;
    z = Math.Sqrt(x*x + y*y);
    Console.WriteLine("Hypotenuse is " + z);
    }
    }
    The output from the program is shown here:
    Hypotenuse is 5
    Here’s another point about the preceding example. As mentioned, Sqrt( ) is a member of
    the Math class. Notice how Sqrt( ) is called; it is preceded by the name Math. This is similar
    to the way Console precedes WriteLine( ). Although not all standard methods are called by
    specifying their class name first, several are.
    The decimal Type
    Perhaps the most interesting C# numeric type is decimal, which is intended for use in
    monetary calculations. The decimal type utilizes 128 bits to represent values within the range
    1E–28 to 7.9E+28. As you may know, normal floating-point arithmetic is subject to a variety

    ---------- Post added at 09:14 PM ---------- Previous post was at 09:13 PM ----------

    of rounding errors when it is applied to decimal values. The decimal type eliminates these
    errors and can accurately represent up to 28 decimal places (or 29 places, in some cases).
    This ability to represent decimal values without rounding errors makes it especially useful for
    computations that involve money.
    Here is a program that uses the decimal type in a financial calculation. The program
    computes a balance after interest has been applied.
    // Use the decimal type in a financial calculation.
    using System;
    class UseDecimal {
    static void Main() {
    decimal balance;
    decimal rate;
    // Compute new balance.
    balance = 1000.10m;
    rate = 0.1m;
    balance = balance * rate + balance;
    Console.WriteLine("New balance: $" + balance);
    }
    }
    The output from this program is shown here:
    New balance: $1100.110

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  2. #12 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    In the program, notice that the decimal constants are followed by the m or M suffix. This
    is necessary because without the suffix, these values would be interpreted as standard floatingpoint
    constants, which are not compatible with the decimal data type. (We will look more
    closely at how to specify numeric constants later in this chapter.)
    Q: The other computer languages that I have worked with do not have a decimal data
    type. Is it unique to C#?
    A: The decimal type is not supported by C, C++, or Java as a built-in type. Thus, within its
    direct line of descent, it is unique.
    Characters
    In C#, characters are not 8-bit quantities like they are in many other computer languages, such
    as C++. Instead, C# uses Unicode. Unicode defines a character set that can represent all of the
    characters found in all human languages. Thus, in C#, char is an unsigned 16-bit type having a
    range of 0 to 65,535. The standard 8-bit ASCII character set is a subset of Unicode and ranges
    from 0 to 127. Thus, the ASCII characters are still valid C# characters.
    A character variable can be assigned a value by enclosing the character inside single
    quotes. For example, this assigns X to the variable ch:
    char ch;
    ch = 'X';
    You can output a char value using a WriteLine( ) statement. For example, this line
    outputs the value in ch:
    Console.WriteLine("This is ch: " + ch);
    Although char is defined by C# as an integer type, it cannot be freely mixed with integers
    in all cases. This is because there is no automatic type conversion from integer to char. For
    example, the following fragment is invalid:
    char ch;
    ch = 10; // error, won't work
    The reason the preceding code will not work is that 10 is an integer value and it won’t
    automatically convert to a char. Thus, the assignment involves incompatible types. If you
    attempt to compile this code, you will see an error message. Later in this chapter you will see
    a way around this restriction.

    ---------- Post added at 09:16 PM ---------- Previous post was at 09:15 PM ----------

    Q: Why does C# use Unicode?
    A: C# was designed to allow programs to be written for worldwide use. Thus, it needs to use
    a character set that can represent all of the world’s languages. Unicode is the standard
    character set designed expressly for this purpose. Of course, the use of Unicode is
    inefficient for languages such as English, German, Spanish, or French, whose characters
    can be contained within 8 bits. But such is the price of global portability.
    The bool Type
    The bool type represents true/false values. C# defines the values true and false using the
    reserved words true and false. Thus, a variable or expression of type bool will be one of these
    two values. Furthermore, there is no conversion defined between bool and integer values. For
    example, 1 does not convert to true, and 0 does not convert to false.
    Here is a program that demonstrates the bool type:
    // Demonstrate bool values.
    using System;
    class BoolDemo {
    static void Main() {
    bool b;
    b = false;
    Console.WriteLine("b is " + b);
    b = true;
    Console.WriteLine("b is now " + b);
    // A bool value can control the if statement.
    if(b) Console.WriteLine("This is executed.");
    b = false;
    if(b) Console.WriteLine("This is not executed.");
    // The outcome of a relational operator is a bool value.
    Console.WriteLine("88 > 17 is " + (88 > 17));
    }
    }

    ---------- Post added at 09:16 PM ---------- Previous post was at 09:16 PM ----------

    The output generated by this program is shown here:
    b is False
    b is now True
    This is executed.
    88 > 17 is True
    There are three interesting things to notice about this program. First, as you can see, when
    a bool value is output by WriteLine( ), “True” or “False” is displayed. Second, the value of a
    bool variable is sufficient, by itself, to control the if statement. There is no need to write an if
    statement like this:
    if(b == true) ...
    Third, the outcome of a relational operator, such as <, is a bool value. This is why the expression
    88 > 17 displays the value “True.” Further, the extra set of parentheses around 88 > 17 is
    necessary because the + operator has a higher precedence than the > operator.

    ---------- Post added at 09:17 PM ---------- Previous post was at 09:16 PM ----------

    Some Output Options
    Before continuing our examination of data types and operators, a small digression will be
    useful. Up to this point, when outputting lists of data, you have been separating each part of
    the list with a plus sign, as shown here:
    Console.WriteLine("You ordered " + 2 + " items at $" + 3 + " each.");
    Although very convenient, outputting numeric information in this way does not give you
    any control over how that information appears. For example, for a floating-point value, you
    can’t control the number of decimal places displayed. Consider the following statement:
    Console.WriteLine("Here is 10/3: " + 10.0/3.0);
    It generates this output:
    Here is 10/3: 3.33333333333333
    While this might be fine for some purposes, displaying so many decimal places could be
    inappropriate for others. For example, in financial calculations, you will usually want to display
    two decimal places.
    To control how numeric data is formatted, you will need to use a second form of WriteLine( ),
    shown here, which allows you to embed formatting information:
    WriteLine(“format string”, arg0, arg1, ... , argN)
    In this version, the arguments to WriteLine( ) are separated by commas and not plus signs.
    The format string contains two items: regular, printing characters that are displayed as-is and
    format specifiers. Format specifiers take this general form:
    {argnum, width: fmt}

    ---------- Post added at 09:17 PM ---------- Previous post was at 09:17 PM ----------

    Here, argnum specifies the number of the argument (starting from zero) to display. The minimum
    width of the field is specified by width, and the format is specified by fmt.
    During execution, when a format specifier is encountered in the format string, the
    corresponding argument, as specified by argnum, is substituted and displayed. Thus, it is the
    position of a format specification within the format string that determines where its matching
    data will be displayed. Both width and fmt are optional. Thus, in its simplest form, a format
    specifier simply indicates which argument to display. For example, {0} indicates arg0, {1}
    specifies arg1, and so on.
    Let’s begin with a simple example. The statement
    Console.WriteLine("February has {0} or {1} days.", 28, 29);
    produces the following output:
    February has 28 or 29 days.
    As you can see, the value 28 is substituted for {0}, and 29 is substituted for {1}. Thus, the
    format specifiers identify the location at which the subsequent arguments—in this case,

    ---------- Post added at 09:18 PM ---------- Previous post was at 09:17 PM ----------

    28 and 29—are displayed within the string. Furthermore, notice that the additional values are
    separated by commas, not plus signs.
    Here is a variation of the preceding statement that specifies minimum field widths:
    Console.WriteLine("February has {0,10} or {1,5} days.", 28, 29);
    It produces the following output:
    February has 28 or 29 days.
    As you can see, spaces have been added to fill out the unused portions of the fields. Remember,
    a minimum field width is just that: the minimum width. Output can exceed that width if needed.
    In the preceding examples, no formatting was applied to the values themselves. Of course,
    the value of using format specifiers is to control the way the data looks. The types of data most
    commonly formatted are floating-point and decimal values. One of the easiest ways to specify
    a format is to describe a template that WriteLine( ) will use. To do this, show an example of
    the format that you want, using #s to mark the digit positions. For instance, here is a better way
    to display 10 divided by 3:
    Console.WriteLine("Here is 10/3: {0:#.##}", 10.0/3.0);
    The output from this statement is shown here:
    Here is 10/3: 3.33
    In this example, the template is #.##, which tells WriteLine( ) to display two decimal places.
    It is important to understand, however, that WriteLine( ) will display more than one digit to
    the left of the decimal point if necessary so as not to misrepresent the value.
    If you want to display monetary values, use the C format specifier. For example,
    decimal balance;
    balance = 12323.09m;
    Console.WriteLine("Current balance is {0:C}", balance);
    The output from this sequence is shown here (in U.S. dollar format):
    Current balance is $12,323.09
    Talk to Mars
    At its closest point to Earth, Mars is approximately 34 million miles away. Assuming there
    is someone on Mars you want to talk with, what is the delay between the time a radio signal
    leaves Earth and the time it arrives on Mars? This program supplies the answer. Recall that light
    travels approximately 186,000 miles per second. Thus, to compute the delay, you will need to
    divide the distance by the speed of light. Display the delay in terms of seconds and minutes.

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  3. #13 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    Step by Step
    1. Create a new file called Mars.cs.
    2. To compute the delay, you will need to use floating-point values. Why? Because the time
    interval will have a fractional component. Here are the variables used by the program:
    double distance;
    double lightspeed;
    double delay;
    double delay_in_min;
    3. Give distance and lightspeed these values:
    distance = 34000000; // 34,000,000 miles
    lightspeed = 186000; // 186,000 miles per second
    4. To compute the delay, divide distance by lightspeed. This yields the delay in seconds.
    Assign this value to delay and display the results. These steps are shown here:
    delay = distance / lightspeed;
    Console.WriteLine("Time delay when talking to Mars: " +
    delay + " seconds.");
    5. Divide the number of seconds in delay by 60 to obtain the delay in minutes; display that
    result using these lines of code:
    delay_in_min = delay / 60;
    Console.WriteLine("This is " + delay_in_min +
    " minutes.");
    Here is the entire Mars.cs program listing:
    // Talk to Mars
    using System;
    class Mars {
    static void Main() {
    double distance;
    double lightspeed;
    double delay;
    double delay_in_min;
    distance = 34000000; // 34,000,000 miles
    lightspeed = 186000; // 186,000 miles per second
    delay = distance / lightspeed;

    ---------- Post added at 09:20 PM ---------- Previous post was at 09:19 PM ----------

    Console.WriteLine("Time delay when talking to Mars: " +
    delay + " seconds.");
    delay_in_min = delay / 60;
    Console.WriteLine("This is " + delay_in_min +
    " minutes.");
    }
    }
    6. Compile and run the program. The following result is displayed:
    Time delay when talking to Mars: 182.795698924731 seconds.
    This is 3.04659498207885 minutes.
    7. For most people, the program displays too many decimal places. To improve the readability
    of the program, substitute the following WriteLine( ) statements for the ones shown in the
    program:
    Console.WriteLine("Time delay when talking to Mars: {0:#.###} seconds",
    delay);
    Console.WriteLine("This is about {0:#.###} minutes", delay_in_min);
    8. Recompile and run the program. When you do, you will see this output:
    Time delay when talking to Mars: 182.796 seconds
    This is about 3.047 minutes
    Now, only three decimal places are displayed.

    ---------- Post added at 09:20 PM ---------- Previous post was at 09:20 PM ----------

    Literals
    In C#, literals refer to fixed values that are represented in their human-readable form. For
    example, the number 100 is a literal. For the most part, literals and their usage are so intuitive
    that they have been used in one form or another by all the preceding sample programs. Now
    the time has come to explain them formally.
    C# literals can be of any of the value types. The way each literal is represented depends
    upon its type. As explained earlier, character literals are enclosed between single quotes. For
    example ‘a’ and ‘%’ are both character literals.
    Integer literals are specified as numbers without fractional components. For example,
    10 and –100 are integer literals. Floating-point literals require the use of the decimal point
    followed by the number’s fractional component. For example, 11.123 is a floating-point literal.
    C# also allows you to use scientific notation for floating-point numbers.
    Since C# is a strongly typed language, literals, too, have a type. Naturally, this raises the
    following question: What is the type of a numeric literal? For example, what is the type of 12,
    123987, or 0.23? Fortunately, C# specifies some easy-to-follow rules that answer these questions.

    ---------- Post added at 09:21 PM ---------- Previous post was at 09:20 PM ----------

    First, for integer literals, the type of the literal is the smallest integer type that will hold it,
    beginning with int. Thus, an integer literal is of type int, uint, long, or ulong, depending upon
    its value. Second, floating-point literals are of type double.
    If C#’s default type is not what you want for a literal, you can explicitly specify its type by
    including a suffix. To specify a long literal, append an l or an L. For example, 12 is an int, but
    12L is a long. To specify an unsigned integer value, append a u or U. Thus, 100 is an int, but
    100U is a uint. To specify an unsigned, long integer, use ul or UL. For example, 984375UL is
    of type ulong.
    To specify a float literal, append an F or f. For example, 10.19F is of type float. Although
    redundant, you can specify a double literal by appending a D or d. (As just mentioned,
    floating-point literals are double by default.)
    To specify a decimal literal, follow its value with an m or M. For example, 9.95M is
    a decimal literal.
    Although integer literals create an int, uint, long, or ulong value by default, they can
    still be assigned to variables of type byte, sbyte, short, or ushort as long as the value being
    assigned can be represented by the target type.

    ---------- Post added at 09:21 PM ---------- Previous post was at 09:21 PM ----------

    Hexadecimal Literals
    In programming, it is sometimes easier to use a number system based on 16 instead of 10. The
    base 16 number system is called hexadecimal and uses the digits 0 through 9, plus the letters
    A through F, which stand for 10, 11, 12, 13, 14, and 15. For example, the hexadecimal number
    10 is 16 in decimal. Because of the frequency with which hexadecimal numbers are used, C#
    allows you to specify integer literals in hexadecimal format. A hexadecimal literal must begin
    with 0x (a zero followed by an x). Here are some examples:
    count = 0xFF; // 255 in decimal
    incr = 0x1a; // 26 in decimal
    Character Escape Sequences
    Enclosing character constants in single quotes works for most printing characters, but a few
    characters, such as the carriage return, pose a special problem when a text editor is used. In
    addition, certain other characters, such as single and double quotes, have special meaning
    in C#, so you cannot use them directly. For these reasons, C# provides special escape
    sequences, shown in Table 2-2. These sequences are used in place of the characters that they
    represent.
    For example, this assigns ch the tab character:
    ch = '\t';
    The next example assigns a single quote to ch:
    ch = '\'';
    Escape Sequence Description
    \a Alert (bell)
    \b Backspace
    \f Form feed
    \n Newline (linefeed)
    \r Carriage return
    \t Horizontal tab
    \v Vertical tab
    \0 Null
    \' Single quote
    \" Double quote
    \\ Backslash

    ---------- Post added at 09:22 PM ---------- Previous post was at 09:21 PM ----------

    String Literals
    C# supports another type of literal: the string. A string literal is a set of characters enclosed by
    double quotes. For example,
    "this is a test"
    is a string. You have seen examples of strings in many of the WriteLine( ) statements in the
    preceding sample programs.
    In addition to normal characters, a string literal can also contain one or more of the escape
    sequences just described. For example, consider the following program. It uses the \n and \t
    escape sequences.
    Q: I know that C++ allows integer literals to be specified in octal (a number system based
    on 8). Does C# allow octal literals?
    A: No. C# allows integer literals to be specified only in decimal or hexadecimal form. Octal is
    seldom used in today’s modern programming environments.

    ---------- Post added at 09:23 PM ---------- Previous post was at 09:22 PM ----------

    // Demonstrate escape sequences in strings.
    using System;
    class StrDemo {
    static void Main() {
    Console.WriteLine("First line\nSecond line");
    Console.WriteLine("A\tB\tC");
    Console.WriteLine("D\tE\tF");
    }
    }
    The output is shown here:
    First line
    Second line
    A B C
    D E F
    Notice how the \n escape sequence is used to generate a new line. You don’t need to use
    multiple WriteLine( ) statements to get multiline output. Just embed \n within a longer string
    at the points at which you want the newlines to occur.
    In addition to the form of string literal just described, you can specify a verbatim string
    literal. A verbatim string literal begins with an @, which is followed by a quoted string. The
    contents of the quoted string are accepted without modification and can span two or more
    lines. Thus, you can include newlines, tabs, and so on, but you don’t need to use the escape
    sequences. The only exception is that to obtain a double quote ("), you must use two double
    quotes in a row (""). Here is a program that demonstrates verbatim string literals:

    ---------- Post added at 09:23 PM ---------- Previous post was at 09:23 PM ----------

    // Demonstrate verbatim literal strings.
    using System;
    class Verbatim {
    static void Main() {
    Console.WriteLine(@"This is a verbatim
    string literal
    that spans several lines.
    ");
    Console.WriteLine(@"Here is some tabbed output:
    1 2 3 4
    5 6 7 8
    ");
    Console.WriteLine(@"Programmers say, ""I like C#.""");
    }
    }
    The output from this program is shown here:
    This is a verbatim
    string literal
    that spans several lines.
    Here is some tabbed output:
    1 2 3 4
    5 6 7 8
    Programmers say, "I like C#."
    The important point to notice about the preceding program is that the verbatim string literals
    are displayed precisely as they are entered into the program.
    The advantage of verbatim string literals is that you can specify output in your program
    exactly as it will appear on the screen. However, in the case of multiline strings, the wrapping
    will cause the indentation of your program to be obscured. For this reason, the programs in this
    book will make only limited use of verbatim string literals. That said, they are still a wonderful
    benefit for many formatting situations.

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  4. #14 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    A Closer Look at Variables
    Variables were introduced in Chapter 1. As you learned, variables are declared using this form
    of statement:
    type var-name;
    where type is the data type of the variable and var-name is its name. You can declare a variable
    of any valid type, including the value types just described. It is important to understand that
    the capabilities of the variable are determined by its type. For example, a variable of type
    bool cannot be used to store floating-point values. Furthermore, the type of a variable cannot
    change during its lifetime. An int variable cannot turn into a char variable, for example.
    All variables in C# must be declared. This is necessary because the compiler must know
    what type of data a variable contains before it can properly compile any statement that uses the
    variable. It also enables C# to perform strict type-checking.
    C# defines several different kinds of variables. The kinds that we have been using are
    called local variables because they are declared within a method.
    Q: Is a string consisting of a single character the same as a character literal? For
    example, is “k” the same as ‘k’?
    A: No. You must not confuse strings with characters. A character literal represents a single
    letter of type char. A string containing only one letter is still a string. Although strings
    consist of characters, they are not the same type.
    Ask the Expert

    ---------- Post added at 09:24 PM ---------- Previous post was at 09:24 PM ----------

    Initializing a Variable
    One way to give a variable a value is through an assignment statement, as you have already
    seen. Another way is by giving it an initial value when it is declared. To do this, follow
    the variable’s name with an equal sign and the value being assigned. The general form of
    initialization is shown here:
    type var-name = value;
    Here, value is the value that is given to var-name when var-name is created. The value must be
    compatible with the specified type.
    Here are some examples:
    int count = 10; // give count an initial value of 10
    char ch = 'X'; // initialize ch with the letter X
    float f = 1.2F; // f is initialized with 1.2
    When declaring two or more variables of the same type using a comma-separated list, you
    can give one or more of those variables an initial value. For example:
    int a, b = 8, c = 19, d; // b and c have initializations
    In this case, only b and c are initialized.

    ---------- Post added at 09:25 PM ---------- Previous post was at 09:24 PM ----------

    Dynamic Initialization
    Although the preceding examples have used only constants as initializers, C# allows variables
    to be initialized dynamically, using any expression valid at the point at which the variable is
    declared. For example, here is a short program that computes the volume of a cylinder given
    the radius of its base and its height:
    // Demonstrate dynamic initialization.
    using System;
    class DynInit {
    static void Main() {
    double radius = 4, height = 5;
    // Dynamically initialize volume.
    double volume = 3.1416 * radius * radius * height;
    Console.WriteLine("Volume is " + volume);
    }
    }
    Here, three local variables—radius, height, and volume—are declared. The first two, radius and
    height, are initialized by constants. However, volume is initialized dynamically to the volume of
    the cylinder. The key point here is that the initialization expression can use any element valid at
    the point of the initialization, including calls to methods, other variables, or literals.

    ---------- Post added at 09:26 PM ---------- Previous post was at 09:25 PM ----------

    Implicitly Typed Variables
    As explained, in C# all variables must be declared. Normally, a declaration includes the type
    of the variable, such as int or bool, followed by the name of the variable. However, beginning
    with C# 3.0, it is possible to let the compiler determine the type of a variable based on the
    value used to initialize it. This is called an implicitly typed variable.
    An implicitly typed variable is declared using the keyword var, and it must be initialized.
    The compiler uses the type of the initializer to determine the type of the variable. Here is an
    example:
    var pi = 3.1416;
    Because pi is initialized with a floating-point literal (whose type is double by default), the type
    of pi is double. Had pi been declared like this:
    var pi = 3.1416M;
    then pi would have the type decimal instead.
    The following program demonstrates implicitly typed variables:
    // Demonstrate implicitly typed variables.

    ---------- Post added at 09:27 PM ---------- Previous post was at 09:26 PM ----------

    using System;
    class ImpTypedVar {
    static void Main() {
    // These are implicitly typed variables.
    var pi = 3.1416; // pi is a double
    var radius = 10; // radius is an int
    // Both msg and msg2 are string types.
    var msg = "Radius: ";
    var msg2 = "Area: ";
    // Explicitly declare area as a double.
    double area;
    Console.WriteLine(msg2 + radius);
    area = pi * radius * radius;
    Console.WriteLine(msg + area);
    Console.WriteLine();
    radius = radius + 2;
    Console.WriteLine(msg2 + radius);
    area = pi * radius * radius;

    ---------- Post added at 09:28 PM ---------- Previous post was at 09:27 PM ----------

    Console.WriteLine(msg + area);
    // The following statement will not compile because
    // radius is an int and cannot be assigned a floating-
    // point value.
    // radius = 12.2; // Error!
    }
    }
    The output is shown here:
    Area: 10
    Radius: 314.16
    Area: 12
    Radius: 452.3904
    It is important to emphasize that an implicitly typed variable is still a strongly typed
    variable. Notice this commented-out line in the program:
    // radius = 12.2; // Error!
    This assignment is invalid because radius is of type int. Thus, it cannot be assigned a floatingpoint
    value. The only difference between an implicitly typed variable and a “normal” explicitly
    typed variable is how the type is determined. Once that type has been determined, the variable
    has a type, and this type is fixed throughout the lifetime of the variable. Thus, the type of
    radius cannot be changed during the execution of the program.
    Implicitly typed variables were added to C# to handle some special-case situations, the
    most important of which relate to LINQ (language-integrated query), which is described later
    in this book. For the majority of variables, you should use explicitly typed variables because
    they make your code easier to read and easier to understand. Implicitly typed variables should
    be used only when necessary. They are not intended to replace normal variable declarations in
    general. In essence, use, but don’t abuse, this new C# feature.
    One last point: Only one implicitly typed variable can be declared at any one time.
    Therefore, the following declaration
    var count = 10, max = 20; // Error!
    is wrong and won’t compile because it attempts to declare both count and max at the same time.
    The Scope and Lifetime of Variables
    So far, all of the variables that we have been using are declared at the start of the Main( )
    method. However, C# allows a local variable to be declared within any block. As explained in
    Chapter 1, a block is begun with an ****ing curly brace and ended with a closing curly brace.
    A block defines a scope. Thus, each time you start a new block, you are creating a new scope.
    A scope determines what names are visible to other parts of your program. It also determines
    the lifetime of local variables.

    ---------- Post added at 09:28 PM ---------- Previous post was at 09:28 PM ----------

    The most important scopes in C# are those defined by a class and those defined by a method. A
    discussion of class scope (and variables declared within it) is deferred until later in this book, when
    classes are described. For now, we will examine only the scopes defined by or within a method.
    The scope defined by a method begins with its ****ing curly brace and ends with its
    closing curly brace. However, if that method has parameters, they, too, are included within the
    scope defined by the method.
    As a general rule, local variables declared inside a scope are not visible to code that is defined
    outside that scope. Thus, when you declare a variable within a scope, you are preventing it
    from being accessed or modified by code outside the scope. Indeed, the scope rules provide the
    foundation for encapsulation.
    Scopes can be nested. For example, each time you create a block of code, you are creating
    a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means
    that local variables declared in the outer scope will be visible to code within the inner scope.
    However, the reverse is not true. Local variables declared within the inner scope will not be
    visible outside it.
    To understand the effect of nested scopes, consider the following program:

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  5. #15 Collapse post
    ahmedamire is offline
    Banned Array
    Join Date
    Sep 2013
    Posts
    664
    Accrued Payments
    70 USD
    Thanks
    0
    Thanked 0 Times in 0 Posts
    شكرا جزيلا اخي على هذا الكتاب الرائع والذي استفدت منه كثيرا
    وارجو ان تكثر من مثل هذا المجذو لتزيدنا علما ومعرفتا

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  6. #16 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    // Demonstrate block scope.
    using System;
    class ScopeDemo {
    static void Main() {
    int x; // known to all code within Main()
    x = 10;
    if(x == 10) { // start new scope
    int y = 20; // known only to this block
    // x and y both known here.
    Console.WriteLine("x and y: " + x + " " + y);
    x = y * 2;
    }
    // y = 100; // Error! y not known here
    // x is still known here.
    Console.WriteLine("x is " + x);
    }
    }
    As the comments indicate, the variable x is declared at the start of Main( )’s scope and is
    accessible to all subsequent code within Main( ). Within the if block, y is declared. Since a
    block defines a scope, y is visible only to other code within its block. This is why outside of
    its block, the line y = 100; is commented out. If you remove the leading comment symbol, a
    compile-time error will occur because y is not visible outside of its block. Within the if block,
    x can be used because code within a block (that is, a nested scope) has access to variables
    declared by an enclosing scope.

    ---------- Post added at 09:29 PM ---------- Previous post was at 09:29 PM ----------

    Within a block, local variables can be declared at any point, but are valid only after they
    are declared. Thus, if you define a variable at the start of a method, it is available to all of
    the code within that method. Conversely, if you declare a variable at the end of a block, it is
    effectively useless, because no code will have access to it.
    If a variable declaration includes an initializer, that variable will be reinitialized each time
    the block in which it is declared is entered. For example, consider this program:
    // Demonstrate the lifetime of a variable.
    using System;
    class VarInitDemo {
    static void Main() {
    int x;
    for(x = 0; x < 3; x++) {
    int y = -1; // y is initialized each time block is entered
    Console.WriteLine("y is: " + y); // this always prints -1
    y = 100;
    Console.WriteLine("y is now: " + y);
    }
    }
    }

    ---------- Post added at 09:30 PM ---------- Previous post was at 09:29 PM ----------

    The output generated by this program is shown here:
    y is: -1
    y is now: 100
    y is: -1
    y is now: 100
    y is: -1
    y is now: 100
    As you can see, y is always reinitialized to –1 each time the for block is entered. Even though
    it is subsequently assigned the value 100, this value is lost.
    There is one quirk to C#’s scope rules that may surprise you: Although blocks can be
    nested, no variable declared within an inner scope can have the same name as a variable
    declared by an enclosing scope. For example, the following program, which tries to declare
    two separate variables with the same name, will not compile:
    /*
    This program attempts to declare a variable
    in an inner scope with the same name as one
    defined in an outer scope.
    *** This program will not compile. ***
    */
    using System;

    ---------- Post added at 09:31 PM ---------- Previous post was at 09:30 PM ----------

    class NestVar {
    static void Main() {
    int count;
    for(count = 0; count < 10; count = count+1) {
    Console.WriteLine("This is count: " + count);
    // Illegal!!! This conflicts with the previous count.
    int count;
    for(count = 0; count < 2; count++)
    Console.WriteLine("This program is in error!");
    }
    }
    }
    If you come from a C/C++ background, you know that there is no restriction on the names
    that you give variables declared in an inner scope. Thus, in C/C++, the declaration of count
    within the block of the outer for loop is completely valid. However, in C/C++, such a declaration
    hides the outer count. The designers of C# felt that this type of name hiding could easily lead to
    programming errors and disallowed it.

    ---------- Post added at 09:32 PM ---------- Previous post was at 09:31 PM ----------

    Operators
    C# provides a rich operator environment. An operator is a symbol that tells the compiler
    to perform a specific mathematical or logical manipulation. C# has four general classes of
    operators: arithmetic, bitwise, relational, and logical. C# also has several other operators that
    handle certain special situations. This chapter will examine the arithmetic, relational, and
    logical operators. It also examines the assignment operator. The bitwise and other special
    operators are examined later.
    Arithmetic Operators
    C# defines the following arithmetic operators:
    Operator Meaning
    + Addition
    – Subtraction (also unary minus)
    * Multiplication
    / Division
    % Modulus
    ++ Increment
    – – Decrement

    ---------- Post added at 09:33 PM ---------- Previous post was at 09:32 PM ----------

    The operators +, –, *, and / all work in the expected way. These can be applied to any built-in
    numeric data type.
    Although the actions of the basic arithmetic operators are well known to all readers,
    the % warrants some explanation. First, remember that when / is applied to an integer, any
    remainder will be truncated; for example, 10/3 will equal 3 in integer division. You can obtain
    the remainder of this division by using the modulus operator %. It works in C# the way that
    it does in other languages: It yields the remainder of an integer division. For example, 10 % 3
    is 1. In C#, the % can be applied to both integer and floating-point types. Thus, 10.0 % 3.0 is
    also 1. (This differs from C/C++, which allow modulus operations only on integer types.) The
    following program demonstrates the modulus operator:
    // Demonstrate the % operator.
    using System;
    class ModDemo {
    static void Main() {
    int iresult, irem;
    double dresult, drem;
    iresult = 10 / 3;
    irem = 10 % 3;
    dresult = 10.0 / 3.0;
    drem = 10.0 % 3.0;
    Console.WriteLine("Result and remainder of 10 / 3: " +
    iresult + " " + irem);
    Console.WriteLine("Result and remainder of 10.0 / 3.0: " +
    dresult + " " + drem);
    }
    }

    ---------- Post added at 09:34 PM ---------- Previous post was at 09:33 PM ----------

    The output from the program is shown here:
    Result and remainder of 10 / 3: 3 1
    Result and remainder of 10.0 / 3.0: 3.33333333333333 1
    As you can see, the % yields a remainder of 1 for both integer and floating-point operations.
    Increment and Decrement
    Introduced in Chapter 1, the ++ and the – – are the increment and decrement operators, respectively.
    As you will see, they have some special properties that make them quite interesting. Let’s begin by
    reviewing precisely what the increment and decrement operators do.
    The increment operator adds 1 to its operand, and the decrement operator subtracts 1.
    Therefore:
    x = x + 1;

    ---------- Post added at 09:35 PM ---------- Previous post was at 09:34 PM ----------

    can be written as
    ++x; // prefix form
    or as
    x++; // postfix form
    In the foregoing example, there is no difference whether the increment is applied as a prefix
    or a postfix. However, when an increment or decrement is used as part of a larger expression,
    there is an important difference. In this case, when the operator precedes its operand, the result
    of the operation is the value of the operand after the increment or decrement. If the operator
    follows its operand, the result of the operation is the value of the operand before the increment or
    decrement. Consider the following:
    x = 10;
    y = ++x;
    In this case, y will be set to 11. This is because x is first incremented and then its value is obtained.
    However, if the code is written as
    x = 10;
    y = x++;
    then y will be set to 10. In this case, the value of x is first obtained, x is incremented, and then
    the original value of x is returned. In both cases, x is still set to 11; the difference is what is
    returned by the operator.
    Here is a bit more complicated example:
    x = 10;
    y = 2;
    z = x++ - (x * y);

    ---------- Post added at 09:36 PM ---------- Previous post was at 09:35 PM ----------

    This gives z the value –12. The reason is that when x++ is evaluated, it sets x to 11, but yields
    the value 10 (x’s original value). This means that z is assigned 10 – (11 * 2), which is –12.
    However, written like this:
    z = ++x - (x * y);
    The result is –11. This is because the x is first incremented and then its value is obtained. Thus,
    z is assigned 11 – (11 * 2), which is –11. As this example hints at, there can be significant
    advantages in being able to control when the increment or decrement operation takes place.
    Relational and Logical Operators
    In the terms relational operator and logical operator, relational refers to the relationships that
    values can have with one another, and logical refers to the ways in which true and false values
    can be connected together. Since the relational operators produce true or false results, they
    often work with the logical operators. For this reason, they will be discussed together here.
    The relational operators are shown here:

    ---------- Post added at 09:37 PM ---------- Previous post was at 09:36 PM ----------

    Operator Meaning
    == Equal to
    != Not equal to
    > Greater than
    < Less than
    >= Greater than or equal to
    <= Less than or equal to
    The logical operators are shown next:
    Operator Meaning
    & AND
    | OR
    ^ XOR (exclusive OR)
    || Short-circuit OR
    && Short-circuit AND
    ! NOT
    The outcome of the relational and logical operators is a bool value.
    In general, objects can be compared for equality or inequality using == and !=. However,
    the comparison operators, <, >, <=, or >=, can be applied only to those types that support an
    ordering relationship. Therefore, all of the relational operators can be applied to all numeric
    types. However, values of type bool can only be compared for equality or inequality, since the
    true and false values are not ordered. For example, true > false has no meaning in C#.

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  7. #17 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    As the table shows, the outcome of an exclusive OR operation is true only when exactly one
    operand is true.
    Here is a program that demonstrates several of the relational and logical operators:
    // Demonstrate the relational and logical operators.
    using System;
    class RelLogOps {
    static void Main() {
    int i, j;
    bool b1, b2;
    i = 10;
    j = 11;
    if(i < j) Console.WriteLine("i < j");
    if(i <= j) Console.WriteLine("i <= j");
    if(i != j) Console.WriteLine("i != j");
    if(i == j) Console.WriteLine("this won't execute");
    if(i >= j) Console.WriteLine("this won't execute");
    if(i > j) Console.WriteLine("this won't execute");
    b1 = true;
    b2 = false;
    if(b1 & b2) Console.WriteLine("this won't execute");
    if(!(b1 & b2)) Console.WriteLine("!(b1 & b2) is true");
    if(b1 | b2) Console.WriteLine("b1 | b2 is true");
    if(b1 ^ b2) Console.WriteLine("b1 ^ b2 is true");
    }
    }
    The output from the program is shown here:
    i < j
    i <= j
    i != j
    !(b1 & b2) is true
    b1 | b2 is true
    b1 ^ b2 is true

    ---------- Post added at 09:39 PM ---------- Previous post was at 09:38 PM ----------

    Short-Circuit Logical Operators
    C# supplies special short-circuit versions of its AND and OR logical operators that can be
    used to produce more efficient code. To understand why, consider the following. In an AND
    operation, if the first operand is false, the outcome is false, no matter what value the second
    operand has. In an OR operation, if the first operand is true, the outcome of the operation is
    true, no matter what the value of the second operand. Thus, in these two cases, there is no need
    to evaluate the second operand. By not evaluating the second operand, time is saved and more
    efficient code is produced.
    The short-circuit AND operator is &&, and the short-circuit OR operator is ||. As described
    earlier, their normal counterparts are & and |. The only difference between the normal and
    short-circuit versions is that the normal operands will always evaluate each operand, but shortcircuit
    versions will evaluate the second operand only when necessary.
    Here is a program that demonstrates the short-circuit AND operator. The program
    determines if the value in d is a factor of n. It does this by performing a modulus operation.
    If the remainder of n / d is zero, then d is a factor. However, since the modulus operation
    involves a division, the short-circuit form of the AND is used to prevent a divide-by-zero error.
    // Demonstrate the short-circuit operators.
    using System;
    class SCops {
    static void Main() {
    int n, d;
    n = 10;
    d = 2;
    // Here, d is 2, so the modulus operation takes place.
    if(d != 0 && (n % d) == 0)
    Console.WriteLine(d + " is a factor of " + n);
    d = 0; // now, set d to zero

    ---------- Post added at 09:39 PM ---------- Previous post was at 09:39 PM ----------

    // Since d is zero, the second operand is not evaluated.
    if(d != 0 && (n % d) == 0)
    Console.WriteLine(d + " is a factor of " + n);
    // Now, try same thing without short-circuit operator.
    // This will cause a divide-by-zero error.
    if(d != 0 & (n % d) == 0)
    Console.WriteLine(d + " is a factor of " + n);
    }
    }
    To prevent a divide-by-zero error, the if statement first checks to see if d is equal to zero.
    If it is, the short-circuit AND stops at that point and does not perform the modulus division.

    ---------- Post added at 09:40 PM ---------- Previous post was at 09:39 PM ----------

    Thus, in the first test, d is 2 and the modulus operation is performed. Next, d is set to zero.
    This causes the second test to fail, and the modulus operation is skipped, avoiding a divideby-
    zero error. Finally, the normal AND operator is tried. This causes both operands to be
    evaluated, which leads to a runtime error when the division-by-zero occurs.
    One other point: The short-circuit AND is also known as the conditional AND, and the
    short-circuit OR is also called the conditional OR.
    Display a Truth Table for the Logical Operators
    Here you will create a program that displays the truth table for C#’s logical operators. This
    program makes use of several features covered in this chapter, including one of C#’s character
    escape sequences and the logical operators. It also illustrates the differences in the precedence
    between the arithmetic + operator and the logical operators.

    ---------- Post added at 09:41 PM ---------- Previous post was at 09:40 PM ----------

    Step by Step
    1. Create a new file called LogicalOpTable.cs.
    2. To ensure that the columns line up, use the \t escape sequence to embed tabs into each
    output string. For example, this WriteLine( ) statement displays the header for the table:
    Console.WriteLine("P\tQ\tAND\tOR\tXOR\tNOT");
    3. For each subsequent line in the table, use tabs to properly position the outcome of each
    operation under its proper heading.
    4. Here is the entire LogicalOpTable.cs program listing. Enter it at this time.
    // Print a truth table for the logical operators.
    using System;
    class LogicalOpTable {
    static void Main() {
    bool p, q;
    Console.WriteLine("P\tQ\tAND\tOR\tXOR\tNOT");
    p = true; q = true;
    Console.Write(p + "\t" + q +"\t");
    Console.Write((p&q) + "\t" + (p|q) + "\t");
    Console.WriteLine((p^q) + "\t" + (!p));
    p = true; q = false;
    Console.Write(p + "\t" + q +"\t");
    Console.Write((p&q) + "\t" + (p|q) + "\t");
    Console.WriteLine((p^q) + "\t" + (!p));
    p = false; q = true;
    Console.Write(p + "\t" + q +"\t");
    Console.Write((p&q) + "\t" + (p|q) + "\t");
    Console.WriteLine((p^q) + "\t" + (!p));
    p = false; q = false;
    Console.Write(p + "\t" + q +"\t");
    Console.Write((p&q) + "\t" + (p|q) + "\t");
    Console.WriteLine((p^q) + "\t" + (!p));
    }
    }

    ---------- Post added at 09:41 PM ---------- Previous post was at 09:41 PM ----------

    6. Notice the parentheses surrounding the logical operations inside the Write( ) and WriteLine( )
    statements. They are necessary because of the precedence of C#’s operators. The + operator
    is higher than the logical operators.
    7. On your own, try modifying the program so that it uses and displays 1’s and 0’s, rather than
    true and false.
    Q: Since the short-circuit operators are, in some cases, more efficient than their normal
    counterparts, why does C# still offer the normal AND and OR operators?
    A: In some cases, you will want both operands of an AND or OR operation to be evaluated
    because of the side effects produced. Consider the following:
    // Side effects can be important.
    using System;
    class SideEffects {
    static void Main() {
    int i;
    i = 0;
    // Here, i is incremented even though the if statement fails.

    ---------- Post added at 09:42 PM ---------- Previous post was at 09:41 PM ----------

    if(false & (++i < 100))
    Console.WriteLine("this won't be displayed");
    Console.WriteLine("if statement executed: " + i); // displays 1
    // In this case, i is not incremented because the short-circuit
    // operator skips the increment.
    if(false && (++i < 100))
    Console.WriteLine("this won't be displayed");
    Console.WriteLine("if statement executed: " + i); // still 1 !!
    }
    }
    As the comments indicate, in the first if statement, i is incremented whether the if
    succeeds or not. However, when the short-circuit operator is used, the variable i is not
    incremented when the first operand is false. The lesson here is that if your code expects the
    right-hand operand of an AND or OR operation to be evaluated, you must use the normal
    forms of these operations.

    ---------- Post added at 09:43 PM ---------- Previous post was at 09:42 PM ----------

    The Assignment Operator
    You have been using the assignment operator since Chapter 1. Now it is time to take a formal
    look at it. The assignment operator is the single equal sign, =. The assignment operator works
    in C# much as it does in other computer languages. It has this general form:
    var = expression;
    Here, the type of var must be compatible with the type of expression.
    The assignment operator does have one interesting attribute with which you may not be
    familiar: It allows you to create a chain of assignments. For example, consider this fragment:
    int x, y, z;
    x = y = z = 100; // set x, y, and z to 100
    This fragment sets the variables x, y, and z to 100 using a single statement. This works because
    the = is an operator that yields the assigned value. Thus, the value of z = 100 is 100, which is
    then assigned to y, which, in turn, is assigned to x. Using a “chain of assignment” is an easy
    way to set a group of variables to a common value.
    Compound Assignments
    C# provides special compound assignment operators that simplify the coding of certain
    assignment statements. Let’s begin with an example. The assignment statement shown here:
    x = x + 10;

    ---------- Post added at 09:44 PM ---------- Previous post was at 09:43 PM ----------

    can be written using a compound assignment, such as
    x += 10;
    The operator pair += tells the compiler to assign to x the value of x plus 10.
    Here is another example. The statement
    x = x - 100;
    is the same as
    x -= 100;
    Both statements assign to x the value of x minus 100.
    There are compound assignment operators for many of the binary operators (that is, those
    that require two operands). The general form of the shorthand is
    variable op = expression;
    Thus, the arithmetic and logical assignment operators are

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  8. #18 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    += –= *= /=
    %= &= |= ^=
    Because the compound assignment statements are shorter than their noncompound
    equivalents, the compound assignment operators are also sometimes called the shorthand
    assignment operators.
    The compound assignment operators provide two benefits. First, they are more compact
    than their “longhand” equivalents. Second, they can result in more efficient executable code
    (because the left-hand operand is evaluated only once). For these reasons, you will often see
    the compound assignment operators used in professionally written C# programs.
    Type Conversion in Assignments
    In programming, it is common to assign a value of one type to a variable of another type.
    For example, you might want to assign an int value to a float variable, as shown here:
    int i;
    float f;
    i = 10;
    f = i; // assign an int to a float
    When compatible types are mixed in an assignment, the value of the right side is automatically
    converted to the type of the left side. Thus, in the preceding fragment, the value in i is converted
    into a float and then assigned to f. However, because of C#’s strict type-checking, not all types
    are compatible, and thus, not all type conversions are implicitly allowed. For example, bool and
    int are not compatible.

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  9. #19 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    When one type of data is assigned to another type of variable, an implicit type conversion
    will take place automatically, if:
    ● The two types are compatible.
    ● The destination type is larger than the source type.
    When these two conditions are met, a widening conversion takes place. For example, the int
    type is always large enough to hold all valid byte values, and both int and byte are integer
    types, so an implicit conversion can be applied.
    For widening conversions, the numeric types, including integer and floating-point types,
    are compatible with each other. For example, the following program is perfectly valid, since
    long to double is a widening conversion that is automatically performed:
    // Demonstrate implicit conversion from long to double.
    using System;
    class LtoD {
    static void Main() {
    long L;
    double D;
    L = 100123285L;
    D = L;
    Console.WriteLine("L and D: " + L + " " + D);
    }
    }
    Although there is an implicit conversion from long to double, there is no implicit
    conversion from double to long, since this is not a widening conversion. Thus, the following
    version of the preceding program is invalid:
    // *** This program will not compile. ***
    using System;
    class LtoD {
    static void Main() {
    long L;
    double D;
    D = 100123285.0;
    L = D; // Illegal!!!
    Console.WriteLine("L and D: " + L + " " + D);
    }
    }
    In addition to the restrictions just described, there are no implicit conversions between
    decimal and float or double, or from the numeric types to char or bool. Also, char and bool
    are not compatible with each other.
    Casting Incompatible Types
    Although the implicit type conversions are helpful, they will not fulfill all programming needs
    because they apply only to widening conversions between compatible types. For all other
    cases, you must employ a cast. A cast is an instruction to the compiler to convert an expression
    into a specified type. Thus, it requests an explicit type conversion. A cast has this general form:
    (target-type) expression
    Here, target-type specifies the desired type to convert the specified expression to. For example,
    if you want the type of the expression x/y to be int, you can write
    double x, y;
    // ...
    (int) (x / y)
    Here, even though x and y are of type double, the cast converts the outcome of the expression
    to int. The parentheses surrounding x / y are necessary. Otherwise, the cast to int would apply
    only to the x, and not to the outcome of the division. The cast is necessary here because there
    is no implicit conversion from double to int.
    When a cast involves a narrowing conversion, information might be lost. For example,
    when casting a long into an int, information will be lost if the long’s value is greater than the
    range of an int because its high-order bits are removed. When a floating-point value is cast to
    an integer type, the fractional component will also be lost due to truncation. For example, if
    the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 is lost.
    The following program demonstrates some type conversions that require casts:
    // Demonstrate casting.
    using System;
    class CastDemo {
    static void Main() {
    double x, y;
    byte b;
    int i;
    char ch;
    x = 10.0;
    y = 3.0;
    i = (int) (x / y);
    Console.WriteLine("Integer outcome of x / y: " + i);
    i = 100;
    b = (byte) i;
    Console.WriteLine("Value of b: " + b);
    i = 257;
    b = (byte) i;
    Console.WriteLine("Value of b: " + b);
    b = 88; // ASCII code for X
    ch = (char) b;
    Console.WriteLine("ch: " + ch);
    }
    }
    The output from the program is shown here:
    Integer outcome of x / y: 3
    Value of b: 100
    Value of b: 1
    ch: X
    In the program, the cast of (x / y) to int results in the truncation of the fractional component
    and information is lost. Next, no loss of information occurs when b is assigned the value
    100 because a byte can hold the value 100. However, when the attempt is made to assign
    b the value 257, information loss occurs because 257 exceeds a byte’s range. This results
    in b having the value 1 because only the 1 bit is set in the low-order 8 bits of the binary
    representation of 257. Finally, no information is lost, but a cast is needed when assigning a
    byte value to a char.
    Operator Precedence
    Table 2-3 shows the order of precedence for all C# operators, from highest to lowest. This
    table includes several operators that will be discussed later in this book.
    Type Conversion in Expressions
    Within an expression, it is possible to mix two or more different types of data, as long as they
    are compatible with each other. For example, you can mix short and long within an expression
    because they are both numeric types. When different types of data are mixed within an
    expression, they are converted to the same type on an operation-by-operation basis.
    The conversions are accomplished through the use of C#’s type promotion rules. Here is
    the algorithm that the rules define for binary operations:
    IF one operand is decimal, THEN the other operand is promoted to decimal
    (unless it is of type float or double, in which case an error results).
    ELSE IF one of the operands is double, the second is promoted to double.
    Highest
    () [] . ++(postfix) --(postfix)
    checked new sizeof typeof unchecked
    ! ~ (cast) +(unary) -(unary) ++(prefix) --(prefix)
    * / %
    + -
    << >>
    < > <= >= is
    == !=
    &
    ^
    |
    &&
    ||
    ??
    ?:
    = op= =>
    ELSE IF one operand is a float operand, the second is promoted to float.
    ELSE IF one operand is a ulong, the second is promoted to ulong (unless it is
    of type sbyte, short, int, or long, in which case an error results).
    ELSE IF one operand is a long, the second is promoted to long.
    ELSE IF one operand is a uint and the second is of type sbyte, short, or int,
    both are promoted to long.
    ELSE IF one operand is a uint, the second is promoted to uint.
    ELSE both operands are promoted to int.
    There are a couple of important points to be made about the type promotion rules. First,
    not all types can be mixed in an expression. Specifically, there is no implicit conversion from
    float or double to decimal, and it is not possible to mix ulong with any signed integer type. To
    mix these types requires the use of an explicit cast.
    Second, *** special attention to the last rule. It states that if none of the preceding rules
    applies, then all other operands are promoted to int. Therefore, in an expression, all char,
    sbyte, byte, ushort, and short values are promoted to int for the purposes of calculation. This
    is called integer promotion. It also means that the outcome of all arithmetic operations will be
    no smaller than int.
    It is important to understand that type promotions apply to the values operated upon only
    when an expression is evaluated. For example, if the value of a byte variable is promoted to
    int inside an expression, outside the expression, the variable is still a byte. Type promotion
    only affects the evaluation of an expression.
    Type promotion can, however, lead to somewhat unexpected results. For example, when an
    arithmetic operation involves two byte values, the following sequence occurs: First, the byte
    operands are promoted to int. Then the operation takes place, yielding an int result. Thus, the
    outcome of an operation involving two byte values will be an int. This is not what you might
    intuitively expect. Consider the following program:
    // A type promotion surprise!
    using System;
    class PromDemo {
    static void Main() {
    byte b;
    int i;
    b = 10;
    i = b * b; // OK, no cast needed
    b = 10;
    b = (byte) (b * b); // cast needed!!
    Console.WriteLine("i and b: " + i + " " + b);
    }
    }
    Somewhat counterintuitively, no cast is needed when assigning b * b to i, because b is
    promoted to int when the expression is evaluated. Thus, the result type of b * b is int. However,
    when you try to assign b * b to b, you do need a cast—back to byte! Keep this in mind if you
    get unexpected type-incompatibility error messages on expressions that would otherwise seem
    perfectly okay.
    This same sort of situation also occurs when performing operations on chars. For example,
    in the following fragment, the cast back to char is needed because of the promotion of ch1 and
    ch2 to int within the expression:
    char ch1 = 'a', ch2 = 'b';
    ch1 = (char) (ch1 + ch2);
    Without the cast, the result of adding ch1 to ch2 would be int, which can’t be assigned to a char.
    Casts are not only useful when converting between types in an assignment. They can be
    used within an expression. For example, consider the following program. It uses a cast to
    double to obtain a fractional component from an otherwise integer division.
    // Using a cast.
    using System;
    class UseCast {
    static void Main() {
    int i;
    for(i = 1; i < 5; i++) {
    Console.WriteLine(i + " / 3: " + i / 3);
    Console.WriteLine(i + " / 3 with fractions: {0:#.##}",
    (double) i / 3);
    Console.WriteLine();
    }
    }
    }
    In the expression:
    (double) i / 3
    the cast to double causes i to be converted to double, which ensures that the fractional
    component of the division by 3 is preserved. The output from the program is shown here:
    1 / 3: 0
    1 / 3 with fractions: .33
    2 / 3: 0
    2 / 3 with fractions: .67
    3 / 3: 1
    3 / 3 with fractions: 1
    4 / 3: 1
    4 / 3 with fractions: 1.33
    Q: Do type promotions occur when a unary operation, such as the unary –, takes place?
    A: Yes. For the unary operations, operands smaller than int (byte, sbyte, short, and ushort)
    are promoted to int. Also, a char operand is converted to int. Furthermore, if a uint value
    is negated, it is promoted to long.

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


  10. #20 Collapse post
    zied toumi is offline
    Banned Array
    Join Date
    Oct 2013
    Posts
    78
    Accrued Payments
    6 USD
    Thanks
    0
    Thanked 1 Time in 1 Post
    Spacing and Parentheses
    An expression in C# can have tabs and spaces in it to make it more readable. For example, the
    following two expressions are the same, but the second is easier to read:
    x=10/y*(127-x);
    x = 10 / y * (127 - x);
    Parentheses can be used to group subexpressions, thereby effectively increasing the
    precedence of the operations contained within them, just like in algebra. Use of redundant
    or additional parentheses will not cause errors or slow down the execution of the expression.
    You are encouraged to use parentheses to make clear how an expression is evaluated, both for
    yourself and for others who may have to maintain your program later. For example, which of
    the following two expressions is easier to read?
    x = y/3-34*temp+127;
    x = (y/3) - (34*temp) + 127;

    ---------- Post added at 09:49 PM ---------- Previous post was at 09:48 PM ----------

    Compute the Regular ***ments on a Loan
    As mentioned earlier, the decimal type is especially well suited for calculations that involve
    money. This program demonstrates its use in this capacity. The program computes the regular
    ***ments on a loan, such as a car loan. Given the principal, the length of time, number of
    ***ments per year, and the interest rate, the program will compute the ***ment. Since this
    is a financial calculation, it makes sense to use the decimal type to represent the data. This
    program also demonstrates casting and another of C#’s library methods.
    To compute the ***ments, you will use the following formula:
    IntRate * (Principal / ***PerYear)
    ***ment =
    1 – ((IntRate / ***PerYear) + 1) – ***PerYear * NumYears
    where IntRate specifies the interest rate, Principal contains the starting balance, ***PerYear
    specifies the number of ***ments per year, and NumYears specifies the length of the loan in years.
    Notice that in the denominator of the formula, you must raise one value to the power of
    another. To do this, you will use the C# math method Math.Pow( ). Here is how you will
    call it:
    result = Math.Pow(base, exp);
    Pow( ) returns the value of base raised to the exp power. The arguments to Pow( ) must be of
    type double, and it returns a value of type double. This means that you will need to use a cast
    to convert between double and decimal.

    ---------- Post added at 09:49 PM ---------- Previous post was at 09:49 PM ----------

    Step by Step
    1. Create a new file called Reg***.cs.
    2. Here are the variables that will be used by the program:
    decimal Principal; // original principal
    decimal IntRate; // interest rate as a decimal, such as 0.075
    decimal ***PerYear; // number of ***ments per year
    decimal NumYears; // number of years
    decimal ***ment; // the regular ***ment
    decimal numer, denom; // temporary work variables
    double b, e; // base and exponent for call to Pow()

    ---------- Post added at 09:50 PM ---------- Previous post was at 09:49 PM ----------

    Since most of the calculation will be done using the decimal data type, most of the
    variables are of type decimal.
    Notice how each variable declaration is followed by a comment that describes its use. This
    helps anyone reading your program understand the purpose of each variable. Although we
    won’t include such detailed comments for most of the short programs in this book, it is a
    good practice to follow as your programs become longer and more complicated.

    ---------- Post added at 09:50 PM ---------- Previous post was at 09:50 PM ----------

    3. Add the following lines of code, which specify the loan information. In this case, the
    principal is $10,000, the interest rate is 7.5 percent, the number of ***ments per year is 12,
    and the length of the loan is 5 years.
    Principal = 10000.00m;
    IntRate = 0.075m;
    ***PerYear = 12.0m;
    NumYears = 5.0m;

    ---------- Post added at 09:51 PM ---------- Previous post was at 09:50 PM ----------

    4. Add the lines that perform the financial calculation:
    numer = IntRate * Principal / ***PerYear;
    e = (double) -(***PerYear * NumYears);
    b = (double) (IntRate / ***PerYear) + 1;
    denom = 1 - (decimal) Math.Pow(b, e);
    ***ment = numer / denom;
    Notice how casts must be used to pass values to Pow( ) and to convert the return value.
    Remember, there are no implicit conversions between decimal and double in C#.
    5. Finish the program by outputting the regular ***ment, as shown here:
    Console.WriteLine("***ment is {0:C}", ***ment);
    6. Here is the entire Reg***.cs program listing:
    // Compute the regular ***ments for a loan.

    ---------- Post added at 09:51 PM ---------- Previous post was at 09:51 PM ----------

    using System;
    class Reg*** {
    static void Main() {
    decimal Principal; // original principal
    decimal IntRate; // interest rate as a decimal, such as 0.075
    decimal ***PerYear; // number of ***ments per year
    decimal NumYears; // number of years
    decimal ***ment; // the regular ***ment
    decimal numer, denom; // temporary work variables
    double b, e; // base and exponent for call to Pow()
    Principal = 10000.00m;
    IntRate = 0.075m;
    ***PerYear = 12.0m;
    NumYears = 5.0m;
    numer = IntRate * Principal / ***PerYear;
    e = (double) -(***PerYear * NumYears);
    b = (double) (IntRate / ***PerYear) + 1;
    denom = 1 - (decimal) Math.Pow(b, e);
    ***ment = numer / denom;
    Console.WriteLine("***ment is {0:C}", ***ment);
    }
    }
    Here is the output from the program:
    ***ment is $200.38
    Before moving on, you migh

    ---------- Post added at 09:52 PM ---------- Previous post was at 09:51 PM ----------

    want to try having the program compute the regular
    ***ments for differing amounts, periods, and interest rates.
    Chapter 2 Self Test
    1. Why does C# strictly specify the range and behavior of its simple types?
    2. What is C#’s character type, and how does it differ from the character type used by some
    other programming languages?
    3. A bool value can have any value you like because any nonzero value is true. True or false?

    ---------- Post added at 09:52 PM ---------- Previous post was at 09:52 PM ----------

    4. Given this output:
    One
    Two
    Three
    Use a single string and escape sequences to show the WriteLine( ) statement that produced it.
    5. What is wrong with this fragment?
    for(i = 0; i < 10; i++) {
    int sum;
    sum = sum + i;
    }
    Console.WriteLine("Sum is: " + sum);
    6. Explain the difference between the prefix and postfix forms of the increment operator.
    7. Show how a short-circuit AND can be used to prevent a divide-by-zero error.
    8. In an expression, what type are byte and short promoted to?
    9. Which of the following types cannot be mixed in an expression with a decimal value?
    A. float
    B. int
    C. uint
    D. byte
    10. In general, when is a cast needed?
    11. Write a program that finds all of the prime numbers between 2 and 100.
    12. On your own, rewrite the truth table program in Try This: Display a Truth Table for the
    Logical Operators so that it uses verbatim string literals with embedded tab and newline
    characters rather escape sequences.

    ---------- Post added at 09:53 PM ---------- Previous post was at 09:52 PM ----------

    Chapter 3
    Program Control
    Statements


    ---------- Post added at 09:54 PM ---------- Previous post was at 09:53 PM ----------

    Key Skills & Concepts
    ● Input characters from the keyboard
    ● if and for
    ● switch
    ● while
    ● do-while
    ● break
    ● continue
    ● goto
    This chapter describes the statements that control a program’s flow of execution. There are
    three categories of program control statements: selection statements, which include if and
    switch; iteration statements, which include the for, while, do-while, and foreach loops; and
    jump statements, which include break, continue, goto, return, and throw. Except for return,
    foreach, and throw, which are discussed later in this book, the remaining control statements
    are examined in detail here.

    ---------- Post added at 09:55 PM ---------- Previous post was at 09:54 PM ----------

    Inputting Characters from the Keyboard
    Before examining C#’s control statements, we will make a short digression that will allow you
    to begin writing interactive programs. Up to this point, the sample programs in this book have
    displayed information to the user, but they have not received information from the user. Thus,
    you have been using console output, but not console (that is, keyboard) input. Here, you will
    begin to use input by reading characters that are typed at the keyboard.
    To read a character from the keyboard, call Console.Read( ). This method waits until the
    user presses a key and then returns the key. The character is returned as an integer, so it must
    be cast to char to assign it to a char variable. By default, console input is line-buffered, so you
    must press ENTER before any character that you type will be sent to your program. Here is a
    program that reads a character from the keyboard:
    // Read a character from the keyboard.
    using System;
    class KbIn {
    static void Main() {
    char ch;

    Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.


+ Reply to Thread
Page 2 of 7 1 2 3 4 ...

Subscribe to this Thread (2)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Threads

Posts

Members