STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0.

Slides:



Advertisements
Similar presentations
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Advertisements

Neal Stublen C# Data Types Built-in Types  Integer Types byte, sbyte, short, ushort, int, uint, long, ulong  Floating Point Types.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Introduction to the C# Programming Language for the VB Programmer.
True or false A variable of type char can hold the value 301. ( F )
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
JavaScript, Third Edition
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
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.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
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 Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Operations Lecture 9.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Programming with Visual C++: Concepts and Projects Chapter 3A: Integral Data (Concepts)
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Performing Simple Calculations with C# Telerik Corporation
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
BOOLEAN OPERATIONS AND CONDITIONALS CHAPTER 20 1.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Operators and Expressions
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
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.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Java Primer 1: Types, Classes and Operators
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3: Understanding C# Language Fundamentals
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Java - Data Types, Variables, and Arrays
Basics of ‘C’.
Module 2: Understanding C# Language Fundamentals
C Operators, Operands, Expressions & Statements
Chapter 6 Control Statements: Part 2
Structured Program Development in C
Primitive Types and Expressions
Presentation transcript:

STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0

SELECT STATEMENTS If - ifstatement evaluate to an expression of type bool If - ifstatement evaluate to an expression of type bool

Switch - have often been error-prone; it is just too easy to inadvertently omit a break statement at the end of a case Switch - have often been error-prone; it is just too easy to inadvertently omit a break statement at the end of a case

C# KEYWORDS

AVOIDING CONFLICTS If you really want to use an identifier that clashes with a keyword, you can do so by qualifying it with If you really want to use an identifier that clashes with a keyword, you can do so by qualifying it with

CONTEXTUAL KEYWORDS Some keywords are contextual, meaning they can also be used as identifiers - without Some keywords are contextual, meaning they can also be used as identifiers - without

LITERALS, PUNCTUATORS, AND OPERATORS Literals – 12 and 30 are examples of literals Literals – 12 and 30 are examples of literals Punctuators – help demarcate the structure of the program Punctuators – help demarcate the structure of the program { } - statement block { } - statement block ; - terminates a statement ; - terminates a statement Operator – transforms and combines expressions Operator – transforms and combines expressions. () * =. () * =

COMMENTS // - single line // - single line /* */ - multiple line /* */ - multiple line

TYPE BASICS A type defines the blueprint for a value A type defines the blueprint for a value Literals 12 and 30 Literals 12 and 30 Variable of type int for x Variable of type int for x All values in C# are instances of a type. All values in C# are instances of a type.

PREDEFINED TYPE EXAMPLES Predefined types are types that are specially supported by the compiler. The int type is a predefined type for representing the set of integers that fit into 32 bits of memory, from − 2 31 to 2 31 − 1. Predefined types are types that are specially supported by the compiler. The int type is a predefined type for representing the set of integers that fit into 32 bits of memory, from − 2 31 to 2 31 − 1. String is another predefined C# type. String is another predefined C# type. Bool is another predefined type with two possible values: true and false. Bool is another predefined type with two possible values: true and false.

CUSTOM TYPE EXAMPLES

Members of a type Members of a type A type contains data members and function members. A type contains data members and function members. The data member of UnitConverter is the field called ratio. The data member of UnitConverter is the field called ratio. The function members of UnitConverter are the Convert method and the UnitConverter’s constructor. The function members of UnitConverter are the Convert method and the UnitConverter’s constructor.

Symmetry of predefined types and custom types Symmetry of predefined types and custom types A beautiful aspect of C# is that predefined types and custom types have few differences. A beautiful aspect of C# is that predefined types and custom types have few differences. The predefined int type serves as a blueprint for integers. The predefined int type serves as a blueprint for integers. It holds data—32 bits - and provides function members that use that data, such as ToString. It holds data—32 bits - and provides function members that use that data, such as ToString. UnitConverter type acts as a blueprint for unit conversions. It holds data - the ratio - and provides function members to use that data. UnitConverter type acts as a blueprint for unit conversions. It holds data - the ratio - and provides function members to use that data.

Constructor and Instantiation Constructor and Instantiation The new operator creates instances of a custom type. UnitConverter feetToInchesConverter = new UnitConverter (12); The new operator creates instances of a custom type. UnitConverter feetToInchesConverter = new UnitConverter (12); Constructor is called to perform initialization. Constructor is called to perform initialization.

Instance versus static members Instance versus static members The data members and function members that operate on the instanceof the type are called instance members. The data members and function members that operate on the instanceof the type are called instance members. The UnitConverter’s Convertmethod and the int’s ToString method are examples of instance members. The UnitConverter’s Convertmethod and the int’s ToString method are examples of instance members. By default, members are instance members. By default, members are instance members. Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static. Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static.

