C# Control Statements part 1 (Based on Deitel Book)

Slides:



Advertisements
Similar presentations
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
Advertisements

 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Introduction to Computers and Programming Lecture 7:
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
1 CSCE 1030 Computer Science 1 Control Statements in Java.
Chapter 2: Using Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved. 1.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures.
Performing Simple Calculations with C# Telerik Corporation
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Computers and Programming Lecture 7:
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline Counter-Controlled Repetition: Example Sentinel-Controlled Repetition:
A DVANCED P ROGRAMMING C HAPTER 5 & 6: C ONTROL S TRUCTURES Dr Shahriar Bijani Spring 2016.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 3 Structured Program Development in C Part II C How to Program, 8/e, GE © 2016 Pearson Education, Ltd. All rights reserved.1.
CompSci 230 S Programming Techniques
Control Statements: Part 1
Lecture 3 Java Operators.
Yanal Alahmad Java Workshop Yanal Alahmad
Control Statements: Part 1
Computing with C# and the .NET Framework
Chapter 4 – Control Structures Part 1
Chapter 4- part 2 Control Statements: Loops 1
Dr Shahriar Bijani Winter 2017
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I UTPA – Fall 2012 This set of slides is revised from lecture slides.
Advanced Programming Chapters 5 & 6: Control Structures
Chapter 4 Control Statements: Loops 1
3-4-5 Introduction.
CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 This set of slides is revised from lecture.
Chapter 6 Control Statements: Part 2
Structured Program Development in C
Classes, Objects, Methods and Strings
Data Types Imran Rashid CTO at ManiWeber Technologies.
Chapter 4 - Control Structures: Part 1
Visual Programming COMP-315
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Problem 1 Given n, calculate 2n
Control Statements:.
Presentation transcript:

C# Control Statements part 1 (Based on Deitel Book)

Reading User Input For example

Code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class Program static void Main(string[] args) Console.WriteLine("Please enter something and press Enter"); string userInputValue; userInputValue = Console.ReadLine(); //Reading User input Console.WriteLine("You entered {0}", userInputValue); Console.ReadLine(); //WAITING }

