3 C Control Statements Dr John P Abraham
3 C# Control Statements Dr. John P. Abraham Professor UTPA
Control statements • Linear (sequential) program execution • Selection structure and repetition structure • Structured programming – Controlled entry and exit out of a module. – Avoid goto statements
Selection structures in C# • If – single selection statement • If. . else – double selection statement • Swich – multiple – selection satement
Examples: if (grade >= 60) Console. writeline(“Passed!”); If (grade >=0) Console. writeline(“Passed!”); else Console. writeline(“Failed!”); Conditional Operator Console. writeline(grade >= 60 ? “Passed!” : “Failed!”);
Nested if (grade >=90) Console. writeline(“A”); else if (grade >=80) Console. writeline(“B!”); … else Console. writeline(“F!”);
Repetiton Structure - while Read LCV (initialize) While (condition) { Block Read LCV again (change value) }
Example length = Convert. To. Int 16(Console. Read. Line()); while (length > 0) { Console. Write("Enter Height of the Wall: "); height = Convert. To. Int 16(Console. Read. Line()); Paint. AWall this. Wall = new Paint. AWall(length, height, price. Per. Gal); this. Wall. Calculate. Cost(ref paint. Cost, ref labor. Cost, ref gal. Paint, ref sq. Ft); Console. Write("Enter Length and Height for Wall # : “ + Convert. To. String(num. Walls+1)); Console. Write("n. Enter Length of the Wall (0 to quit): "); length = Convert. To. Int 16(Console. Read. Line()); }
Counter Controlled vs sentinel controlled • • A while loop, use LCV as a counter Counter =1 While (counter <=10) { … Counter ++ }//does it 10 times Sentinel controlled is good when one does not know exact number of times to execute a loop
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 av; av = sum / num; Console. Write. Line(av); Will print 66
Unary Cast Operator int sum = 200, num = 3; float av; av = (float) sum / num; Console. Write. Line(av); Will print 66. 6666 Float/float or float/int or int/float will yield a float. C# implicitly promotes the one int to float.
Nested control statements • See example of a multiplication table generation class Multiplication. Table { static void Main(string[] args) { int i=2, j, k; while (i <= 12) { for (j = 1; j <= 10; j++) { Console. Write. Line(i + " x " + j + " = " + i * j ); } Console. Write. Line("n"); i++; } }
Switch Statements
- Slides: 12