The public keyword The public keyword The publickeyword exposes members to other classes. The publickeyword exposes members to other classes.

CONVERSIONS Can be either implicit or explicit Can be either implicit or explicit Example Example

Implicit conversions are allowed when both of the following are true: Implicit conversions are allowed when both of the following are true: The compiler can guarantee they will always succeed. The compiler can guarantee they will always succeed. No information is lost in conversion. No information is lost in conversion. Explicit conversions are required when one of the following is true: Explicit conversions are required when one of the following is true: The compiler cannot guarantee they will always succeed. The compiler cannot guarantee they will always succeed. Information may be lost during conversion. Information may be lost during conversion.

PREDEFINED TYPE TAXONOMY

NUMERIC TYPES

Numeric Literals Numeric Literals Integral literals – decimal and hexadecimal Integral literals – decimal and hexadecimal int x = 127; int x = 127; long y = 0x7F; long y = 0x7F; Real literal – decimal and/or exponential notation Real literal – decimal and/or exponential notation double d = 1.5; double d = 1.5; double million = 1E06 double million = 1E06

Numeric literal type inference Numeric literal type inference By default, the compiler infers a numeric literal to be either double or an integral type: By default, the compiler infers a numeric literal to be either double or an integral type: If the literal contains a decimal point or the exponential symbol (E), it is a double. If the literal contains a decimal point or the exponential symbol (E), it is a double. Otherwise, the literal’s type is the first type in this list that can fit the literal’s value: int, uint, long, and ulong Otherwise, the literal’s type is the first type in this list that can fit the literal’s value: int, uint, long, and ulong

Numeric suffixes Numeric suffixes

The suffixes U and L are rarely necessary, because the uint, long, and ulong types can nearly always be either inferred or implicitly converted from int: The suffixes U and L are rarely necessary, because the uint, long, and ulong types can nearly always be either inferred or implicitly converted from int: long i = 5; long i = 5; The D suffix is technically redundant, in that all literals with a decimal point are inferred to be double. The D suffix is technically redundant, in that all literals with a decimal point are inferred to be double. Double x = 4.0 Double x = 4.0

The F and M suffixes are the most useful and should always be applied when specifying float or decimal literals. The F and M suffixes are the most useful and should always be applied when specifying float or decimal literals. float f = 4.5F; //will not compile without the F float f = 4.5F; //will not compile without the F The same principle is true for a decimal literal: decimal d = − 1.23M; // Will not compile without the M suffix. The same principle is true for a decimal literal: decimal d = − 1.23M; // Will not compile without the M suffix.

NUMERIC CONVERSIONS Integral to integral conversion Integral to integral conversion Integral conversions are implicit when the destination type can represent every possible value of the source type. Otherwise, an explicit conversion is required Integral conversions are implicit when the destination type can represent every possible value of the source type. Otherwise, an explicit conversion is required Floating-point to floating-point conversions Floating-point to floating-point conversions A float can be implicitly converted to a double, since a double can represent every possible value of a float. The reverse conversion must be explicit. A float can be implicitly converted to a double, since a double can represent every possible value of a float. The reverse conversion must be explicit.

Floating-point to integral conversions Floating-point to integral conversions All integral types may be implicitly converted to all floating-point types: int i = 1; float f = i; All integral types may be implicitly converted to all floating-point types: int i = 1; float f = i; The reverse conversion must be explicit: int i2 = (int)f; The reverse conversion must be explicit: int i2 = (int)f;

Decimal conversions Decimal conversions All integral types can be implicitly converted to the decimal type, since a decimal can represent every possible C# integral value. All integral types can be implicitly converted to the decimal type, since a decimal can represent every possible C# integral value. All other numeric conversions to and from a decimal type must be explicit. All other numeric conversions to and from a decimal type must be explicit.

ARITHMETIC OPERATORS The arithmetic operators (+, -, *, /, %) are defined for all numeric types except the 8- and 16-bit integral types: The arithmetic operators (+, -, *, /, %) are defined for all numeric types except the 8- and 16-bit integral types:

INCREMENT AND DECREMENT OPERATORS The increment and decrement operators (++, −− ) increment and decrement numeric types by 1. The increment and decrement operators (++, −− ) increment and decrement numeric types by 1.

SPECIALIZED INTEGRAL OPERATIONS Integral Division Integral Division Division operations on integral types always truncate remainders (round towards zero). Dividing by a variable whose value is zero generates a runtime error (a DivideByZeroException): Division operations on integral types always truncate remainders (round towards zero). Dividing by a variable whose value is zero generates a runtime error (a DivideByZeroException):

