SlideShare a Scribd company logo
1 of 72
An Introduction 
to C# 
Lecture 1 
Dr. Hakem Beitollahi 
Computer Engineering Department 
Soran University
Objectives of this lecture 
 In this chapter you will learn: 
 To write simple C# applications. 
 To use input and output statements. 
 C#’s primitive types. 
 Basic memory concepts. 
 To use arithmetic operators. 
 The precedence of arithmetic operators. 
 To write decision-making statements. 
 To use relational and equality operators. 
An introduction to C#— 2
First program in C# 
An introduction to C#— 3
First C# program: printing a line 
Single-line comments. 
Left brace { begins function 
body. 
Predefined namespace (System)– part of .NET FCL 
User defined namespace 
User defined class 
A blank line 
Function Main returns 
nothing (void) and is static 
Function Main appears exactly once in every C# program.. 
Corresponding right brace } 
ends function body. 
Statements end with a 
semicolon ;. 
Console 
An introduction to C#— 4
Elements of a C# Program
Anatomy of the first program (I) 
// First program in C#. 
 Comments start with: // 
 Comments ignored during program execution 
 Document and describe code 
 Provides code readability 
 Traditional comments: /* ... */ 
/* This is a traditional 
comment. It can be 
split over many lines */ 
An introduction to C#— 6
Good Programming Practice Tip (1) 
 Every program should begin with a 
comment that explains the purpose of the 
program, the author and the date and time 
the program 
Chapter 3: An introduction to C# — 7
using Directive 
 Permits use of classes found in specific 
namespaces without having to qualify them 
 Framework class library 
 Over 2,000 classes included 
 Syntax 
 using namespaceIdentifier; 
An introduction to C#— 8
namespace 
 One of the great strengths of C# is that C# programmers 
can use the rich set of namespaces provided by the 
.NET 
 These namespaces contain code that programmers can 
reuse 
 framework.Groups semantically related types under a 
single umbrella 
 System: most important and frequently used namespace 
 An example of one of the features in namespace System is 
Console 
 We discuss many namespaces and their features 
throughout the course. 
An introduction to C#— 9
Blank line 
 Use blank lines and space characters 
throughout a program to make the 
program easier to read. 
 Collectively, blank lines, space characters, 
newline characters and tab characters are 
known as whitespace 
 The compiler ignores 
 blank lines, tabs and extra spaces that 
separate language elements. 
An introduction to C#— 10
 Our first class 
 C# programs consist of pieces called classes, which are 
logical groupings of members (e.g., methods) that 
simplify program organization. 
 These methods perform tasks and return information 
when the tasks are completed. 
 A C# program consists of classes and methods created 
by the programmer and of preexisting classes found in 
the Framework Class Library. 
 Every program in C# consists of at least one class 
definition that the programmer defines. 
 The class keyword begins a class definition in C# and is 
followed immediately by the class name (program) 
An introduction to C#— 11
Identifiers names 
 By convention, each word in a class name begins with an uppercase 
first letter and has an uppercase letter for each word in the class 
name: SampleClassName 
 Identifiers is a series of characters consisting of letters, digits, 
underscores ( _ ) and “at” symbols (@). 
 Identifiers cannot begin with a digit and cannot contain spaces. 
 The “at” character (@) can be used only as the first character in an 
identifier 
 Examples of valid identifiers: 
 Welcome1, _value, m_inputField1, button7, @value 
 Examples of invalid identifiers 
 5welcome, input field, val@, in$put 
 C# is case sensitive 
An introduction to C#— 12
Common Programming Error (1) 
C# is case sensitive. Not using the proper 
case for an identifier, e.g.,writing Total 
when the identifier is total, is a compiler 
error. 
An introduction to C#— 13
Good Programming Practice Tip (2) 
 Always begin a class name with an 
uppercase first letter. This practice makes 
class names easier to identify. 
An introduction to C#— 14
Braces { } 
 The left brace ({) begins the body of the 
class definition. 
 The corresponding right brace (}) ends the 
class definition. 
An introduction to C# — 15
Common Programming Error Tip (2) 
 If braces do not occur in matching pairs, a 
syntax error occurs. 
An introduction to C#— 16
Good Programming Practice Tip (3) 
 When typing an opening left brace ({) in a 
program, immediately type the closing 
right brace (}) then reposition the cursor 
between the braces to begin typing the 
body. 
An introduction to C#— 17
Good Programming Practice Tip (4) 
 Indent the entire body of each class definition 
one “level” of indentation between the left brace 
({) and the right brace (}) that delimit the class 
body. This emphasizes the structure of the class 
definition and helps make the class definition 
easier to read. 
An introduction to C#— 18
static void Main(string[] args) 
 present in all C# console and Windows applications. 
 These applications begin executing at Main, which is 
known as the entry point of the program. 
 The parentheses after Main indicate that Main is a 
program building block, called a method. 
 C# class definitions normally contain one or more 
methods and C# applications contain one or more 
classes. 
 For a C# console or Windows application, exactly one of 
those methods must be called Main 
 M in Main must be uppercase 
Administrative — 19
The Console 
 The Console class enables programs to output 
information to the computer’s standard output. 
 It provides methods to display strings and other types 
of information in the Windows command prompt. 
 Method Console.WriteLine displays (or prints) a line 
of text in the console window. 
 When Console.WriteLine completes its task, it 
positions the output cursor at the beginning of the next 
line in the console window. 
 Statement: The entire line, including Console.WriteLine, 
