Search This Blog

Monday, January 10, 2011

C# part 2

Lesson 2: Operators, Types, and Variables
Objectives:
·                      Understand what a variable is.
·                      Familiarization with C# built-in types.
·                      Get an introduction to C# operators.
·                      Learn how to use Arrays.

Problem statement:
1.     Calculate y, as a result of a given arithmetic equation.
2.     Calculate z, as a result of a given logical equation.
3.     Calculate s, as a result of a given string expression (text message).

Variants
Вариант  1
1) Y=;      
2) Z=       
Variant №  2
1) Y=           
2) Z=      
Variant №  3
1) Y=  
2) Z=          
Variant №  4
1) Y= 
2) Z=       
Variant №  5
1) Y=      
2) Z= 
Variant  6
1) Y=; 
2) Z=   
Variant №  7
1) Y=  
2) Z=         
Variant №  8
1) Y=
2) Z=;       
Variant №  9
1) Y=        
2) Z=       
Variant №  10
1) Y=;           
2) Z=;
Variant  11
1) Y=;           
2) Z=   
Variant №  12
1) Y=;      
2) Z=     
Variant №  13
1) Y=;    
2) Z=
Variant №  14 
1) Y=;   
2) Z=
Variant №  15 
1) Y=;          
2) Z=
Variant  16
1) Y=;     
2) Z=
Variant №  17
1) Y=;           
2) Z=
Variant №  18
1) Y=        
2) Z=
Variant №  19
1) Y=;      
2) Z=
Variant №  20
1) Y= 
2) Z=
Variant  21
1) Y=;         
2) Z=
Variant №  22
1) Y=        
2) Z=
Variant №  23 
1) Y=    
2) Z=;
Variant №  24
1) Y=
2) Z=
Variant №  25
1) Y=;     
2) Z=;
Variant  26
1) Y=;     
2) Z=
Variant №  27
1) Y=;     
2) Z=           
Variant №  28
1) Y=;         
2) Z=    
Variant №  29
1) Y=;    
2) Z=           
Variant №  30
1) Y=;           
2) Z=;           


Example
1.     Calculate value of  the next expression:  
if
2.     Calculate  if , where  logic operator  NOT, - logic multiplication AND,  - logic addition OR.
3.     Print out author’s full name, if first name –Ivan, and surname - Petrov.
STEP1
STEP2
STEP3
STEP4
using System;
using System.Collections.Generic;
using System.Text;

namespace Ivanov2
{
    class Program
    {
        static void Main()
        {
            double
                y,  
                x=3.5, 
                z=1e-5,
                Denominator,  Numerator, 
                X = 6.3,    Y=5.1;          
            int
                b=-4; 
            string FullName = "";  
            string FirstName = "Petr";  
            string Surname = "Ivanov";  
            bool
                Z,             
                A = true, 
                B = false;
            int
                iFirstName
                iSurname, iFullName; 

            Console.WriteLine(" ***** Initial data*****:\n");
            Console.WriteLine(" x={0} z={1} b={2}", x, z, b);
            Console.WriteLine(" X={0} Y={1}", X, Y);
            Console.WriteLine(" A={0} B={1}", A, B);
            Console.WriteLine(" Name={0}", FirstName);
            Console.WriteLine(" Surname={0}", Surname);
            
Numerator=Math.Atan(z)*Math.Pow(z,1/3.0)*Math.PI/Math.Exp(x)+
Math.Pow(z,2)-4.5*Math.Pow(10.0,2.5)*Math.Sqrt(x)*Math.Asin(z);

Denominator = Math.Tan(2.7e-3) - Math.Acos(z) * Math.Log(x) + 
Math.Pow(z, x) + Math.Abs(Math.Sin((double)b)) - Math.Log10(z);

            y = Numerator / Denominator;
        
            Z=!A && (X<=Y) || (X>0) && B;

            iFirstName = FirstName.Length;
            iSurname=Surname.Length;
            FullName = FirstName + " " + Surname;
            iFullName = FullName.Length;

            Console.WriteLine("\n ***** Results *****:\n");
            Console.WriteLine(" Arithmetic equation: y={0}", y);
            Console.WriteLine(" Logical equation: Z={0}", Z);             Console.WriteLine(" String type: FullName={0}", FullName);
  Console.WriteLine(" Number of  letters in the full name={0}", iFullName);
    Console.WriteLine("Number of  letters in the name ={0}", iFirstName);
       Console.WriteLine("Number of  letters in the surname={0}", iSurname);
        }
    }
}
STEP5

