c# program structure · 2009-03-18 · 7 identifiers identifiersare the words that a programmer...

44
CSS 330 Object CSS 330 Object - - Oriented Oriented Programming Programming C# Program Structure C# Program Structure

Upload: others

Post on 31-Mar-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

CSS 330 ObjectCSS 330 Object--Oriented Oriented ProgrammingProgramming

C# Program StructureC# Program Structure

Page 2: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

2

C# Translation and ExecutionThe C# compiler translates C# source code (.csfiles) into a special representation called Microsoft Intermediate Language (MSIL)

MSIL is not the machine language for any traditional CPU, but a virtual machine

The Common Language Runtime (CLR) then interprets the MSIL file

It uses a just-in-time compiler to translate from MSIL format to machine code on the fly

Page 3: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

3

C# Compilation and Execution

C# sourcecode

MSIL

C#compiler

Machinecode

Just in timecompiler

Page 4: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

4

A Simple C# Program

//==========================================================// // File: HelloWorld.cs // // Classes: HelloWorld// --------------------// This program prints a string called "Hello, World!”////==========================================================

using System;

class HelloWorld{

static void Main(string[] args) {

Console.WriteLine(“Hello, World!”);}

}

Page 5: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

5

C# Program StructureProgram specifications (optional)

//==========================================================// // File: HelloWorld.cs// // Classes: HelloWorld// --------------------// This program prints a string called "Hello, World!”////==========================================================

Library imports (optional)using System;

Class and namespace definitionsclass HelloWorld{

static void Main(string[] args) {

Console.WriteLine(“Hello, World!”);}

}

Page 6: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

6

White Space and CommentsWhite Space

Includes spaces, newline characters, tabs, blanklinesC# programs should be formatted to enhance readability, using consistent indentation!

CommentsComments are ignored by the compiler: used only for human readers (i.e., inline documentation)

Two types of comments• Single-line comments use //…// this comment runs to the end of the line

• Multi-lines comments use /* … *//* this comment runs to the terminatingsymbol, even across line breaks */

Page 7: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

7

Identifiers

Identifiers are the words that a programmer uses in a programAn identifier can be made up of letters, digits, and the underscore characterThey cannot begin with a digitC# is case sensitive, therefore args and Args are different identifiersSometimes we choose identifiers ourselves when writing a program (such as HelloWorld)Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as WriteLine)

using System;class HelloWorld{

static void Main(string[] args) {

Console.WriteLine(“Hello World!”);}

}

Page 8: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

8

Identifiers: Keywords

Often we use special identifiers called keywords that already have a predefined meaning in the language

Example: classA keyword cannot be used in any other way

C# Keywords abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach get goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed set short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using value virtual void volatile while

All C# keywords are lowercase!

Page 9: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

9

NamespacesPartition the name space to avoid name conflict!All .NET library code are organized using namespaces!By default, C# code is contained in the global namespaceTo refer to code within a namespace, must use qualified name (as in System.Console) or import explicitly (as in using System; )

using System;

class HelloWorld{

static void Main(string[] args) {

Console.WriteLine(“Hello World!”);}

}

class HelloWorld{

static void Main(string[] args) {

System.Console.WriteLine(“Hello World!”);}

}

Page 10: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

10

C# Program Structure: Method

class HelloWorld

{

}

// comments about the class

static void Main (string[] args)

{

}

// comments about the method

Console.Write(“Hello World!”);Console.WriteLine(“This is from CS112!”);

Page 11: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Welcome1.cs

Program Output

1 // Welcome1.cs2 // A program in C#.34 using System;56 class Welcome17 {8 static void Main( string[] args )9 {10 Console.WriteLine( "Welcome to C# Programming!" );11 }12 }

Welcome to C# Programming!