its argument in the parentheses ("Welcome to C# 
Programming!") and the semicolon (;) 
 Every statement must end with a semicolon. 
Chapter 3: An introduction to C#— 20
Common Programming Error Tip (3) 
 Omitting the semicolon at the end of a 
statement is a syntax error. 
 When the compiler reports a syntax error, 
the error might not be on the line indicated 
by the error message. First, check the line 
where the error was reported. If that line 
does not contain syntax errors, check the 
lines that precede the one reported. 
Chapter 3: An introduction to C#— 21
Administrative — 22 
// Fig. 3.4: Welcome2.cs 
// Printing a line with multiple statements. 
using System; 
class Welcome2 
{ 
static void Main( string[] args ) 
{ 
Console.Write( "Welcome to " ); 
Console.WriteLine( "C# Programming!" ); 
} 
} 
Console.Write keeps the curse in the last position
Modifying the first program 
(print same contents using different code) 
An introduction to C#— 23
// Fig. 3.5: Welcome3.cs 
// Printing multiple lines with a single statement. 
using System; 
class Welcome3 
{ 
static void Main( string[] args ) 
{ 
Console.WriteLine( "WelcomentonC#nProgramming!" ); 
} 
} 
Notice how a new line is output for 
each n escape sequence. 
An introduction to C#— 24
Slash Operator (I) 
An introduction to C#— 25
Slash Operator (II) 
Code Meaning 
b Backspace 
n Newline 
r Carriage return 
t Horizontal tab 
v Vertical tab 
” Double quote 
 backslash 
a Beep 
26/27
The Same Program in Windows Form Style 
An introduction to C#— 27
// Fig. 3.7: Welcome4.cs 
// Printing multiple lines in a dialog Box. 
using System; 
using System.Windows.Forms; 
class Welcome4 
{ 
static void Main( string[] args ) 
{ 
Class MessageBox 
is located in assembly 
System.Windows.Forms 
MessageBox.Show("WelcomentonC#nprogramming!"); 
} 
} 
An introduction to C#— 28
Common Programming Error Tip (4) 
 Including a namespace with the using 
directive, but not adding a reference to 
the proper assembly, results in a compiler 
error. 
An introduction to C#— 29
Add a reference to your program (I) 
 To begin, make sure you have an application 
open. Select the Add Reference… option from 
the Project menu, or right click the 
References folder in the Solution Explorer 
and select Add Reference… from the popup 
menu that appears. This opens the Add 
Reference dialog. Double click 
System.Windows.Forms.dll to add this file to 
the Selected Components list at the bottom of 
the dialog, then click OK. 
 See next slide 
An introduction to C#— 30
Add a reference to your program (II) 
An introduction to C#— 31
GUI EXample 
An introduction to C#— 32
Another Simple Program: Adding Integers 
An introduction to C#— 33
Addition Proggram 
// Fig. 3.11: Addition.cs 
// An addition program. 
using System; 
class Addition 
{ 
static void Main( string[] args ) 
{ 
string firstNumber, // first string entered by user 
secondNumber; // second string entered by user 
int number1, // first number to add 
number2, // second number to add 
sum; // sum of number1 and number2 
// prompt for and read first number from user as string 
Console.Write("Please enter the first integer: "); 
firstNumber = Console.ReadLine(); 
// read second number from user as string 
Console.Write("nPlease enter the second integer: "); 
secondNumber = Console.ReadLine(); 
// convert numbers from type string to type int 
number1 = Int32.Parse( firstNumber ); 
number2 = Int32.Parse( secondNumber ); 
// add numbers 
sum = number1 + number2; 
// display results 
Console.WriteLine( "nThe sum is {0}.", sum ); 
} // end method Main 
} //end class Addition 
Define two string variables to enter 
numbers 
Define three integer variables 
prompt for first number from user as 
string 
Read first number from user as string 
usinf ReadLine method 
convert numbers from type string to 
type int using Int32 class and Parse 
method 
Add numbers 
Display result in the screen 
An introduction to C#— 34
Variables 
 A variable is a location in the computer’s memory where 
a value can be stored for use by a program. 
 All variables must be declared with a name and a data 
type before they can be used in a program. 
 firstNumber and secondNumber are data of type string, 
which means that these variables store strings of 
characters. 
 Primitive data types: string, int, double and char 
 int holds integer values (whole numbers): i.e., 0, -4, 97 
 Types float and double can hold decimal numbers 
 Type char can hold a single character: i.e., x, $, n, 7 
 A variable name can be any valid identifier 
An introduction to C#— 35
Good Programming Practice Tip (5) 
 Choosing meaningful variable names helps a program to 
be “self-documenting” (i.e., easier to understand simply 
by reading it, rather than having to read manuals or use 
excessive comments). 
An introduction to C#— 36
Good Programming Practice Tip (6) 
 By convention, variable-name identifiers 
begin with a lowercase letter. As with class 
names, every word in the name after the 
first word should begin with a capital letter. 
For example, identifier firstNumber has a 
capital N in its second word, Number. 
An introduction to C#— 37
Good Programming Practice Tip (7) 
 Some programmers prefer to declare each 
variable on a separate line. This format 
allows for easy insertion of a comment that 
describes each variable. 
An introduction to C#— 38
Prompt 
Console.Write("Please enter the first integer: "); 
firstNumber = Console.ReadLine(); 
 prompt the user to input an integer and read from the 
user a string representing the first of the two integers 
that the program will add. 
 It is called a prompt, because it directs the user to take a 
specific action. 
 Method ReadLine causes the program to pause and wait 
for user input. 
 The user inputs characters from the keyboard, then 
presses the Enter key to return the string to the program. 
An introduction to C#— 39
Convert string to int 
// convert numbers from type string to type int 
number1 = Int32.Parse( firstNumber ); 
number2 = Int32.Parse( secondNumber ); 
 Method Int32.Parse converts its string 
argument to an integer. 
 Class Int32 is part of the System 
namespace. 
 assign the integer that Int32.Parse 
returns to variable number1. 
 The = operator is a binary operator 
An introduction to C#— 40
Good Programming Practice Tip (7) 
Place spaces on either side of a binary 
operator. This makes the operator stand 
out and makes the program more 
readable. 
An introduction to C#— 41
Sum 
// add numbers 
sum = number1 + number2; 
 calculates the sum of the variables 
number1 and number2 and assigns the 
result to variable sum by using the 
assignment operator =. 
An introduction to C#— 42
Display results (I) 
// display results 
Console.WriteLine( "nThe sum is {0}.", sum ); 
 It displays the result of the addition 
 we want to output the value in a variable 
using method WriteLine 
 use {0} to indicate a placeholder for a 
variable’s value. 
 Suppose sum =117, the resulting string 
will be “The sum is 117.” 
An introduction to C#— 43
Display results (II) 
Console.WriteLine("The numbers entered are {0} and {1}", number1, number2); 
 the value of number1 would replace {0} (because 
it is the first variable) and the value of number2 
would replace {1} (because it is the second 
variable). 
 The resulting string would be "The numbers 
entered are 45 and 72". 
 More formats can be used ({2}, {3} etc.) if there 
are more variables to display in the string. 
An introduction to C#— 44
Good Programming Practice Tip (8) 
 Place a space after each comma in a 
method’s argument list to make programs 
more readable. 
An introduction to C#— 45
Good Programming Practice Tip (9) 
 Follow the closing right brace (}) of the 