Theoretical introduction
Variables and Types
"Variables" are simply storage locations for data. You can place data into them and retrieve their contents as part of a C# expression. The interpretation of the data in a variable is controlled through "Types".
C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.
The C# simple types consist of the Boolean type and three numeric types - Integrals, Floating Point, Decimal, and String. The term "Integrals", which is defined in the C# Programming Language Specification, refers to the classification of types that include sbyte, byte, short, ushort, int, uint, long, ulong, and char. More details are available in the Integral Types section later in this lesson. The term "Floating Point" refers to the float and double types, which are discussed, along with the decimal type, in more detail in the Floating Point and Decimal Types section later in this lesson. The string type represents a string of characters and is discussed in The String Type section, later in this lesson. The next section introduces the boolean type.
The Boolean Type
Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means true. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords. Listing 2-1 shows one of many ways that boolean types can be used in a program.
Listing 2-1. Displaying Boolean Values: Boolean.cs
using System;
class
Booleans
{
    public static void Main()
    {
        bool content = true;
        bool noContent = false;
        Console.WriteLine("It is {0} that C# Station provides C# programming language content.", content);
        Console.WriteLine("The statement above is not {0}.", noContent);
    }
}
In Listing 2-1, the boolean values are written to the console as a part of a sentence. The only legal values for the bool type are either true or false, as shown by the assignment of true to content and false to noContent. When run, this program produces the following output:
    It is True that C# Station provides C# programming language content.
   The statement above is not False.
Integral Types
In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. For more information, visit The Unicode Home Page. table 2-1 shows the integral types, their size, and range.
Table 2-1. The Size and Range of C# Integral Types
Type
Size (in bits)
Range
sbyte
8
-128 to 127
byte
8
0 to 255
short
16
-32768 to 32767
ushort
16
0 to 65535
int
32
-2147483648 to 2147483647
uint
32
0 to 4294967295
long
64
-9223372036854775808 to 9223372036854775807
ulong
64
0 to 18446744073709551615
char
16
0 to 65535
Integral types are well suited for those operations involving whole number calculations. The char type is the exception, representing a single Unicode character. As you can see from the table above, you have a wide range of options to choose from, depending on your requirements.
Floating Point and Decimal Types
A C# floating point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values. table 2-2 shows the floating point and decimal types, their size, precision, and range.
Table 2-2. The Floating Point and Decimal Types with Size, precision, and Range
Type
Size (in bits)
precision
Range
float
32
7 digits
1.5 x 10-45 to 3.4 x 1038
double
64
15-16 digits
5.0 x 10-324 to 1.7 x 10308
decimal
128
28-29 decimal places
1.0 x 10-28 to 7.9 x 1028
Floating point types are used when you need to perform operations requiring fractional representations. However, for financial calculations, the decimal type is the best choice because you can avoid rounding errors.
The string Type
A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1, where we used the Console.WriteLine method to send output to the console.
Some characters aren't printable, but you still need to use them in strings. Therefore, C# has a special syntax where characters can be escaped to represent non-printable characters. For example, it is common to use newlines in text, which is represented by the '\n' char. The backslash, '\', represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as an alphabetical character, but now represents a newline.
You may be now wondering how you could represent a backslash character in your code. We have to escape that too by typing two backslashes, as in '\\'. table 2-3 shows a list of common escape sequences.
Table 2-3. C# Character Escape Sequences
Escape Sequence
Meaning
\'
Single Quote
\"
Double Quote
\\
Backslash
\0
Null, not the same as the C# null value
\a
Bell
\b
Backspace
\f
form Feed
\n
Newline
\r
Carriage Return
\t
Horizontal Tab
\v
Vertical Tab
Another useful feature of C# strings is the verbatim literal, which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe".
That is fine, but now you have the problem where quoting text is not as easy. In that case, you would specify double double quotes. For example, the string "copy \"c:\\source file name with spaces.txt\" c:\\newfilename.txt" would be written as the verbatim literal @"copy ""c:\source file name with spaces.txt"" c:\newfilename.txt".
C# Operators
Results are computed by building expressions.  These expressions are built by combining variables and operators together into statements.  The following table describes the allowable operators, their precedence, and associativity.
Table 2-4. Operators with their precedence and Associativity
Category (by precedence)
Operator(s)
Associativity
Primary
x.y  f(x)  a[x]  x++  x--  new  typeof  default  checked  unchecked delegate
left
Unary
+  -  !  ~  ++x  --x  (T)x
left
not
  !