Integral overflow Integral overflow No exception is thrown and the result exhibits “wraparound” behavior No exception is thrown and the result exhibits “wraparound” behavior

Integral arithmetic overflow check operators Integral arithmetic overflow check operators The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions. The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions. The checked operator tells the runtime to generate an OverflowException rather than overflowing silently when an integral expression or statement exceeds the arithmetic limits of that type. The checked operator tells the runtime to generate an OverflowException rather than overflowing silently when an integral expression or statement exceeds the arithmetic limits of that type. The checked operator affects expressions with the ++, −−, +, − (binary and unary), *, /, and explicit conversion operators between integral types. The checked operator affects expressions with the ++, −−, +, − (binary and unary), *, /, and explicit conversion operators between integral types.

Disable checking Disable checking

Overflow checking for constant expressions Overflow checking for constant expressions Regardless of the /checked compiler switch, expressions evaluated at compile time are always overflow-checked—unless you apply the unchecked operator: int x = int.MaxValue + 1; // Compile-time error int y = unchecked (int.MaxValue + 1); // No errors Regardless of the /checked compiler switch, expressions evaluated at compile time are always overflow-checked—unless you apply the unchecked operator: int x = int.MaxValue + 1; // Compile-time error int y = unchecked (int.MaxValue + 1); // No errors

Bitwise operators Bitwise operators

8- AND 16-BIT INTEGRALS The 8- and 16-bit integral types are byte, sbyte, short, and ushort. The 8- and 16-bit integral types are byte, sbyte, short, and ushort. These types lack their own arithmetic operators, so C# implicitly converts them to larger types as required. These types lack their own arithmetic operators, so C# implicitly converts them to larger types as required. This can cause a compile-time error when trying to assign the result back to a small integral type: short x = 1, y = 1; short z = x + y; // Compile-time error short z = (short) (x + y); //OK This can cause a compile-time error when trying to assign the result back to a small integral type: short x = 1, y = 1; short z = x + y; // Compile-time error short z = (short) (x + y); //OK

SPECIAL FLOAT AND DOUBLE VALUES

DOUBLE VERSUS DECIMAL

REAL NUMBER ROUNDING ERRORS float and double internally represent numbers in base 2. float and double internally represent numbers in base 2. Base 10 will not be represented precisely. Base 10 will not be represented precisely. For example: For example: float tenth = 0.1f; // Not quite 0.1 float tenth = 0.1f; // Not quite 0.1 float one = 1f; float one = 1f; Console.WriteLine (one - tenth * 10f); // − E-08 Console.WriteLine (one - tenth * 10f); // − E-08 Decimal works in base 10 and so can precisely represent numbers expressible in base 10 (as well as its factors, base 2 and base 5) Decimal works in base 10 and so can precisely represent numbers expressible in base 10 (as well as its factors, base 2 and base 5)

BOOLEAN TYPE AND OPERATORS C#’s booltype (aliasing the System.Booleantype) is a logical value that can be assigned the literal trueor false. C#’s booltype (aliasing the System.Booleantype) is a logical value that can be assigned the literal trueor false.

EQUALITY AND COMPARISON OPERATORS == and != test for equality and inequality of any type, but always return a bool value. Value types typically have a very simple notion of equality: == and != test for equality and inequality of any type, but always return a bool value. Value types typically have a very simple notion of equality: int x = 1; int x = 1; int y = 2; int y = 2; int z = 1; int z = 1; Console.WriteLine (x == y); // False Console.WriteLine (x == y); // False Console.WriteLine (x == z); // True Console.WriteLine (x == z); // True

