920 likes | 937 Views
This introductory guide covers C# basics, syntax rules, namespaces, and GUI concepts. Learn about comments, keywords, methods, and statements while working on simple text output programs. Includes examples for printing text lines and using message boxes in Windows applications.
E N D
Introduction • Console applications • No visual components • Only text output • Windows applications • Forms with several output types • Contain Graphical User Interfaces (GUIs)
Simple Program: Printing a line of text • Comments • Comments can be created using //… • Multi-lines comments use /* … */ • Comments are ignored by the compiler • Used only for human readers • Namespaces • Groups related C# features into a categories • Allows the easy reuse of code • Many namespaces are found in the .NET framework library • Must be referenced in order to be used • White Space • Includes spaces, newline characters and tabs
Simple Program: Printing a line of text • Keywords • Words that cannot be used as variable or class names or any other capacity • Have a specific unchangeable function within the language • Example: class • Classes • Class names can only be one word long (i.e. no white space in class name ) • Each class name is an identifier • Can contain letters, digits, and underscores (_) • Cannot start with digits • Can start with the at symbol (@)
Simple Program: Printing a line of text • Class bodies start with a left brace ({) • Class bodies end with a right brace (}) • Methods • Building blocks of programs • The Main method • Each console or windows application must have exactly one • All programs start by executing the Main method • Braces are used to start ({) and end (}) a method • Statements • Every statement must end in a semicolon (;)
Simple Program: Printing a line of text • Graphical User Interface • GUIs are used to make it easier to get data from the user as well as display data to the user • Message boxes • Within the System.Windows.Forms namespace • Used to prompt or display information to the user
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 a string of characters that Console.WriteLine instructs the compiler to output 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 class keyword and then the name of the class. This is the start of the Main method. In this case it instructs the program to do everything 1// Fig. 3.1: Welcome1.cs 2// A first program in C#. 3 4 using System; 5 6 class Welcome1 7{ 8staticvoid Main( string[] args ) 9 { 10 Console.WriteLine( "Welcome to C# Programming!" ); 11 } 12} Welcome1.csProgram Output Welcome to C# Programming!
Simple Program: Printing a Line of Text Fig. 3.2 Visual Studio .NET-generated console application.
Simple Program: Printing a Line of Text Fig. 3.3 Execution of the Welcome1 program.
Console.WriteLine will pick up where the line ends. This will cause the output to be on one line even though it is on two in the code. 1 // Fig. 3.4: Welcome2.cs 2 // Printing a line with multiple statements. 3 4 using System; 5 6 class Welcome2 7 { 8 staticvoid Main( string[] args ) 9 { 10 Console.Write( "Welcome to " ); 11 Console.WriteLine( "C# Programming!" ); 12 } 13 } Welcome2.csProgram Output Welcome to C# Programming!
The \n escape sequence is used to put output on the next line. This causes the output to be on several lines even though it is only on one in the code. 1 // Fig. 3.5: Welcome3.cs 2 // Printing multiple lines with a single statement. 3 4 using System; 5 6 class Welcome3 7 { 8 staticvoid Main( string[] args ) 9 { 10 Console.WriteLine( "Welcome\nto\nC#\nProgramming!" ); 11 } 12 } Welcome3.csProgram Output Welcome to C# Programming!
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. 1 // Fig. 3.7: Welcome4.cs 2 // Printing multiple lines in a dialog Box. 3 4 using System; 5using System.Windows.Forms; 6 7 class Welcome4 8 { 9 staticvoidMain( string[] args ) 10 { 11 MessageBox.Show( "Welcome\nto\nC#\nprogramming!" ); 12 } 13 } Welcome4.csProgram Output
Simple Program: Printing a Line of Text Add Reference dialogue Fig. 3.8 Adding a reference to an assembly in Visual Studio .NET (part 1).
Solution Explorer System.Windows.Formsreference Referencesfolder Simple Program: Printing a Line of Text Fig. 3.8 Adding a reference to an assembly in Visual Studio .NET (part 2).
Close box OK button allows the user to dismiss the dialog. Dialog is automatically sized to accommodate its contents. Mouse cursor Simple Program: Printing a Line of Text Fig. 3.10 Dialog displayed by calling MessageBox.Show.
Another Simple Program: Adding Integers • Primitive data types • Data types that are built into C# • string, int, double, char, long • 15 primitive data types • Each data type name is a C# keyword • Same type variables can be declared on separate lines or on one line • Console.ReadLine() • Used to get a value from the user input • Int32.Parse() • Used to convert a string argument to an integer • Allows math to be preformed once the string is converted
This is the start of class Addition Two string variables defined over two lines The comment after the declaration is used to briefly state the variable purpose These are three ints that are declared over several lines and only use one semicolon. Each is separated by a coma. 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 two numbers are added and stored in the variable sum. Console.ReadLine is used to take the users input and place it into a variable. 1 // Fig. 3.11: Addition.cs 2 // An addition program. 3 4 using System; 5 6class Addition 7 { 8 staticvoid Main( string[] args ) 9 { 10string firstNumber, // first string entered by user 11 secondNumber; // second string entered by user 12 13int number1, // first number to add 14 number2, // second number to add 15 sum; // sum of number1 and number2 16 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 Addition.cs
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. 32 // display results 33 Console.WriteLine( "\nThe sum is {0}.", sum ); 34 35 } // end method Main 36 37 } // end class Addition Addition.csProgram Output Please enter the first integer: 45 Please enter the second integer: 72 The sum is 117.
Memory Concepts • Memory locations • Each variable is a memory location • Contains name, type, size and value • When a new value is entered the old value is lost • Used variables maintain their data after use
number1 45 Memory Concepts Fig. 3.12 Memory location showing name and value of variable number1.
Arithmetic • Arithmetic operations • Not all operations use the same symbol • Asterisk (*) is multiplication • Slash (/) is division • Percent sign (%) is the modulus operator • Plus (+) and minus (-) • There are no exponents • Division • Division can vary depending on the variables used • When dividing two integers the result is always rounded down to an integer • To be more exact use a variable that supports decimals
Arithmetic • Order • Parenthesis are done first • Division, multiplication and modulus are done second • Left to right • Addition and subtraction are done last • Left to right
number1 number2 45 72 Memory Concepts Fig. 3.13 Memory locations after values for variables number1 and number2 have been input.
sum number1 number2 45 72 117 Memory Concepts Fig. 3.14 Memory locations after a calculation.
x y Arithmetic
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7; 2 * 5 is 10 (Leftmost multiplication) Step 2. y = 10 * 5 + 3 * 5 + 7; 10 * 5 is 50 (Leftmost multiplication) Step 3. y = 50 + 3 * 5 + 7; 3 * 5 is 15 (Multiplication before addition) Step 4. y = 50 + 15 + 7; 50 + 15 is 65 (Leftmost addition) Step 5. y = 65 + 7; 65 + 7 is 72 (Last addition) Step 6. y = 72; (Last operation—place 72 into y) Arithmetic Fig. 3.17 Order in which a second-degree polynomial is evaluated.
Decision Making: Equality and Relational Operators • The if structure • Used to make a decision based on the truth of the condition • True: a statement is performed • False: the statement is skipped over • Fig. 3.18 lists the equality and rational operators • There should be no spaces separating the operators
If number1 is the same as number2 this line is preformed Combining these two methods eliminates the need for a temporary string variable. If number1 does not equal number2 this line of code is executed. If number1 is less than number2 the program will use this line If number1 is greater than number2 this line will be preformed 1 // Fig. 3.19: Comparison.cs 2 // Using if statements, relational operators and equality 3 // operators. 4 5 using System; 6 7 class Comparison 8 { 9 static void Main( string[] args ) 10 { 11 int number1, // first number to compare 12 number2; // second number to compare 13 14 // read in first number from user 15 Console.Write( "Please enter first integer: " ); 16 number1 = Int32.Parse( Console.ReadLine() ); 17 18 // read in second number from user 19 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 Comparison.cs
If number1 is less than or equal to number2 then this code will be used Lastly if number1 is greater than or equal to number2 then this code will be executed 34 if ( number1 <= number2 ) 35 Console.WriteLine( number1 + " <= " + number2 ); 36 37 if ( number1 >= number2 ) 38 Console.WriteLine( number1 + " >= " + number2 ); 39 40 } // end method Main 41 42 } // end class Comparison Comparison.csProgram Output Please enter first integer: 2000 Please enter second integer: 1000 2000 != 1000 2000 > 1000 2000 >= 1000 Please enter first integer: 1000 Please enter second integer: 2000 1000 != 2000 1000 < 2000 1000 <= 2000 Please enter first integer: 1000 Please enter second integer: 1000 1000 == 1000 1000 <= 1000 1000 >= 1000
Control Structures • Program of control • Program performs one statement then goes to next line • Sequential execution • Different statement other than the next one executes • Selection structure • The if and if/else statements • The goto statement • No longer used unless absolutely needed • Causes many readability problems • Repetition structure • The while and do/while loops (chapter 5) • The for and foreach loops (chapter 5)
if Selection Structure • The if structure • Causes the program to make a selection • Chooses based on conditional • Any expression that evaluates to a bool type • True: perform an action • False: skip the action • Single entry/exit point • Require no semicolon in syntax
Grade >= 60 print “Passed” true false if Selection Structure Fig. 4.3 Flowcharting a single-selection if structure.
if/else selection structure • The if/else structure • Alternate courses can be taken when the statement is false • Rather than one action there are two choices • Nested structures can test many cases • Structures with many lines of code need braces ({) • Can cause errors
false true Grade >= 60 print “Failed” print “Passed” if/else Selection Structure Fig. 4.4 Flowcharting a double-selection if/else structure.
Conditional Operator (?:) • Conditional Operator (?:) • C#’s only ternary operator • Similar to an if/else structure • The syntax is: • (boolean value ? if true : if false)
while Repetition Structure • Repetition Structure • An action is to be repeated • Continues while statement is true • Ends when statement is false • Contain either a line or a body of code • Must alter conditional • Endless loop
Product <= 1000 true Product = 2 * product false while Repetition Structure Fig. 4.5 Flowcharting the while repetition structure.
Formulating Algorithms: Case Study 1 (Counter Controlled Repetition) • Counter Controlled Repetition • Used to enter data one at a time • Constant amount • A counter is used to determine when the loop should break • When counter hits certain value, the statement terminates
Formulating Algorithms: Case Study 1 (Counter Controlled Repetition) Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counterSet the class average to the total divided by tenPrint the class average Fig. 4.6 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.
Initialize total to 0 Initialize gradeCounter to 1 The while loop will loop through 10 times to get the grades of the 10 students Prompt the user to enter a grade Accumulate the total of the 10 grades Add 1 to the counter so the loop will eventually end 1 // Fig. 4.7: Average1.cs2 // Class average with counter-controlled repetition.3 4 using System;5 6 class Average17 {8 staticvoid Main( string[] args )9 {10 int total, // sum of grades11 gradeCounter, // number of grades entered12 gradeValue, // grade value13 average; // average of all grades14 15 // initialization phase16 total = 0; // clear total17 gradeCounter = 1; // prepare to loop18 19 // processing phase20while ( gradeCounter <= 10 ) // loop 10 times21 {22 // prompt for input and read grade from user23 Console.Write( "Enter integer grade: " );24 25 // read input and convert to integer26 gradeValue = Int32.Parse( Console.ReadLine() );27 28 // add gradeValue to total29 total = total + gradeValue;30 31 // add 1 to gradeCounter32 gradeCounter = gradeCounter + 1;33 } Average1.cs
Divide the total by ten to get the average of the ten grades Display the results 34 35 // termination phase 36 average = total / 10; // integer division 37 38 // display average of exam grades 39 Console.WriteLine( "\nClass average is {0}", average ); 40 41 } // end Main 42 43 } // end class Average1 Average1.cs Program Output Enter integer grade: 100 Enter integer grade: 88 Enter integer grade: 93 Enter integer grade: 55 Enter integer grade: 68 Enter integer grade: 77 Enter integer grade: 83 Enter integer grade: 95 Enter integer grade: 73 Enter integer grade: 62 Class average is 79
Case Study 2 (Sentinel Controlled Repetition) • Sentinel controlled repetition • Continues an arbitrary amount of times • Sentinel value • Causes loop to break • Avoid collisions • When flag value = user entered value • Casting • Allows one variable to temporarily be used as another
Case Study 2 (Sentinel Controlled Repetition) Initialize total to zeroInitialize counter to zeroInput the first grade (possibly the sentinel)While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel)If the counter is not equal to zero Set the average to the total divided by the counter Print the averageElse Print “No grades were entered” Fig. 4.8 Pseudocode algorithm that uses sentinel-controlled repetition to solve the class-average problem.
The variable average is set to a double so that it can be more exact and have an answer with decimals Variables gradeCounter and total are set to zero at the beginning Get a value from the user and store it in gradeValue 1 // Fig. 4.9: Average2.cs 2 // Class average with sentinel-controlled repetition. 3 4 using System; 5 6 class Average2 7 { 8 staticvoid Main( string[] args ) 9 { 10 int total, // sum of grades 11 gradeCounter, // number of grades entered 12 gradeValue; // grade value 13 14double average; // average of all grades 15 16 // initialization phase 17 total = 0; // clear total 18 gradeCounter = 0; // prepare to loop 19 20 // processing phase 21 // prompt for input and convert to integer 22 Console.Write( "Enter Integer Grade, -1 to Quit: " ); 23 gradeValue = Int32.Parse( Console.ReadLine() ); 24 Average2.cs
Have the program loop as long as gradeValue is not -1 Add 1 to the counter in order to know the student count Accumulate the total of the grades Prompt the user for another grade, this time it is in the loop so it can happen repeatedly Make sure the total amount of entered grades was not zero to prevent any errors Divide the total by the number of times the program looped to find the average Display the average Inform user if no grades were entered 25 // loop until a -1 is entered by user 26while ( gradeValue != -1 ) 27 { 28 // add gradeValue to total 29 total = total + gradeValue; 30 31 // add 1 to gradeCounter 32 gradeCounter = gradeCounter + 1; 33 34 // prompt for input and read grade from user 35 // convert grade from string to integer 36 Console.Write( "Enter Integer Grade, -1 to Quit: " ); 37 gradeValue = Int32.Parse( Console.ReadLine() ); 38 39 } // end while 40 41 // termination phase 42if ( gradeCounter != 0 ) 43 { 44 average = ( double ) total / gradeCounter; 45 46 // display average of exam grades 47 Console.WriteLine( "\nClass average is {0}", average ); 48 } 49 else 50{ 51 Console.WriteLine( "\nNo grades were entered" ); 52 } 53 54 } // end method Main 55 56 } // end class Average2 Average2.cs
Enter Integer Grade, -1 to Quit: 97 Enter Integer Grade, -1 to Quit: 88 Enter Integer Grade, -1 to Quit: 72 Enter Integer Grade, -1 to Quit: -1 Class average is 85.6666666666667 Average2.cs Program Output