Multiplicative
*  /  %
left
Additive
+  -
left
Shift
<<  >>
left
Relational
<  >  <=  >=  is as
left
Equality
==  !=
right
Logical AND
&
left
Logical XOR
^
left
Logical OR
|
left
Conditional AND
&&
left
Conditional OR
||
left
Null Coalescing
??
left
Ternary
?:
right
Assignment
=  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=  =>
right
Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left, such as assignment operators where everything to the right is evaluated before the result is placed into the variable on the left.
Most operators are either unary or binary. Unary operators form expressions on a single variable, but binary operators form expressions with two variables. Listing 2-2 demonstrates how unary operators are used.
Listing 2-2. Unary Operators: Unary.cs
using System;

class Unary
{
    public static void Main()
    {
        int unary = 0;
        int preIncrement;
        int preDecrement;
        int postIncrement;
        int postDecrement;
        int positive;
        int negative;
        sbyte bitNot;
        bool logNot;

        preIncrement = ++unary;
        Console.WriteLine("pre-Increment: {0}", preIncrement);

        preDecrement = --unary;
        Console.WriteLine("pre-Decrement: {0}", preDecrement);

        postDecrement = unary--;
        Console.WriteLine("Post-Decrement: {0}", postDecrement);

        postIncrement = unary++;
        Console.WriteLine("Post-Increment: {0}", postIncrement);

        Console.WriteLine("Final Value of Unary: {0}", unary);

        positive = -postIncrement;
        Console.WriteLine("Positive: {0}", positive);

        negative = +postIncrement;
        Console.WriteLine("Negative: {0}", negative);

        bitNot = 0;
        bitNot = (sbyte)(~bitNot);
        Console.WriteLine("Bitwise Not: {0}", bitNot);

        logNot = false;
        logNot = !logNot;
        Console.WriteLine("Logical Not: {0}", logNot);
    }
}
When evaluating expressions, post-increment (x++) and post-decrement (x--) operators return their current value and then apply the operators. However, when using pre-increment (++x) and pre-decrement (--x) operators, the operator is applied to the variable prior to returning the final value.
In Listing 2-2, the unary variable is initialized to zero. When the pre-increment (++x) operator is used, unary is incremented to 1 and the value 1 is assigned to the preIncrement variable. The pre-decrement (--x) operator turns unary back to a 0 and then assigns the value to the preDecrement variable.
When the post-decrement (x--) operator is used, the value of unary, 0, is placed into the postDecrement variable and then unary is decremented to -1. Next the post-increment (x++) operator moves the current value of unary, -1, to the postIncrement variable and then increments unary to 0.
The variable bitNot is initialized to 0 and the bitwise not (~) operator is applied. The bitwise not (~) operator flips the bits in the variable. In this case, the binary representation of 0, "00000000", was transformed into -1, "11111111".
While the (~) operator works by flipping bits, the logical negation operator (!) is a logical operator that works on bool values, changing true to false or false to true. In the case of the logNot variable in Listing 2-2, the value is initialized to false, and the next line applies the logical negation operator, (!), which returns true and reassigns the new value, true, to logNot. Essentially, it is toggling the value of the bool variable, logNot.
The setting of positive is a little tricky. At the time that it is set, the postIncrement variable is equal to -1. Applying the minus (-) operator to a negative number results in a positive number, meaning that postitive will equal 1, instead of -1. The minus operator (-), which is not the same as the pre-decrement operator (--), doesn't change the value of postInc - it just applies a sign negation. The plus operator (+) doesn't affect the value of a number, assigning negative with the same value as postIncrement, -1.
Notice the expression (sbyte)(~bitNot). Any operation performed on types sbyte, byte, short, or ushort return int values. To assign the result into the bitNot variable we had to use a cast, (Type), operator, where Type is the type you wish to convert to (in this case - sbyte). The cast operator is shown as the Unary operator, (T)x, in table 2-4. Cast operators must be performed explicity when you go from a larger type to a smaller type because of the potential for lost data. Generally speaking, assigning a smaller type to a larger type is no problem, since the larger type has room to hold the entire value. Also be aware of the dangers of casting between signed and unsigned types. You want to be sure to preserve the integrity of your data. Many basic programming texts contain good descriptions of bit representations of variables and the dangers of explicit casting.
Here's the output from the Listing 2-2:
     pre-Increment: 1
    pre-Decrement 0
    Post-Decrement: 0
    Post-Increment: -1
    Final Value of Unary: 0
    Positive: 1
    Negative: -1
    Bitwise Not: -1
    Logical Not: true


