C# Control Statements

CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement Part I Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539 [email protected] 1 Objectives In this chapter, you will: Learn the primitive data types in Visual C# Become familiar with arithmetic operators Explore how to design algorithms to solve

problems Learn the components of basic control structures Study the syntax of basic sequence, selection, and repetition structures in Visual C# 2 Introduction Computer program Sequence of statements whose objective is to accomplish a task Programming Process of planning and creating a program

3 Introduction (cont'd) Function Collection of statements; accomplishes something when executed, Syntax Rules that specify which statements (instructions) are legal

Programming language A set of rules, symbols, and special words Visual C# 4 Introduction (cont'd) Reserved words, keywords, or word symbols Words that are reserved by Visual C# Usually in blue color in the IDE (Visual Studio) 5 About Some Data Types in C#

Value Types 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 147483648 to 2147483647 uint 32 0 to 4294967295 long 64 -9223372036854775808 to 9223372036854775807 ulong 64 0 to 18446744073709551615 char 16

0 to 65535 bool 8 true, false enum types and struct types Reference types include class types, interface types, delegate types, and array types Pointer types 6 Declaration of Variables All variables must be declared before they are used in a program Declaring a variable

int product = 3; Declaring multiple variables of the same type int number1, number2; 7 Naming Convention Consist of letters, digits, and the underscore character (_) Must begin with a letter or underscore C# is case sensitive NUMBER is not the same as number 8

Arithmetic Operators in Visual C# Addition: + Subtraction: Multiplication: * Division: / Modulus: % Increment: ++

Decrement: -9 Explicitly and Implicitly Converting Between Simple Types Integer and integer division yields integer result Suppose average is a floating point number: Average = total/num; Average will only get an integer if total and num are integers. int sum = 200, num = 3; float avg; avg = sum / num; Console.WriteLine(avg); // Output: 66

10 Unary Cast Operator int sum = 200, num = 3; float av; av = (float) sum / num; Console.WriteLine(av); // Output: 66.6666 float/float or float/int or int/float will yield a float. C# implicitly promotes the one int to float 11 Division and Modulus x / y and x%y

int x=7, y = 2; Console.WriteLine(x / y); Console.WriteLine(x % y); E.g., 7.0 / 2 evaluates to 3.5 12 Last Chapter: Arithmetic Operators Unary: +, Multiplicative: *, /, %

Additive: +, Relational operators high > < >= <= Equality operators ==, != Precedence of operators low http://msdn.microsoft.com/en-us/library/6a71f45d.aspx 13

Exercises What are the values of the following expressions? 10/3 5.2/2.0 9%3 What is the order of the following expression? X = 2 * 5 / 3+ 3 * 5 + 7 14 Control Statements

Linear (sequential) program execution Selection structure repetition structure Structured programming Controlled entry and exit out of a module Avoid goto statements 15 Selection Structures in C# if single selection statement if else double selection statement

switch multiple selection statement [grade>=60] display "passed" [grade<60] 16 Examples if (grade >= 60) Console.WriteLine("Passed!"); if (grade >= 60)

Console.WriteLine("Passed!"); else Console.WriteLine("Failed!"); Conditional Operator Console.WriteLine(grade >= 60 ? "Passed!": Failed!); 17 Nested If Statement if (grade >=90) Console.WriteLine(A); else if (grade >=80) Console.WriteLine(B!);

else Console.WriteLine(F!); 18 Repetition Structure - while Read LCV (initialize) while (condition) { Block Read LCV again (change value) } 19

Example length = Convert.ToInt16(Console.ReadLine()); while (length > 0) { Console.Write("Enter Height of the Wall: "); height = Convert.ToInt16(Console.ReadLine()); PaintAWall thisWall = new PaintAWall(length, height, pricePerGal); thisWall.CalculateCost(ref paintCost, ref laborCost, ref galPaint, ref sqFt); Console.Write("Enter Length and Height for Wall #: " + Convert.ToString(numWalls+1)); Console.Write("\nEnter Length of the Wall (0 to quit): "); length = Convert.ToInt16(Console.ReadLine()); }

20 Counter Controlled vs Sentinel Controlled Counter controlled while loop (use LCV as a counter) int Counter =1; while (Counter <=10) { increment operator Counter ++; }//does it 10 times 21

Counter Controlled vs Sentinel Controlled (cont'd) Sentinel controlled while loop string str; while (str != "0") { str = Console.ReadLine(); }//does it until str is "0" Sentinel controlled is good when one does not know exact number of times to execute a loop 22 Example of while Loop

int product = 3; while (product <= 100) product = 3*product; 23 Nested Control Statements class MultiplicationTable { static void Main(string[] args) { int i=2, j; while (i <= 12) {

j = 1; while (j <= 10) { Console.WriteLine(i + " x " + j + " = " + i * j ); j++; } Console.WriteLine("\n"); i++; } } } 24 Exercises Write a console program using nested while

loop to output the following pattern to screen: * ** *** **** ***** 25

Recently Viewed Presentations

  • Introduction to Computer Systems

    Introduction to Computer Systems

    CF Carry Flag (for unsigned) SF Sign Flag (for signed) ZF Zero Flag OF Overflow Flag (for signed) Implicitly set (as side effect) of arithmetic operations. Example: addqSrc,Dest ↔ t = a+b. CF setif carry/borrow out from most significant bit...
  • deerparksped.weebly.com


    Example - see FISH assessment booklet - ADT 77 - Sit on toilet set a table - if respondent not sure, see objective in lesson plan (page 115 in FISH book) The student will sit and remain on a toilet...
  • 9.1 The Qualitative Process of Data Analysis

    9.1 The Qualitative Process of Data Analysis

    Times New Roman Arial Black Arial Tahoma Creswell 2E Spring 2004 Custom Design Chapter 9 Key Ideas What is the Process of Data Analysis? A Visual Model of the Coding Process in Qualitative Research How do You Use Codes to...
  • Universal Transverse Mercator (UTM)

    Universal Transverse Mercator (UTM)

    USING UTM, MGRS & USNG Monica Spicker Some slides adapted from Harry Frank 2008 B M O C B M O C Objectives Understanding UTM system Finding coordinates of a point Plotting a point B M O C Universal Transverse...
  • Mining the Milky Way Galaxy with SDSS

    Mining the Milky Way Galaxy with SDSS

    The Earth's center is not the center of the Universe Religion? The center of the Universe is near the Sun The rotation of the Earth accounts for the apparent daily rotation of the stars Copernicus' Model cont… The annual movements...
  • AREA of study: Journeys - English and Drama (IICS)

    AREA of study: Journeys - English and Drama (IICS)

    Journeys -Prep for Film Analysis Essay. HW for Monday - Essay Outline. On one page (typed), come up with a . thesis statement. that you could use to write your Film Analysis Essay. Remember, you are discussing one idea about...
  • Nitrate Technology for Control of Reservoir Souring

    Nitrate Technology for Control of Reservoir Souring

    Consider: Economics/ Field Life/ Downhole Injection Conditions New Products PETROCARE™ Process Nitrate Technology for Control of Reservoir Souring PETROCARE™ The PETROCARE process Licensed from Yara Aqueous Nitrate added via water injection treats & inhibits reservoir souring, stimulating naturally occurring denitrifying...
  • Wales is a fairly small country, covering an

    Wales is a fairly small country, covering an

    Its highest Mountain is Mount Gimie which rises 950m above sea level. St Lucia has 8 principal rivers, one of which is the Dennery on East of the island. 26% of the population work in the agricultural indusrty. 60% of...