These are two single line comments. They are ignored by the compiler and are only used to aid other programmers. They use the double slash (//)

This is the using directive. It lets the compiler know that it should include the System namespace.

This is a blank line. It means nothing to the compiler and is only used to add clarity to the program.This is the beginning of the Welcome1 class definition. It starts with the classkeyword and then the name of the class.

This is the start of the Main method. It instructs the program to do what you want.

This is a statement. Console.WriteLine outputs a string.

Page 12: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

12

Console Application vs. Window Application

Console ApplicationNo visual componentOnly text input and outputRun under Command Prompt or DOS Prompt

Window ApplicationForms with many different input and output typesContains Graphical User Interfaces (GUI)GUIs make the input and output more user friendly!Message boxes

• Within the System.Windows.Forms namespace• Used to prompt or display information to the user

Page 13: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Welcome4.cs

Program Output

1 // Welcome4.cs2 // Printing multiple lines in a dialog Box.3 4 using System;5 using System.Windows.Forms;6 7 class Welcome48 {9 static void Main( string[] args )10 {11 MessageBox.Show( "Welcome\nto\nC#\nprogramming!" );12 }13 }

The System.Windows.Forms namespace allows the programmer to use the MessageBox class.

This will display the contents in a message box as opposed to in the console window.

Page 14: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

14

Example

static void Main(string[] args){

int total;

total = 15;System.Console.Write(“total = “);System.Console.WriteLine(total);

total = 55 + 5;System.Console.Write(“total = “);System.Console.WriteLine(total);

}

Page 15: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

15

Constants

• A constant is similar to a variable except that it holds one value for its entire existence

• The compiler will issue an error if you try to change a constant

• In C#, we use the constant modifier to declare a constantconstant int numberOfStudents = 42;

• Why constants?– give names to otherwise unclear literal values– facilitate changes to the code– prevent inadvertent errors

Page 16: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

16

C# Data Types

• There are 15 data types in C#• Eight of them represent integers:

• byte, sbyte, short, ushort, int, uint, long,ulong• Two of them represent floating point numbers

• float, double• One of them represents decimals:

• decimal• One of them represents boolean values:

• bool• One of them represents characters:

• char• One of them represents strings:

• string• One of them represents objects:

• object

Page 17: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

17

Numeric Data Types

• The difference between the various numeric types is their size, and therefore the values they can store:

Range

0 - 255-128 - 127

-32,768 - 327670 - 65537

-2,147,483,648 – 2,147,483,6470 – 4,294,967,295-9×1018 to 9×1018

0 – 1.8×1019

±1.0×10-28; ±7.9×1028 with 28-29 significant digits

±1.5×10-45; ±3.4×1038 with 7 significant digits±5.0×10-324; ±1.7×10308 with 15-16 significant digits

Question: you need a variable to represent world population. Which type do you use?

Type

bytesbyteshortushortintuintlongulong

decimal

floatdouble

Storage

8 bits8 bits16 bits16 bits32 bits32 bits64 bits64 bits

128 bits

32 bits64 bits

Page 18: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

18

Examples of Numeric Variables

int x = 1;short y = 10;float pi = 3.14f; // f denotes floatfloat f3 = 7E-02f; // 0.07double d1 = 7E-100;// use m to denote a decimaldecimal microsoftStockPrice = 28.38m;

Example: TestNumeric.cs

Page 19: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

19

Boolean

• A bool value represents a true or false condition

• A boolean can also be used to represent any two states, such as a light bulb being on or off

• The reserved words true and false are the only valid values for a boolean type

bool doAgain = true;

Page 20: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

20

Characters

• A char is a single character from the a character set• A character set is an ordered list of characters; each character is given a

unique number• C# uses the Unicode character set, a superset of ASCII

– Uses sixteen bits per character, allowing for 65,536 unique characters– It is an international character set, containing symbols and characters from

many languages– Code chart can be found at:http://www.unicode.org/charts/

• Character literals are represented in a program by delimiting with single quotes, e.g.,

'a‘ 'X‘ '7' '$‘ ',‘

char response = ‘Y’;

Page 21: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

21

Data Input

• Console.ReadLine()– Used to get a value from the user input– Example

string myString = Console.ReadLine();

• Convert from string to the correct data type– Int32.Parse()

• Used to convert a string argument to an integer• Allows math to be preformed once the string is converted• Example:

string myString = “1023”;int myInt = Int32.Parse( myString );

– Double.Parse()– Single.Parse()

Page 22: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

22

Output

• Console.WriteLine(variableName) will print the variable

• You can use the values of some variables at some positions of a string:

System.Console.WriteLine(“{0} {1}.”, iAmVar0, iAmVar1);

• You can control the output format by using the format specifiers:

float price = 2.5f;System.Console.WriteLine(“Price = {0:C}.”, price);

Price = $2.50.

For a complete list of format specifiers, seehttp://msdn.microsoft.com/library/en-us/csref/html/vclrfFormattingNumericResultsTable.asp

Example: TaxAndTotal.cs

Page 23: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

23

TaxAndTotal.cs

Page 24: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

24

Formatting Numbers

Page 25: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

25

Arithmetic Expressions

• An expression is a combination of operators and operands• Arithmetic expressions (we will see logical expressions

later) compute numeric results and make use of the arithmetic operators:

Addition + Subtraction -Multiplication *Division /Remainder %

There are no exponents

Page 26: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Arithmetic.cs

1 // Arithmetic.cs2 // An arithmetic program.3 4 using System;5 6 class Arithmetic7 {8 static void Main( string[] args )9 {10 string firstNumber, // first string entered by user11 secondNumber; // second string entered by user12 13 int number1, // first number to add14 number2; // second number to add15 16 // prompt for and read first number from user as string17 Console.Write( "Please enter the first integer: " );18 firstNumber = Console.ReadLine();19 20 // read second number from user as string21 Console.Write( "\nPlease enter the second integer: " );22 secondNumber = Console.ReadLine();23 24 // convert numbers from type string to type int25 number1 = Int32.Parse( firstNumber );26 number2 = Int32.Parse( secondNumber );27 28 // do operations29 int sum = number1 + number2;30 int diff = number1 - number2;31 int mul = number1 * number2;32 int div = number1 / number2;33 int mod = number1 % number2;

This is the start of class Arithmetic

Two string variables defined over two lines

The comment after the declaration is used to briefly state the variable purposeThese are two ints that are declared

over several lines and only use one semicolon. Each is separated by a coma.

Console.ReadLine is used to take the users input and place it into a variable.

This line is considered a prompt because it asks the user to input data.

Int32.Parse is used to convert the given string into an integer. It is then stored in a variable.

The operation result are stored in result variables.

Page 27: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Arithmetic.cs

32 // display results33 Console.WriteLine( "\n{0} + {1} = {2}.", number1, number2, sum );34 Console.WriteLine( "\n{0} – {1} = {2}.", number1, number2, diff );35 Console.WriteLine( "\n{0} * {1} = {2}.", number1, number2, mul );36 Console.WriteLine( "\n{0} / {2} = {2}.", number1, number2, div );37 Console.WriteLine( "\n{0} % {1} = {2}.", number1, number2, mod );34 35 } // end method Main36 37 } // end class Arithmetic

Putting a variable out through Console.WriteLine is done by placing the variable after the text while using a marked place to show where the variable should be placed.

Page 28: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

28

Increment and Decrement Operators

Operator Called Sample expression Explanation ++ preincrement ++a Increment a by 1, then use the new value

of a in the expression in which a resides.

++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

The increment and decrement operators.

Page 29: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Increment.cs

Program Output

1 // Increment.cs2 // Preincrementing and postincrementing3 4 using System;5 6 class Increment7 {8 static void Main(string[] args)9 { 10 int c;11 12 c = 5;13 Console.WriteLine( c ); // print 514 Console.WriteLine( c++ ); // print 5 then postincrement15 Console.WriteLine( c ); // print 616 17 Console.WriteLine(); // skip a line18 19 c = 5;20 Console.WriteLine( c ); // print 521 Console.WriteLine( ++c ); // preincrement then print 622 Console.WriteLine( c ); // print 623 24 } // end of method Main25 26 } // end of class Increment

556

566

Declare variable c

c is set to 5

Display c (5)

Display c (5) then add 1

Display c (6)

Display c (6)

Add 1 then display c (6)

Display c (5)

Set c equal to 5

Page 30: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

30

Operators Associativity Type () ++ --

left to right right to left

parentheses unary postfix

++ -- + - (type) right to left unary prefix

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

?: right to left conditional

= += -= *= /= %= right to left assignment

Precedence and Associativity

high

low

Page 31: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Increment.cs

Program Output

1 // Fig. 4.14: Increment.cs2 // Preincrementing and postincrementing3 4 using System;5 6 class Increment7 {8 static void Main(string[] args)9 { 10 int c;11 12 c = 5;13 Console.WriteLine( c ); // print 514 Console.WriteLine( c++ ); // print 5 then postincrement15 Console.WriteLine( c ); // print 616 17 Console.WriteLine(); // skip a line18 19 c = 5;20 Console.WriteLine( c ); // print 521 Console.WriteLine( ++c ); // preincrement then print 622 Console.WriteLine( c ); // print 623 24 } // end of method Main25 26 } // end of class Increment

556

566

Declare variable c

c is set to 5

Display c (5)

Display c (5) then add 1

Display c (6)

Display c (6)

Add 1 then display c (6)

Display c (5)

Set c equal to 5

Page 32: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Comparison.cs

1 // Comparison.cs2 // Using if statements, relational operators and equality3 // operators.4 5 using System;6 7 class Comparison8 {9 static void Main( string[] args )10 {11 int number1, // first number to compare12 number2; // second number to compare13 14 // read in first number from user15 Console.Write( "Please enter first integer: " );16 number1 = Int32.Parse( Console.ReadLine() );17 18 // read in second number from user19 Console.Write( "\nPlease enter second integer: " );20 number2 = Int32.Parse( Console.ReadLine() );21 22 if ( number1 == number2 )23 Console.WriteLine( number1 + " == " + number2 );24 25 if ( number1 != number2 )26 Console.WriteLine( number1 + " != " + number2 );27 28 if ( number1 < number2 )29 Console.WriteLine( number1 + " < " + number2 );30 31 if ( number1 > number2 )32 Console.WriteLine( number1 + " > " + number2 );33

Combining these two methods eliminates the need for a temporary string variable.

If number1 is the same as number2 this line is preformed

If number1 does not equal number2 this line of code is executed.If number1 is less than number2

the program will use this lineIf number1 is greater than number2 this line will be preformed

Page 33: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Comparison.cs

Program Output

34 if ( number1 <= number2 )35 Console.WriteLine( number1 + " <= " + number2 );36 37 if ( number1 >= number2 )38 Console.WriteLine( number1 + " >= " + number2 );39 40 } // end method Main41 42 } // end class Comparison