If, else if, if static void Main(string[] args) { Console.WriteLine("Please 1 or 2"); string userInputValue; userInputValue = Console.ReadLine(); //READING USER INPUT if (userInputValue == "1") Console.WriteLine("You entered ONE"); } else if (userInputValue == "2") Console.WriteLine("You entered TWO"); else Console.WriteLine("You entered SOMETHING ELSE {1} “, userInputValue ); Console.ReadLine(); //WAITING

Refactoring using message static void Main(string[] args) { Console.WriteLine("Please 1 or 2"); string userInputValue = Console.ReadLine(); //READING USER INPUT in one line string message; if (userInputValue == "1") message = "You entered ONE"; } else if (userInputValue == "2") message = "You entered TWO"; else message = "You entered SOMETHING ELSE"; Console.WriteLine(message); Console.ReadLine(); //WAITING No {} Only if it is 1 line of code, but not recommended. USE { }

5.5 if Single-Selection Statement

5.6 if…else Double-Selection Statement

if(x>0);

== vs = == (test equality) - results true or false if(x == 0) { //do something } = (assignment) X = 0;

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

Statement: operators and operands

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

C# Primitives (again) C# Primitives Type Primitive Usage Range bool System.Boolean boolean true, false byte System.Byte 8 bit integer 0 - 255 char System.Char 16 bit Unicode character /u0000 - /uffff decimal System.Decimal 128 bit decimal +/-1.0x10-28 to +/-7.9x10+28 precision of 28- 29 digits double System.Double 64 bit floating point -1.79769313486232e308 to 1.79769313486232e308 float System.Single 32 bit floating point +/-1.5x10-45 to +/-3.4x10+38 precision of 7 digits int System.Int32 32 bit integer -2,147,483,648 to 2,147,483,647 long System.Int64 64 bit integer -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 sbyte System.SByte -128 to 127 short System.Int16 16 bit integer -32,768 to 32,767 string System.String - immutable, specified length uint System.UInt32 32 bit unsigned integer 0 to 4,294,967,295 ulong System.UInt64 64 bit unsigned integer 0 to 18,446,744,073,709,551,615 ushort System.UInt16 16 bit unsigned integer 0 to 65,535

operators shortcut

Comparison operators (return true or false) Greater Less Greater OR equal Less OR equal

Logical Operators

Increment/Decrement operators Prefix and Postfix Operators

Type testing (more later)

Ternary operator ?: Another way

Ternary operator example w/ user input (Decisions) string message = (userInputValue == “1”)? “You entered ONE”:”You entered SOMETHING ELSE”;

Operator Precedence means AND means OR

Constants

Enumerations* (more later) By default int type, can be changed

Loops Executes at least once later

5.7 while Repetition Statement

5.8 Formulating Algorithms: Counter-Controlled Repetition (remember?)

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, the compiler creates a private, anonymous backing field that can only be accessed through the property No need for getX and setX like it is in Java

// This class is mutable // This class is mutable. Its data can be modified from outside the class. class Customer { // Auto-Implementated Properties for trivial get and set public double TotalPurchases { get; set; } public string Name { get; set; } public int CustomerID { get; set; } // Constructor public Customer(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. class Program static void Main() {// Intialize a new object. Customer cust1 = new Customer(4987.63, "Northwind", 90108); Console.WriteLine("TORAL PURCHASES AFTER INIT {0} ",cust1.TotalPurchases); cust1.TotalPurchases += 499.99; //Modify a property Console.WriteLine("TORAL PURCHASES UPDATED {0} ", cust1.TotalPurchases); Console.ReadKey();

Local variables

class Rounding { static void Main() int x = 7; int y = 4; Console.WriteLine("x/y = {0} ", x / y); //1 Console.ReadKey(); }

Sentinel value In computer programming, a sentinel value  (also referred to as a flag value, trip value, rogue value, signal value, or dummy data) is a special value in the context of an algorithm which uses its presence as a condition of termination, typically in a loop or recursive algorithm.

5.9 Formulating Algorithms: Sentinel-Controlled Repetition Three phases:

Avoid infinite loop! Avoid division by 0 // determine the average of an arbitrary number of grades public void DetermineClassAverage() { int total; // sum of grades int gradeCounter; // 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 } // 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! Avoid division by 0

5.9 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.

55.9 Explicitly and Implicitly Converting Between Simple Types (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 %.

5.9 Explicitly and Implicitly Converting Between Simple Types (cont.) In GradeBook 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. Console.WriteLine( "\nTotal of the {0} grades entered is {1}", gradeCounter, total ); Console.WriteLine( "Class average is {0:F}", average );

Standard Numeric Format Strings https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx 1234.567 ("F", en-US) -> 1234.57 1234.567 ("F", de-DE) -> 1234,57 1234 ("F1", en-US) -> 1234.0 1234 ("F1", de-DE) -> 1234,0 -1234.56 ("F4", en-US) -> -1234.5600 -1234.56 ("F4", de-DE) -> -1234,5600 123.456 ("C", en-US) -> $123.46 123.456 ("C", fr-FR) -> 123,46 € 123.456 ("C", ja-JP) -> ¥123 -123.456 ("C3", en-US) -> ($123.456) -123.456 ("C3", fr-FR) -> -123,456 € -123.456 ("C3", ja-JP) -> -¥123.456 1234 ("D") -> 1234 -1234 ("D6") -> -001234

5.10 Formulating Algorithms: Nested Control Statements

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 (int to 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

Notes Type Conversion 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

5.11 Compound Assignment Operators

5.12 Increment and Decrement Operators

// Fig. 5.16: Increment.cs // Prefix increment and postfix increment operators. using System; public class Increment { public static void 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 Console.WriteLine( ++c ); // increment then display 6 Console.WriteLine( c ); // display 6 again } // end Main }

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.