Methods of the Math class
To perform the basic algebraic and geometric operations in C#, you can use methods of the Math class of the .NET Framework. As seen in the previous lesson, you can also take advantage of Visual Basic's very powerful library of functions. This library is one of the most extended set of functions of various area of business mathematics.
Here are examples of different ways to declare a variable of a numeric type.:
using System;
 
class Program
{
    static int Main()
    {
        short   sNumber;
        int     iNumber;
        double  dNumber;
        decimal mNumber;
 
        return 0;
    }
}
The Sign of a Number
One of the primary rules to observe in C# is that, after declaring a variable, before using it, it must have been initialized. Here are examples of initializing variables:
using System;
 
class Program
{
    static int Main()
    {
        short   sNumber = 225;
        int     iNumber = -847779;
        double  dNumber = 9710.275D;
        decimal mNumber = 35292742.884295M;
 
Console.WriteLine("Short Integer:      {0}", sNumber);
Console.WriteLine("Integral Number:    {0}", iNumber);
Console.WriteLine("Double-Precision:   {0}", dNumber);
Console.WriteLine("Extended Precision: {0}", mNumber);
      
return 0;
    }
}
This would produce:
Short Integer:      225
Integral Number:    -847779
Double-Precision:   9710.275
Extended Precision: 35292742.884295
Press any key to continue . . .
When initializing a variable using a constant, you decide whether it is negative, 0 or positive. This is referred to as its sign. If you are getting the value of a variable some other way, you may not know its sign. Although you can use comparison operators to find this out, the Math class provides a method to check it out for you.
To find out about the sign of a value or a numeric variable, you can call the Math.Sign() method. It is overloaded in various versions whose syntaxes are:
public static int Sign(int     value);
public static int Sign(double  value);

The Integral Side of a Floating-Point Number
As reviewed in Lesson 1, when dealing with a floating-point number, it consists of an integral side and a precision side; both are separated by a symbol which, in US English, is the period. In some operations, you may want to get the integral side of the value. The Math class can assist you with this.
To get the integral part of a decimal number, the Math class can assist you with the Trancate() method, which is overloaded in two versions whose syntaxes are:
public static double Truncate(double d);
public static double Truncate(double d);
When calling this method, pass it a number or a variable of float, double, or decimal type. The method returns the int side of the value. Here is an example of calling it:
using System;
 