Please enter first integer: 2000

Please enter second integer: 10002000 != 10002000 > 10002000 >= 1000

Please enter first integer: 1000

Please enter second integer: 20001000 != 20001000 < 20001000 <= 2000

Please enter first integer: 1000

Please enter second integer: 10001000 == 10001000 <= 10001000 >= 1000

If number1 is less than or equal to number2 then this code will be usedLastly if number1 is greater

than or equal to number2 then this code will be executed

Page 34: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

34

Operators Associativity Type () ++ --

left to right right to left

parentheses unary postfix

++ -- + - (type) right to left unary prefix

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

?: right to left conditional

= += -= *= /= %= right to left assignment

Precedence and Associativity

high

low

Page 35: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

35

Sequential Programming Revisited

1 // Addition.cs2 // An addition program.3 4 using System;5 6 class Addition7 {8 static void Main( string[] args )9 {10 string firstNumber, // first string entered by user11 secondNumber; // second string entered by user12 13 int number1, // first number to add14 number2, // second number to add15 sum; // sum of number1 and number216 17 // prompt for and read first number from user as string18 Console.Write( "Please enter the first integer: " );19 firstNumber = Console.ReadLine();20 21 // read second number from user as string22 Console.Write( "\nPlease enter the second integer: " );23 secondNumber = Console.ReadLine();24 25 // convert numbers from type string to type int26 number1 = Int32.Parse( firstNumber );27 number2 = Int32.Parse( secondNumber );28 29 // add numbers30 sum = number1 + number2;31 32 // display results33 Console.WriteLine( "\nThe sum is {0}.", sum );34 35 } // end method Main36 37 } // end class Addition