CONDITIONAL OPERATORS The && and ||operators test for and and or conditions. They are frequently used in conjunction with the ! operator, which expresses not. The && and ||operators test for and and or conditions. They are frequently used in conjunction with the ! operator, which expresses not. Example static bool UseUmbrella (bool rainy, bool sunny, bool windy) { Example static bool UseUmbrella (bool rainy, bool sunny, bool windy) { return !windy && (rainy || sunny); }

The &&and ||operators short-circuit evaluation when possible. The &&and ||operators short-circuit evaluation when possible. If it is windy, the expression (rainy || sunny) is not even evaluated. If it is windy, the expression (rainy || sunny) is not even evaluated. Short-circuiting is essential in allowing expressions such as the following to run without throwing a NullReferenceException: if (sb != null && sb.Length > 0)... Short-circuiting is essential in allowing expressions such as the following to run without throwing a NullReferenceException: if (sb != null && sb.Length > 0)... The & and |operators also test for and and or conditions: The & and |operators also test for and and or conditions: return !windy & (rainy | sunny);

STRINGS AND CHARACTERS

String Type String Type string a1 = "\\\\server\\fileshare\\helloworld.cs"; string a1 = "\\\\server\\fileshare\\helloworld.cs"; string a2 string a2 String concatenation String concatenation String s = “a” + “b”; String s = “a” + “b”;

OPERATOR TABLE

STATEMENTS Declaration statements Declaration statements string someWord = "rosebud"; string someWord = "rosebud"; int someNumber = 42; int someNumber = 42; bool rich = true, famous = false; bool rich = true, famous = false; Constants Constants const double c = E08; const double c = E08; c += 10; // Compile-time Error c += 10; // Compile-time Error

Scoping static void Main() { int x; { int y; int x; // Error - x already defined } { int y; // OK - y not in scope } Console.Write (y); // Error - y is out of scope } Scoping static void Main() { int x; { int y; int x; // Error - x already defined } { int y; // OK - y not in scope } Console.Write (y); // Error - y is out of scope }

SELECTION STATEMENTS Selection statements (if, switch) Selection statements (if, switch) Conditional operator (?:) Conditional operator (?:) Loop statements (while, do..while, for, foreach) Loop statements (while, do..while, for, foreach)

The if statement The if statement An if statement executes a statement if a bool expression is true. For example: if (5 < 2 * 3) Console.WriteLine ("true"); // true An if statement executes a statement if a bool expression is true. For example: if (5 < 2 * 3) Console.WriteLine ("true"); // true The statement can be a code block: if (5 < 2 * 3) { Console.WriteLine ("true"); Console.WriteLine ("Let's move on!"); } The statement can be a code block: if (5 < 2 * 3) { Console.WriteLine ("true"); Console.WriteLine ("Let's move on!"); }

The else clause The else clause An if statement can optionally feature an else clause: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else Console.WriteLine ("False"); // False An if statement can optionally feature an else clause: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else Console.WriteLine ("False"); // False Within an else clause, you can nest another if statement: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else if (2 + 2 == 4) Console.WriteLine ("Computes"); // Computes Within an else clause, you can nest another if statement: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else if (2 + 2 == 4) Console.WriteLine ("Computes"); // Computes

The switch statement static void ShowCard(int cardNumber) { switch (cardNumber) { case 13: Console.WriteLine ("King"); break; case 12: Console.WriteLine ("Queen"); break; case 11: Console.WriteLine ("Jack"); break; case − 1: // Joker is − 1 goto case 12; // In this game joker counts as queen default: // Executes for any other cardNumber Console.WriteLine (cardNumber); break; } } The switch statement static void ShowCard(int cardNumber) { switch (cardNumber) { case 13: Console.WriteLine ("King"); break; case 12: Console.WriteLine ("Queen"); break; case 11: Console.WriteLine ("Jack"); break; case − 1: // Joker is − 1 goto case 12; // In this game joker counts as queen default: // Executes for any other cardNumber Console.WriteLine (cardNumber); break; } }

Here are the options: Here are the options: break(jumps to the end of the switch statement) break(jumps to the end of the switch statement) goto case x(jumps to another case clause) goto case x(jumps to another case clause) goto default(jumps to the default clause) goto default(jumps to the default clause) Any other jump statement—namely, return, throw, continue, or goto label Any other jump statement—namely, return, throw, continue, or goto label

ITERATION STATEMENTS while and do-while loops while and do-while loops While loops repeatedly execute a body of code while a bool expression is true. The expression is tested before the body of the loop is executed. While loops repeatedly execute a body of code while a bool expression is true. The expression is tested before the body of the loop is executed. For example: int i = 0; while (i < 3) { Console.WriteLine (i); i++; } For example: int i = 0; while (i < 3) { Console.WriteLine (i); i++; } OUTPUT: OUTPUT: 0 1 2

Do-while loop Do-while loop int i = 0; do { Console.WriteLine (i); i++; } while (i < 3);

For loops For loops for (initialization-clause; condition-clause; iteration-clause) statement-or-statement-block

foreach loops foreach loops Enumerable object Enumerable object

EXERCISES TO BE PASSED 1. Print your birth year in one column. For example, if you were born in 1982, your output should look like the following:

2. Create an application that displays the following patterns. You may use any character of your choice to construct the pattern.

3. Write a program to calculate and display your average and grade.Allow the user to enter five scores. After values are entered, and the average calculated, test the result to determine whether an A, B, C, D, or F should be recorded. The scoring rubric is as follows: A—90–100; B—80–89; C—70– 79; D—60–69; F < 60.