body of a method or class definition 
with a singleline comment. This comment 
should indicate the method or class that 
the right brace terminates. 
An introduction to C#— 46
Memory Concepts 
An introduction to C#— 47
Memory Concepts 
Number 1: 45 
Number 2: 72 
Sum: 117 
MMememoroyr ylo lcoactaiotinosn sa fateftre sr tcoarilncgu lavatinluge sa nfodr sntourminbge trh1e a snudm n uomf nbuemr2b.er1 and 
number2. 
Memory location showing the name and value of variable number1. 
An introduction to C#— 48
Arithmetic 
An introduction to C#— 49
Arithmetic Operations (I) 
An introduction to C#— 50
Arithmetic Operations (II) 
 Be careful! 
 5 / 2 yields an integer 2 
 5.0 / 2 yields a double value 2.5 
 Remainder can be very useful 
 Even numbers % 2 = 0 
 Today is Saturday and you and your friends are 
going to meet in 10 days. What day is in 10 days? 
Saturday is the 6th day in a week 
A week has 7 days 
After 10 days 
The 2nd day in a week is Tuesday 
(6 + 10) % 7 is 2 
An introduction to C#— 51
Arithmetic (III) 
 Operators have precedence 
 Some arithmetic operators act before others 
(i.e., multiplication before addition) 
 Use parenthesis when needed 
 Example: Find the average of three variables 
a, b and c 
 Do not use: a + b + c / 3 
 Use: ( a + b + c ) / 3 
An introduction to C#— 52
Arithmetic (IV) 
An introduction to C#— 53
 Operators have precedence 
1. Parentheses () 
2. *, /, % 
3. +,- 
4. … 
3 + 4 * 4 + 5 * (4 + 3) – 1 
3 + 4 * 4 + 5 * 7 – 1 
3 + 16 + 5 * 7 – 1 
3 + 16 + 35 – 1 
19 + 35 – 1 
54 – 1 
53 
in side parenthesis first 
multiplication 
multiplication 
addition 
addition 
subtraction 
An introduction to C#— 54 
Arithmetic (V)
Algebra: z = pr%q + w/x – y 
C#: z = p * r % q + w / x - y; 
1 
2 
3 
4 
5 
6 
An introduction to C#— 55 
Arithmetic (VI)
 Test yourself 
 y = a * x * x + b * x + c; 
 Y = a+b/(a%5)-a%a*3; (a= 7, b = 3) 
An introduction to C#— 56
Decision Making 
An introduction to C#— 57
Decision Making: Equality and Relational 
Operators (I) 
 Condition 
 Expression can be either true or false 
 if statement 
 Simple version in this section, more detail later 
 If a condition is true, then the body of the if 
statement executed 
 Control always resumes after the if statement 
 Conditions in if statements can be formed 
using equality or relational operators (next slide) 
An introduction to C#— 58
Decision Making: Equality and Relational 
Operators (II) 
An introduction to C#— 59
Common Programming Error Tip (5) 
It is a syntax error if the operators ==, !=, >= 
and<= contain spaces between their 
symbols (as in = =, ! =, > =, < =). 
An introduction to C#— 60
Common Programming Error Tip (6) 
 Reversing the operators !=, >= and <= (as 
in =!, => and =<) is a syntax error. 
An introduction to C#— 61
Common Programming Error Tip (7) 
 Confusing the equality operator == with 