17 // prompt for and read first number from user as string

18 Console.Write( "Please enter the first integer: " );

19 firstNumber = Console.ReadLine();

20

21 // read second number from user as string

22 Console.Write( "\nPlease enter the second integer: " );

23 secondNumber = Console.ReadLine();

24

25 // convert numbers from type string to type int

26 number1 = Int32.Parse( firstNumber );

27 number2 = Int32.Parse( secondNumber );

28

29 // add numbers

30 sum = number1 + number2;

31

32 // display results

33 Console.WriteLine( "\nThe sum is {0}.", sum );

Page 36: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

36

C# Control Structures: Selection

T

F

if structure(single selection)

if/else structure(double selection)

TF

switch structure(multiple selections)

.

.

break

break

break

break

T

T

T

F

F

F

.

Page 37: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

37

C# Control Structures: Repetition

T

F

while structure

T

F

do/while structure F

T

for structure/foreach structure

Page 38: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

38

Ternary Conditional Operator (?:)

• Conditional Operator (e1?e2:e3)– C#’s only ternary operator– Can be used to construct expressions– Similar to an if/else structure

string result;

int numQ;

…………

result = (numQ==1) ? “Quarter” : “Quarters”;

// beginning of the next statement

Page 39: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Analysis.cs

1 // Analysis.cs2 // Analysis of Examination Results.3 4 using System;5 6 class Analysis7 {8 static void Main( string[] args )9 {10 int passes = 0, // number of passes11 failures = 0, // number of failures12 student = 1, // student counter13 grade; // one exam grade14 15 // process 10 students; counter-controlled loop16 while ( student <= 10 ) 17 {18 Console.Write( "Enter grade (0-100): " );19 grade = Int32.Parse( Console.ReadLine() );20 21 if ( result >= 60 )22 passes = passes + 1;23 24 else25 failures = failures + 1;26 27 student = student + 1;28 }29

