1 / 48

C# Control Statements part 1

C# Control Statements part 1. 5.5 if Single-Selection Statement. 5.6 if…else Double-Selection Statement. String.Format. DateTime dat = new DateTime (2012, 1, 17, 9, 30, 0); string city = "Chicago"; int temp = -16;

levia
Download Presentation

C# Control Statements part 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C# Control Statements part 1

  2. 5.5 if Single-Selection Statement

  3. 5.6 if…else Double-Selection Statement

  4. String.Format DateTimedat = newDateTime(2012, 1, 17, 9, 30, 0); string city = "Chicago"; int temp = -16; string output = String.Format("At {0} in {1}, the temperature was {2} degrees.", dat, city, temp); Console.WriteLine(output); // The example displays the following output: // At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.

  5. ==vs= == (test equality) - results true or false =(assignment)

  6. if else if(condition1) { One line does no need {} but use them anyway } else if(condition2) { } else { }

  7. Primitives (again)

  8. operators shortcut

  9. Comparison operators

  10. Logical Operators

  11. Increment/Decrement operators Prefix and Postfix Operators

  12. Type testing (more later)

  13. Ternary operator

  14. Operator Precedence

  15. Constants

  16. Enumerations* (more later) By default inttype, can be changed

  17. Loops later

  18. 5.7 while Repetition Statement

  19. 5.8 Formulating Algorithms: Counter-Controlled Repetition

  20. Auto-Implemented Properties • In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. • They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property‘ • No need for getX and setX

  21. // This class is mutable. Its data can be modified from outside the class. classCustomer { // Auto-Impl Properties for trivial get and set public double TotalPurchases { get; set; } public string Name { get; set; } public intCustomerID { get; set; } // Constructor publicCustomer(double purchases, string name, int ID) { TotalPurchases = purchases; Name = name; CustomerID = ID; } // Methods public string GetContactInfo() {return "ContactInfo";} public string GetTransactionHistory() {return "History";} // .. Additional methods, events, etc. } classProgram { staticvoidMain() { // Intialize a new object. Customer cust1 = new Customer ( 4987.63, "Northwind",90108 ); //Modify a property cust1.TotalPurchases += 499.99; } }

  22. Local variables

  23. 5.9 Formulating Algorithms: Sentinel-Controlled Repetition 3 phases

  24. // determine the average of an arbitrary number of grades publicvoidDetermineClassAverage() { int total; // sum of grades intgradeCounter; // number of grades entered int grade; // grade value double average; // number with decimal point for average // initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter // processing phase // prompt for and read a grade from the user Console.Write( "Enter grade or -1 to quit: " ); grade = Convert.ToInt32( Console.ReadLine() ); // loop until sentinel value is read from the user while ( grade != -1 ) { total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter // prompt for and read the next grade from the user Console.Write( "Enter grade or -1 to quit: " ); grade = Convert.ToInt32( Console.ReadLine() ); } // end while // termination phase // if the user entered at least one grade... if ( gradeCounter != 0 ) { // calculate the average of all the grades entered average = ( double ) total / gradeCounter; // display the total and average (with two digits of precision) Console.WriteLine( "\nTotal of the {0} grades entered is {1}", gradeCounter, total ); Console.WriteLine( "Class average is {0:F}", average ); } // end if else// no grades were entered, so output error message Console.WriteLine( "No grades were entered" ); } // end method DetermineClassAverage } Avoid infinite loop!

  25. 5.9  Formulating Algorithms: Sentinel-Controlled Repetition (Cont..) Explicitly and Implicitly Converting Between Simple Types To perform a floating-point calculation with integer values, we temporarily treat these values as floating-point numbers. A unary cast operator such as (double) performs explicit conversion. C# performs an operation called promotion (or implicit conversion) on selected operands for use in the expression.

  26. 5.9  Formulating Algorithms: Sentinel-Controlled Repetition (Cont..) The cast operator is formed by placing parentheses around the name of a type. This operator is a unary operator (i.e., an operator that takes only one operand). Cast operators associate from right to left and have the same precedence as other unary operators, such as unary + and unary -. This precedence is one level higher than that of the multiplicative operators *, / and %. In this app, the three grades entered during the sample execution of class GradeBookTest(Fig. 5.10) total 263, which yields the average 87.66666…. The format item rounds the average to the hundredths position, and the average is displayed as 87.67.

  27. 5.10 Formulating Algorithms: Nested Control Statements

  28. Notes Type Conversion • C# statically types at compile time. After variable declaration the type is set • Conversion: • Implicit (when it is safe) • From smaller to larger (intto double) • From derived to base class • Explicit (cast) • Variables compatible, but risk of precision loss (smaller to larger) • Using helpers (between non-compatible types) • System.BitConverter • System.Convert • Int32.Parse • The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse. So the only difference is that if a null string is passed to Convert it returns 0, whereas Int32.Parse throws an ArgumentNullException. MSDN

  29. 5.11 Compound Assignment Operators

  30. 5.12 Increment and Decrement Operators

  31. // Fig. 5.16: Increment.cs // Prefix increment and postfix increment operators. using System; publicclassIncrement { publicstaticvoid Main( string[] args ) { int c; // demonstrate postfix increment operator c = 5; // assign 5 to c Console.WriteLine( c ); // display 5 Console.WriteLine( c++ ); // display 5 again, then increment Console.WriteLine( c ); // display 6 Console.WriteLine(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c Console.WriteLine( c ); // display 5 Console.WriteLine( ++c ); // increment then display 6 Console.WriteLine( c ); // display 6 again } // end Main • }

  32. 5.13  Simple Types (and again) • The table in Appendix B, Simple Types, lists the 13 simple types in C#. • C# requires all variables to have a type. • Instance variables of types char, byte, sbyte, short, ushort, int, uint, long, ulong, float, double, and decimal are all given the value 0 by default. • Instance variables of type bool are given the value false by default.

More Related