the assignment operator = is a logic 
error. The equality operator should be 
read “is equal to,” and the assignment 
operator should be read “gets” or “gets the 
value of.” Some people prefer to read the 
equality operator as “double equals” or 
“equals equals.” 
An introduction to C#— 62
// Fig. 3.19: Comparison.cs 
// Using if statements, relational operators and equality operators. 
using System; 
class Comparison 
{ 
static void Main( string[] args ) 
{ 
int number1, // first number to compare 
number2; // second number to compare 
Directly get string 
and convert to int 
// read in first number from user 
Console.Write("Please enter first integer: "); 
number1 = Int32.Parse(Console.ReadLine()); 
// read in second number from user 
Console.Write("nPlease enter second integer: "); 
number2 = Int32.Parse(Console.ReadLine()); 
if (number1 == number2) 
Console.WriteLine(number1 + " == " + number2); 
if (number1 != number2) 
Console.WriteLine(number1 + " != " + number2); 
if (number1 < number2) 
Console.WriteLine(number1 + " < " + number2); 
if (number1 > number2) 
Console.WriteLine(number1 + " > " + number2); 
if (number1 <= number2) 
Console.WriteLine(number1 + " <= " + number2); 
if ( number1 >= number2 ) 
If condition is true (i.e., 
values are equal), execute this 
statement. 
Console.WriteLine( number1 + " >= " + number2 ); 
}// end method Main 
} // end class Comparison 
if structure compares values 
of num1 and num2 to test for 
equality. if structure compares values 
If condition is true (i.e., 
values are not equal), execute 
this statement. 
of num1 and num2 to test for 
inequality. 
An introduction to C#— 63
Console.WriteLine(number1 + " == " + number2); 
 This expression uses the operator + to 
“add” (or combine) numbers and strings. 
 C# has a version of the + operator used 
for string concatenation. 
 Concatenation is the process that enables 
a string and a value of another data type 
(including another string) to be combined 
to form a new string. 
An introduction to C#— 64
Common Programming Error Tip (8) 
 Confusing the + operator used for string 
concatenation with the + operator used for 
addition can lead to strange results 
 Assume y = 5; 
 The expression "y + 2 = " + y + 2 results in 
the string "y + 2 = 52“ and not "y + 2 = 7". 
 The expression "y + 2 = " + (y + 2) results 
in "y + 2 = 7“ 
An introduction to C#— 65
Common Programming Error Tip (9) 
 Replacing operator == in the condition 
of an if structure, such as if ( x == 1 ), 
with operator =, as in if ( x = 1 ), is a 
logic error. 
if (number1 = number2) 
Console.WriteLine(number1 + " == " + number2); 
An introduction to C#— 66
Common Programming Error Tip (10) 
 Forgetting the left and right parentheses 
for the condition in an if structure is a 
syntax error. The parentheses are 
required. 
if number1 == number2 
Console.WriteLine(number1 + " == " + number2); 
An introduction to C#— 67 
( )
Common Programming Error Tip (11) 
 There is no semicolon (;) at the end of the 
first line of each if structure. It is Syntax 
error. If takes no action. 
 Example: 
if (number1 == number2); 
Console.WriteLine(number1 + " == " + number2); 
An introduction to C#— 68
Good Programming Practice Tip (10) 
 Place only one statement per line in a 
program. This enhances program 
readability. 
An introduction to C#— 69
Good Programming Practice Tip (11) 
 A lengthy statement may be spread over several lines. 
 In case of splitting, choose breaking points that make 
sense, 
 after a comma in a comma separated list 
 after an operator in a lengthy expression. 
 Indent all subsequent lines with one level of indentation. 
 Example: 
int number1, // first number to add 
number2, // second number to add 
sum; // sum of number1 and number2 
An introduction to C#— 70
Good Programming Practice Tip (12) 
 Confirm that the operators in the expression are 
performed in the expected order. 
 If you are uncertain about the order of evaluation 
in a complex expression, use parentheses to 
force the order 
 assignment (=), associate from right to left rather 
than from left to right. 
 Example 
y = a * x * x + b * x + c; y = (a * x * x) + (b * x) + c; 
y = x; it means that x is assigned into y 
An introduction to C#— 71
HomeWork 
 First Homework 
 Write a program in C# that print your name 
with stars (*) in the screen 
* * 
* * 
* * * * 
* * 
* * 
* * * * 
* * 
* * * * 
* * 
* * 
* * 
* * 
* 
* * 
* * 
* * * * * 
* 
* * * * * 
* 
* * * * * 
Deadline: Next week 
* * 
* * * * 
* * * * 
* * * * 
* * * 
An introduction to C#— 72

More Related Content

What's hot

Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-
Krishna Sai
 
The Art Of Debugging
The Art Of DebuggingThe Art Of Debugging
The Art Of Debugging
svilen.ivanov
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
Akshay Nagpurkar
 
Web Application Testing
Web Application TestingWeb Application Testing
Web Application Testing
Richa Goel
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 

What's hot (20)

Testing web application
Testing web applicationTesting web application
Testing web application
 
Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDB
 
Coding standards and guidelines
Coding standards and guidelinesCoding standards and guidelines
Coding standards and guidelines
 
Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
 
The Art Of Debugging
The Art Of DebuggingThe Art Of Debugging
The Art Of Debugging
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
Compilers
CompilersCompilers
Compilers
 
C#.NET
C#.NETC#.NET
C#.NET
 
Software requirements specification
Software requirements specificationSoftware requirements specification
Software requirements specification
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)
 
Debuggers in system software
Debuggers in system softwareDebuggers in system software
Debuggers in system software
 
Code Generation
Code GenerationCode Generation
Code Generation
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Web Application Testing
Web Application TestingWeb Application Testing
Web Application Testing
 
Inline function
Inline functionInline function
Inline function
 
debugging - system software
debugging - system softwaredebugging - system software
debugging - system software
 

Viewers also liked

Leadership development model npm
Leadership development model npmLeadership development model npm
Leadership development model npm
Anna Leth Clante
 
Beav ex interview questions and answers
Beav ex interview questions and answersBeav ex interview questions and answers
Beav ex interview questions and answers
JulianDraxler
 
The definitive-guide-to LinkedIn
The definitive-guide-to LinkedInThe definitive-guide-to LinkedIn
The definitive-guide-to LinkedIn
AMComms
 