A while loop that will loop 10 times

A nested if statement that determines which counter should be added to

If the grade >= 60 add one to passes

Else add one to failures

Keep track of the total number of students

Initialize both passes and failures to 0Set the student count to 1

Page 40: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

Analysis.cs

30 // termination phase31 Console.WriteLine();32 Console.WriteLine( "Passed: " + passes );33 Console.WriteLine( "Failed: " + failures );34 35 if ( passes > 8 )36 Console.WriteLine( "Raise Tuition\n" );37 38 } // end of method Main39 40 } // end of class Analysis

Display the results to the user

If the total number of passes was greater than 8 then also tell the user to raise the tuition

Page 41: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

Outline

ForCounter.cs

Program Output

1 // ForCounter.cs2 // Counter-controlled repetition with the for structure.3 4 using System;5 6 class ForCounter7 {8 static void Main( string[] args )9 {10 // initialization, repetition condition and incrementing11 // are all included in the for structure12 for ( int counter = 1; counter <= 5; counter++ )13 Console.WriteLine( counter );14 }15 }

12345

This is where the counter variable is initialized. It is set to 1.

The loop will continue until counter is greater than five (it will stop once it gets to six)

The counter is incremented (1 is added to it)

Note: counter can only be used in the body of the for loop!

When the loop ends the variable expires! We will discuss this issue later!

Page 42: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

42

The flexibility of the for Statement

• Each expression in the header of a for loop is optional– If the initialization is left out, no initialization is performed– If the condition is left out, it is always considered to be true, and

therefore creates an infinite loop– If the increment is left out, no increment operation is performed

• Both semi-colons are always required in the for loop header

for ( ; ; ){

// do something

}

Page 43: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

43

Statements break and continue

• Used to alter the flow of control– The break statement

• Used to exit a loop early

– The continue statement• Used to skip the rest of the statements in a loop and restart at

the first statement in the loop

• Programs can be completed without their usage; use with caution.

Page 44: C# Program Structure · 2009-03-18 · 7 Identifiers Identifiersare the words that a programmer uses in a program An identifier can be made up of letters, digits, and the underscore

44

The switch Statement

break;

case: a case a action(s)true

false

.

.

.

break;

case b action(s) break;

false

false

case: z case z action(s) break;

default action(s)

true

true

case: b