class Program
{
    static int Main()
    {
        float number = 225.75f;
 
 Console.WriteLine("The integral part of {0} is {1}\n",
number, Math.Truncate(number));
        return 0;
    }
}
This would produce:
The integral part of 225.75 is 225
 
Press any key to continue . . .

Math.Min(number1, number2)         The Minimum of Two Values
If you have two numbers, you can find the minimum of both without writing your own code. To assist you with this, the Math class is equipped with a method named Min. This method is overloaded in various versions with each version adapted to each integral or floating-point data type. The syntaxes are:
public static int     Min(int     val1, int     val2);
public static float   Min(float   val1, float   val2);
public static double  Min(double  val1, double  val2);

Math.Max(number1, number2)       The Maximum Integer Value of a Series
As opposed to the minimum of two numbers, you may be interested in the higher of both. To help you find the maximum of two numbers, you can call the Max() method of the Math class. It is overloaded in various versions with one of each type of numeric data. The syntaxes of this method are:
public static int     Max(int     val1, int     val2);
public static float   Max(float   val1, float   val2);
public static double  Max(double  val1, double  val2);

Arithmetic
Math.Abs(number)       Absolute Values
The decimal numeric system counts from negative infinity to positive infinity. This means that numbers are usually negative or positive, depending on their position from 0, which is considered as neutral. In some operations, the number considered will need to be only positive even if it is provided in a negative format. The absolute value of a number x is x if the number is (already) positive. If the number is negative, its absolute value is its positive equivalent. For example, the absolute value of 12 is 12, while the absolute value of –12 is 12.
To get the absolute value of a number, the Math class is equipped with a method named Abs, which is overloaded in various versions. Their syntaxes are:
public static int     Abs(int     value);
public static float   Abs(float   value);
public static double  Abs(double  value);

Math.Pow(source, exp);       The Power of a Number
The power is the value of one number or expression raised to another number. This follows the formula:
ReturnValue = xy
To support this operation, the Math class is equipped with a method named Pow whose syntax is
public static double Pow(double x, double y);
This method takes two arguments. The first argument, x, is used as the base number to be evaluated. The second argument, y, also called the exponent, will raise x to this value. 

Math.Exp(709.78222656)        The Exponential
You can calculate the exponential value of a number. To support this, the Math class provides the Exp() method. Its syntax is:
public static double Exp (double d);

Math.Log()       The Natural Logarithm
To calculate the natural logarithm of a number, you can call the Math.Log() method. It is provides in two versions. The syntax of one is:
public static double Log(double d);

Math.Log10()      The Base 10 Logarithm
The Math.Log10() method calculates the base 10 logarithm of a number. The syntax of this method is:
public static double Log10(double d);
The number to be evaluated is passed as the argument. The method returns the logarithm on base 10 using the formula:
y = log10x
which is equivalent to
x = 10y

Math.Log()       The Logarithm of Any Base
The Math.Log() method provides another version whose syntax is:
public static double Log(double a, double newBase);
The variable whose logarithmic value will be calculated is passed as the first argument to the method. The second argument allows you to specify a base of your choice. The method uses the formula:
Y = logNewBasex
This is the same as
x = NewBasey

Sqrt(number)       The Square Root
You can calculate the square root of a decimal positive number. To support this, the Math class is equipped with a method named Sqrt whose syntax is:
public static double Sqrt(double d);
This method takes one argument as a positive floating-point number. After the calculation, the method returns the square root of x.
Math.Cos() method
To calculate the cosine of an angle, the Math class provides the Cos() method. Its syntax is:
public static double Cos(double d);

The Sine of a Value        Math.Sin(number)
To c   alculate the sine of a value, you can call the Sin() method of the Math class. Its syntax is:
public static double Sin(double a);

Tangents      Math.Tan(number)
To assist you with calculating the tangent of of a number, the Math class is equipped with a method named Tan whose syntax is:
public static double Tan(double a);

The Arc Tangent      Math.Atan()
To calculate the arc tangent of a value, you can use the Math.Atan() method. Its syntax is
public static double Atan(double d);



No comments:

Post a Comment