Cozen o'connor interview questions and answers
Cozen o'connor interview questions and answersCozen o'connor interview questions and answers
Cozen o'connor interview questions and answers
AlanWright789
 
Tequipalcatalogo
TequipalcatalogoTequipalcatalogo
Tequipalcatalogo
tishval
 

Viewers also liked (20)

FMS Spring Appeal 2014
FMS Spring Appeal 2014FMS Spring Appeal 2014
FMS Spring Appeal 2014
 
Generator dc
Generator dcGenerator dc
Generator dc
 
Slide11 icc2015
Slide11 icc2015Slide11 icc2015
Slide11 icc2015
 
Incident manager - Apps for Good 2014 Entry
Incident manager - Apps for Good 2014 EntryIncident manager - Apps for Good 2014 Entry
Incident manager - Apps for Good 2014 Entry
 
Leadership development model npm
Leadership development model npmLeadership development model npm
Leadership development model npm
 
Beav ex interview questions and answers
Beav ex interview questions and answersBeav ex interview questions and answers
Beav ex interview questions and answers
 
U.S. Department of Labor - OFFCP Contracts Compliance Officer Roles and Respo...
U.S. Department of Labor - OFFCP Contracts Compliance Officer Roles and Respo...U.S. Department of Labor - OFFCP Contracts Compliance Officer Roles and Respo...
U.S. Department of Labor - OFFCP Contracts Compliance Officer Roles and Respo...
 
Tagmax_ebooklet
Tagmax_ebookletTagmax_ebooklet
Tagmax_ebooklet
 
The 7 greatest cg aliens
The 7 greatest cg aliensThe 7 greatest cg aliens
The 7 greatest cg aliens
 
Anti inflammatory agents
Anti inflammatory agentsAnti inflammatory agents
Anti inflammatory agents
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
 
ความรู้
ความรู้ความรู้
ความรู้
 
Pengukuran aliran b.(variable area)
Pengukuran aliran b.(variable area)Pengukuran aliran b.(variable area)
Pengukuran aliran b.(variable area)
 
The definitive-guide-to LinkedIn
The definitive-guide-to LinkedInThe definitive-guide-to LinkedIn
The definitive-guide-to LinkedIn
 
Reversting system
Reversting systemReversting system
Reversting system
 
Administrative
AdministrativeAdministrative
Administrative
 
Gym registration - 2014 Apps for Good Entry
Gym registration - 2014 Apps for Good EntryGym registration - 2014 Apps for Good Entry
Gym registration - 2014 Apps for Good Entry
 
Cozen o'connor interview questions and answers
Cozen o'connor interview questions and answersCozen o'connor interview questions and answers
Cozen o'connor interview questions and answers
 
Thrust block
Thrust blockThrust block
Thrust block
 
Tequipalcatalogo
TequipalcatalogoTequipalcatalogo
Tequipalcatalogo
 

Similar to Lecture 1

1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
tarifarmarie
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeks
AashutoshChhedavi
 

Similar to Lecture 1 (20)

Basics1
Basics1Basics1
Basics1
 
Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)
 
C programming languag for cse students
C programming languag for cse studentsC programming languag for cse students
C programming languag for cse students
 
C language tutorial
C language tutorialC language tutorial
C language tutorial
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
The C++ Programming Language
The C++ Programming LanguageThe C++ Programming Language
The C++ Programming Language
 
C Introduction and bascis of high level programming
C Introduction and bascis of high level programmingC Introduction and bascis of high level programming
C Introduction and bascis of high level programming
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
 
Unit 1.1 - Introduction to C.pptx
Unit 1.1 - Introduction to C.pptxUnit 1.1 - Introduction to C.pptx
Unit 1.1 - Introduction to C.pptx
 
Cordovilla
CordovillaCordovilla
Cordovilla
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
 
Learn C# programming - Program Structure & Basic Syntax
Learn C# programming - Program Structure & Basic SyntaxLearn C# programming - Program Structure & Basic Syntax
Learn C# programming - Program Structure & Basic Syntax
 
C# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkC# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net Framework
 
Csphtp1 03
Csphtp1 03Csphtp1 03
Csphtp1 03
 
C programming notes
C programming notesC programming notes
C programming notes
 
Overview of c
Overview of cOverview of c
Overview of c
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
 
C programming notes.pdf
C programming notes.pdfC programming notes.pdf
C programming notes.pdf
 
C language
C language C language
C language
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeks
 

More from Soran University (7)

Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 

Recently uploaded

result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Recently uploaded (20)

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 

Lecture 1

  • 1. An Introduction to C# Lecture 1 Dr. Hakem Beitollahi Computer Engineering Department Soran University
  • 2. Objectives of this lecture  In this chapter you will learn:  To write simple C# applications.  To use input and output statements.  C#’s primitive types.  Basic memory concepts.  To use arithmetic operators.  The precedence of arithmetic operators.  To write decision-making statements.  To use relational and equality operators. An introduction to C#— 2
  • 3. First program in C# An introduction to C#— 3
  • 4. First C# program: printing a line Single-line comments. Left brace { begins function body. Predefined namespace (System)– part of .NET FCL User defined namespace User defined class A blank line Function Main returns nothing (void) and is static Function Main appears exactly once in every C# program.. Corresponding right brace } ends function body. Statements end with a semicolon ;. Console An introduction to C#— 4
  • 5. Elements of a C# Program
  • 6. Anatomy of the first program (I) // First program in C#.  Comments start with: //  Comments ignored during program execution  Document and describe code  Provides code readability  Traditional comments: /* ... */ /* This is a traditional comment. It can be split over many lines */ An introduction to C#— 6
  • 7. Good Programming Practice Tip (1)  Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program Chapter 3: An introduction to C# — 7
  • 8. using Directive  Permits use of classes found in specific namespaces without having to qualify them  Framework class library  Over 2,000 classes included  Syntax  using namespaceIdentifier; An introduction to C#— 8
  • 9. namespace  One of the great strengths of C# is that C# programmers can use the rich set of namespaces provided by the .NET  These namespaces contain code that programmers can reuse  framework.Groups semantically related types under a single umbrella  System: most important and frequently used namespace  An example of one of the features in namespace System is Console  We discuss many namespaces and their features throughout the course. An introduction to C#— 9
  • 10. Blank line  Use blank lines and space characters throughout a program to make the program easier to read.  Collectively, blank lines, space characters, newline characters and tab characters are known as whitespace  The compiler ignores  blank lines, tabs and extra spaces that separate language elements. An introduction to C#— 10
  • 11.  Our first class  C# programs consist of pieces called classes, which are logical groupings of members (e.g., methods) that simplify program organization.  These methods perform tasks and return information when the tasks are completed.  A C# program consists of classes and methods created by the programmer and of preexisting classes found in the Framework Class Library.  Every program in C# consists of at least one class definition that the programmer defines.  The class keyword begins a class definition in C# and is followed immediately by the class name (program) An introduction to C#— 11
  • 12. Identifiers names  By convention, each word in a class name begins with an uppercase first letter and has an uppercase letter for each word in the class name: SampleClassName  Identifiers is a series of characters consisting of letters, digits, underscores ( _ ) and “at” symbols (@).  Identifiers cannot begin with a digit and cannot contain spaces.  The “at” character (@) can be used only as the first character in an identifier  Examples of valid identifiers:  Welcome1, _value, m_inputField1, button7, @value  Examples of invalid identifiers  5welcome, input field, val@, in$put  C# is case sensitive An introduction to C#— 12
  • 13. Common Programming Error (1) C# is case sensitive. Not using the proper case for an identifier, e.g.,writing Total when the identifier is total, is a compiler error. An introduction to C#— 13
  • 14. Good Programming Practice Tip (2)  Always begin a class name with an uppercase first letter. This practice makes class names easier to identify. An introduction to C#— 14
  • 15. Braces { }  The left brace ({) begins the body of the class definition.  The corresponding right brace (}) ends the class definition. An introduction to C# — 15
  • 16. Common Programming Error Tip (2)  If braces do not occur in matching pairs, a syntax error occurs. An introduction to C#— 16
  • 17. Good Programming Practice Tip (3)  When typing an opening left brace ({) in a program, immediately type the closing right brace (}) then reposition the cursor between the braces to begin typing the body. An introduction to C#— 17
  • 18. Good Programming Practice Tip (4)  Indent the entire body of each class definition one “level” of indentation between the left brace ({) and the right brace (}) that delimit the class body. This emphasizes the structure of the class definition and helps make the class definition easier to read. An introduction to C#— 18
  • 19. static void Main(string[] args)  present in all C# console and Windows applications.  These applications begin executing at Main, which is known as the entry point of the program.  The parentheses after Main indicate that Main is a program building block, called a method.  C# class definitions normally contain one or more methods and C# applications contain one or more classes.  For a C# console or Windows application, exactly one of those methods must be called Main  M in Main must be uppercase Administrative — 19
  • 20. The Console  The Console class enables programs to output information to the computer’s standard output.  It provides methods to display strings and other types of information in the Windows command prompt.  Method Console.WriteLine displays (or prints) a line of text in the console window.  When Console.WriteLine completes its task, it positions the output cursor at the beginning of the next line in the console window.  Statement: The entire line, including Console.WriteLine, its argument in the parentheses ("Welcome to C# Programming!") and the semicolon (;)  Every statement must end with a semicolon. Chapter 3: An introduction to C#— 20
  • 21. Common Programming Error Tip (3)  Omitting the semicolon at the end of a statement is a syntax error.  When the compiler reports a syntax error, the error might not be on the line indicated by the error message. First, check the line where the error was reported. If that line does not contain syntax errors, check the lines that precede the one reported. Chapter 3: An introduction to C#— 21
  • 22. Administrative — 22 // Fig. 3.4: Welcome2.cs // Printing a line with multiple statements. using System; class Welcome2 { static void Main( string[] args ) { Console.Write( "Welcome to " ); Console.WriteLine( "C# Programming!" ); } } Console.Write keeps the curse in the last position
  • 23. Modifying the first program (print same contents using different code) An introduction to C#— 23
  • 24. // Fig. 3.5: Welcome3.cs // Printing multiple lines with a single statement. using System; class Welcome3 { static void Main( string[] args ) { Console.WriteLine( "WelcomentonC#nProgramming!" ); } } Notice how a new line is output for each n escape sequence. An introduction to C#— 24
  • 25. Slash Operator (I) An introduction to C#— 25
  • 26. Slash Operator (II) Code Meaning b Backspace n Newline r Carriage return t Horizontal tab v Vertical tab ” Double quote backslash a Beep 26/27
  • 27. The Same Program in Windows Form Style An introduction to C#— 27
  • 28. // Fig. 3.7: Welcome4.cs // Printing multiple lines in a dialog Box. using System; using System.Windows.Forms; class Welcome4 { static void Main( string[] args ) { Class MessageBox is located in assembly System.Windows.Forms MessageBox.Show("WelcomentonC#nprogramming!"); } } An introduction to C#— 28
  • 29. Common Programming Error Tip (4)  Including a namespace with the using directive, but not adding a reference to the proper assembly, results in a compiler error. An introduction to C#— 29
  • 30. Add a reference to your program (I)  To begin, make sure you have an application open. Select the Add Reference… option from the Project menu, or right click the References folder in the Solution Explorer and select Add Reference… from the popup menu that appears. This opens the Add Reference dialog. Double click System.Windows.Forms.dll to add this file to the Selected Components list at the bottom of the dialog, then click OK.  See next slide An introduction to C#— 30
  • 31. Add a reference to your program (II) An introduction to C#— 31
  • 32. GUI EXample An introduction to C#— 32
  • 33. Another Simple Program: Adding Integers An introduction to C#— 33
  • 34. Addition Proggram // Fig. 3.11: Addition.cs // An addition program. using System; class Addition { static void Main( string[] args ) { string firstNumber, // first string entered by user secondNumber; // second string entered by user int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 // prompt for and read first number from user as string Console.Write("Please enter the first integer: "); firstNumber = Console.ReadLine(); // read second number from user as string Console.Write("nPlease enter the second integer: "); secondNumber = Console.ReadLine(); // convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber ); // add numbers sum = number1 + number2; // display results Console.WriteLine( "nThe sum is {0}.", sum ); } // end method Main } //end class Addition Define two string variables to enter numbers Define three integer variables prompt for first number from user as string Read first number from user as string usinf ReadLine method convert numbers from type string to type int using Int32 class and Parse method Add numbers Display result in the screen An introduction to C#— 34
  • 35. Variables  A variable is a location in the computer’s memory where a value can be stored for use by a program.  All variables must be declared with a name and a data type before they can be used in a program.  firstNumber and secondNumber are data of type string, which means that these variables store strings of characters.  Primitive data types: string, int, double and char  int holds integer values (whole numbers): i.e., 0, -4, 97  Types float and double can hold decimal numbers  Type char can hold a single character: i.e., x, $, n, 7  A variable name can be any valid identifier An introduction to C#— 35
  • 36. Good Programming Practice Tip (5)  Choosing meaningful variable names helps a program to be “self-documenting” (i.e., easier to understand simply by reading it, rather than having to read manuals or use excessive comments). An introduction to C#— 36
  • 37. Good Programming Practice Tip (6)  By convention, variable-name identifiers begin with a lowercase letter. As with class names, every word in the name after the first word should begin with a capital letter. For example, identifier firstNumber has a capital N in its second word, Number. An introduction to C#— 37
  • 38. Good Programming Practice Tip (7)  Some programmers prefer to declare each variable on a separate line. This format allows for easy insertion of a comment that describes each variable. An introduction to C#— 38
  • 39. Prompt Console.Write("Please enter the first integer: "); firstNumber = Console.ReadLine();  prompt the user to input an integer and read from the user a string representing the first of the two integers that the program will add.  It is called a prompt, because it directs the user to take a specific action.  Method ReadLine causes the program to pause and wait for user input.  The user inputs characters from the keyboard, then presses the Enter key to return the string to the program. An introduction to C#— 39
  • 40. Convert string to int // convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber );  Method Int32.Parse converts its string argument to an integer.  Class Int32 is part of the System namespace.  assign the integer that Int32.Parse returns to variable number1.  The = operator is a binary operator An introduction to C#— 40
  • 41. Good Programming Practice Tip (7) Place spaces on either side of a binary operator. This makes the operator stand out and makes the program more readable. An introduction to C#— 41
  • 42. Sum // add numbers sum = number1 + number2;  calculates the sum of the variables number1 and number2 and assigns the result to variable sum by using the assignment operator =. An introduction to C#— 42
  • 43. Display results (I) // display results Console.WriteLine( "nThe sum is {0}.", sum );  It displays the result of the addition  we want to output the value in a variable using method WriteLine  use {0} to indicate a placeholder for a variable’s value.  Suppose sum =117, the resulting string will be “The sum is 117.” An introduction to C#— 43
  • 44. Display results (II) Console.WriteLine("The numbers entered are {0} and {1}", number1, number2);  the value of number1 would replace {0} (because it is the first variable) and the value of number2 would replace {1} (because it is the second variable).  The resulting string would be "The numbers entered are 45 and 72".  More formats can be used ({2}, {3} etc.) if there are more variables to display in the string. An introduction to C#— 44
  • 45. Good Programming Practice Tip (8)  Place a space after each comma in a method’s argument list to make programs more readable. An introduction to C#— 45
  • 46. Good Programming Practice Tip (9)  Follow the closing right brace (}) of the body of a method or class definition with a singleline comment. This comment should indicate the method or class that the right brace terminates. An introduction to C#— 46
  • 47. Memory Concepts An introduction to C#— 47
  • 48. Memory Concepts Number 1: 45 Number 2: 72 Sum: 117 MMememoroyr ylo lcoactaiotinosn sa fateftre sr tcoarilncgu lavatinluge sa nfodr sntourminbge trh1e a snudm n uomf nbuemr2b.er1 and number2. Memory location showing the name and value of variable number1. An introduction to C#— 48
  • 50. Arithmetic Operations (I) An introduction to C#— 50
  • 51. Arithmetic Operations (II)  Be careful!  5 / 2 yields an integer 2  5.0 / 2 yields a double value 2.5  Remainder can be very useful  Even numbers % 2 = 0  Today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? Saturday is the 6th day in a week A week has 7 days After 10 days The 2nd day in a week is Tuesday (6 + 10) % 7 is 2 An introduction to C#— 51
  • 52. Arithmetic (III)  Operators have precedence  Some arithmetic operators act before others (i.e., multiplication before addition)  Use parenthesis when needed  Example: Find the average of three variables a, b and c  Do not use: a + b + c / 3  Use: ( a + b + c ) / 3 An introduction to C#— 52
  • 53. Arithmetic (IV) An introduction to C#— 53
  • 54.  Operators have precedence 1. Parentheses () 2. *, /, % 3. +,- 4. … 3 + 4 * 4 + 5 * (4 + 3) – 1 3 + 4 * 4 + 5 * 7 – 1 3 + 16 + 5 * 7 – 1 3 + 16 + 35 – 1 19 + 35 – 1 54 – 1 53 in side parenthesis first multiplication multiplication addition addition subtraction An introduction to C#— 54 Arithmetic (V)
  • 55. Algebra: z = pr%q + w/x – y C#: z = p * r % q + w / x - y; 1 2 3 4 5 6 An introduction to C#— 55 Arithmetic (VI)
  • 56.  Test yourself  y = a * x * x + b * x + c;  Y = a+b/(a%5)-a%a*3; (a= 7, b = 3) An introduction to C#— 56
  • 57. Decision Making An introduction to C#— 57
  • 58. Decision Making: Equality and Relational Operators (I)  Condition  Expression can be either true or false  if statement  Simple version in this section, more detail later  If a condition is true, then the body of the if statement executed  Control always resumes after the if statement  Conditions in if statements can be formed using equality or relational operators (next slide) An introduction to C#— 58
  • 59. Decision Making: Equality and Relational Operators (II) An introduction to C#— 59
  • 60. Common Programming Error Tip (5) It is a syntax error if the operators ==, !=, >= and<= contain spaces between their symbols (as in = =, ! =, > =, < =). An introduction to C#— 60
  • 61. Common Programming Error Tip (6)  Reversing the operators !=, >= and <= (as in =!, => and =<) is a syntax error. An introduction to C#— 61
  • 62. Common Programming Error Tip (7)  Confusing the equality operator == with the assignment operator = is a logic error. The equality operator should be read “is equal to,” and the assignment operator should be read “gets” or “gets the value of.” Some people prefer to read the equality operator as “double equals” or “equals equals.” An introduction to C#— 62
  • 63. // Fig. 3.19: Comparison.cs // Using if statements, relational operators and equality operators. using System; class Comparison { static void Main( string[] args ) { int number1, // first number to compare number2; // second number to compare Directly get string and convert to int // read in first number from user Console.Write("Please enter first integer: "); number1 = Int32.Parse(Console.ReadLine()); // read in second number from user Console.Write("nPlease enter second integer: "); number2 = Int32.Parse(Console.ReadLine()); if (number1 == number2) Console.WriteLine(number1 + " == " + number2); if (number1 != number2) Console.WriteLine(number1 + " != " + number2); if (number1 < number2) Console.WriteLine(number1 + " < " + number2); if (number1 > number2) Console.WriteLine(number1 + " > " + number2); if (number1 <= number2) Console.WriteLine(number1 + " <= " + number2); if ( number1 >= number2 ) If condition is true (i.e., values are equal), execute this statement. Console.WriteLine( number1 + " >= " + number2 ); }// end method Main } // end class Comparison if structure compares values of num1 and num2 to test for equality. if structure compares values If condition is true (i.e., values are not equal), execute this statement. of num1 and num2 to test for inequality. An introduction to C#— 63
  • 64. Console.WriteLine(number1 + " == " + number2);  This expression uses the operator + to “add” (or combine) numbers and strings.  C# has a version of the + operator used for string concatenation.  Concatenation is the process that enables a string and a value of another data type (including another string) to be combined to form a new string. An introduction to C#— 64
  • 65. Common Programming Error Tip (8)  Confusing the + operator used for string concatenation with the + operator used for addition can lead to strange results  Assume y = 5;  The expression "y + 2 = " + y + 2 results in the string "y + 2 = 52“ and not "y + 2 = 7".  The expression "y + 2 = " + (y + 2) results in "y + 2 = 7“ An introduction to C#— 65
  • 66. Common Programming Error Tip (9)  Replacing operator == in the condition of an if structure, such as if ( x == 1 ), with operator =, as in if ( x = 1 ), is a logic error. if (number1 = number2) Console.WriteLine(number1 + " == " + number2); An introduction to C#— 66
  • 67. Common Programming Error Tip (10)  Forgetting the left and right parentheses for the condition in an if structure is a syntax error. The parentheses are required. if number1 == number2 Console.WriteLine(number1 + " == " + number2); An introduction to C#— 67 ( )
  • 68. Common Programming Error Tip (11)  There is no semicolon (;) at the end of the first line of each if structure. It is Syntax error. If takes no action.  Example: if (number1 == number2); Console.WriteLine(number1 + " == " + number2); An introduction to C#— 68
  • 69. Good Programming Practice Tip (10)  Place only one statement per line in a program. This enhances program readability. An introduction to C#— 69
  • 70. Good Programming Practice Tip (11)  A lengthy statement may be spread over several lines.  In case of splitting, choose breaking points that make sense,  after a comma in a comma separated list  after an operator in a lengthy expression.  Indent all subsequent lines with one level of indentation.  Example: int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 An introduction to C#— 70
  • 71. Good Programming Practice Tip (12)  Confirm that the operators in the expression are performed in the expected order.  If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order  assignment (=), associate from right to left rather than from left to right.  Example y = a * x * x + b * x + c; y = (a * x * x) + (b * x) + c; y = x; it means that x is assigned into y An introduction to C#— 71
  • 72. HomeWork  First Homework  Write a program in C# that print your name with stars (*) in the screen * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Deadline: Next week * * * * * * * * * * * * * * * * * An introduction to C#— 72