Topic 1 Introduction to C#
Programming
Outline
1.1
1.2
1.1
1.4
1.5
1.6
Introduction
Simple Program: Printing a Line of Text
Another Simple Program: Adding Integers
Memory Concepts
Arithmetic
Decision Making: Equality and Relational Operators
2001 Prentice Hall, Inc. All rights reserved.
1.1 Introduction
Console applications
No visual components
Only text output
Two types
MS-DOS prompt
Used in Windows 95/98/ME
Command prompt
Used in windows 2000/NT/XP
Windows applications
Forms with several output types
Contain Graphical User Interfaces (GUIs)
2001 Prentice Hall, Inc. All rights reserved.
1.2 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
2001 Prentice Hall, Inc. All rights reserved.
1.2 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
All keywords are lowercase
Classes
Class names can only be one word long (i.e. no white space in
class name )
Class names are capitalized, with each additional English word
capitalized as well (e.g., MyFirstProgram )
Each class name is an identifier
Can contain letters, digits, and underscores (_)
Cannot start with digits
Can start with the at symbol (@)
2001 Prentice Hall, Inc. All rights reserved.
1.2 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
Anything in quotes () is considered a string
Every statement must end in a semicolon (;)
2001 Prentice Hall, Inc. All rights reserved.
1.2 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
2001 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 1.1: Welcome1.cs
// A first program in C#.
using System;
Outline
These
are
two single
line comments.
This
is
aathe
string
ofdirective.
characters
This
is
blank
using
line.
It
means
It that
lets and
They
are
ignored
by
the
compiler
Console.WriteLine
instructs
This
is the
start
beginning
of the
of
Main
the
Welcome1
method.
class
the only
nothing
compiler
to
the
know
compiler
that
itand
should
istheonly Welcome1.cs
are
used
to
aid
other
programmers.
compiler
toItSystem
definition.
In
thistocase
itoutput
starts
instructs
with
the
the
program
class keyword
include
used
add
the
namespace.
the
program.
They
use
theclarity
doubleto
slash
(//)
anddothen
to
everything
the name of the class.
class Welcome1
{
static void Main( string[] args )
{
Console.WriteLine( "Welcome to C# Programming!" );
}
}
Program Output
Welcome to C# Programming!
2001 Prentice Hall, Inc.
All rights reserved.
1.2 Simple Program: Printing a Line of Text
Fig. 1.2
Visual Studio .NET-generated console application.
2001 Prentice Hall, Inc. All rights reserved.
1.2 Simple Program: Printing a Line of Text
Fig. 1.1
Execution of the Welcome1 program.
2001 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
Outline
// Fig. 1.4: Welcome2.cs
// Printing a line
with multiple statements.
Console.WriteLine
will pick up
using System;
where the
line ends. This will cause the output to be on
one line even though it is on two in the code.
Welcome2.cs
class Welcome2
{
static void Main( string[] args )
{
Console.Write( "Welcome to " );
Console.WriteLine( "C# Programming!" );
}
}
Welcome to C# Programming!
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
10
1
2
3
4
5
6
7
8
9
10
11
12
Outline
// Fig. 1.5: Welcome1.cs
The with
\n escape
sequence
is used to
// Printing multiple lines
a single
statement.
using System;
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.
Welcome1.cs
class Welcome1
{
static void Main( string[] args )
{
Console.WriteLine( "Welcome\nto\nC#\nProgramming!" );
}
}
Welcome
to
C#
Programming!
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
11
12
1.2 Simple Program: Printing a Line of Text
Escape sequence Description
\n
Newline. Position the screen cursor to the beginning of the
next line.
\t
Horizontal tab. Move the screen cursor to the next tab stop.
\r
Carriage return. Position the screen cursor to the beginning
of the current line; do not advance to the next line. Any
characters output after the carriage return overwrite the
previous characters output on that line.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double quote (") character.
Fig. 3.6 Some common escape sequences.
2001 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
Outline
// Fig. 1.7: Welcome4.cs
// Printing multiple lines in a dialog
Box.
The System.Windows.Forms
namespace allows the programmer
This will display the contents in a message
using System;
to use the
MessageBox
using System.Windows.Forms;box as opposed
to in
the consoleclass.
window.
Welcome4.cs
class Welcome4
{
static void Main( string[] args )
{
MessageBox.Show( "Welcome\nto\nC#\nprogramming!" );
}
}
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
13
14
1.2 Simple Program: Printing a Line of Text
Add
Reference
dialogue
Fig. 1.8
Adding a reference to an assembly in Visual Studio .NET (part 1).
2001 Prentice Hall, Inc. All rights reserved.
15
1.2 Simple Program: Printing a Line of Text
Solution Explorer
System.Windows.Forms
reference
References folder
Fig. 1.8
Adding a reference to an assembly in Visual Studio .NET (part 2).
2001 Prentice Hall, Inc. All rights reserved.
16
1.2 Simple Program: Printing a Line of Text
Label
Fig. 1.9
Button
Text field
Internet Explorers GUI.
2001 Prentice Hall, Inc. All rights reserved.
Menu
Menu bar
17
1.2 Simple Program: Printing a Line of Text
OK button allows the
user to dismiss the
dialog.
Close box
Dialog is automatically sized
to accommodate its contents.
Mouse cursor
Fig. 1.10 Dialog displayed by calling MessageBox.Show.
2001 Prentice Hall, Inc. All rights reserved.
1.1 Another Simple Program: Adding
Integers
Primitive data types
Data types that are built into C#
String, Int, Double, Char, Long
15 primitive data types (chapter 4)
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
Int12.Parse()
Used to convert a string argument to an integer
Allows math to be preformed once the string is converted
2001 Prentice Hall, Inc. All rights reserved.
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 1.11: Addition.cs
// An addition program.
This is the start of class Addition
Outline
using System;
Two stringThe
variables
comment after the
Addition.cs
defined over
declaration
two linesis used to briefly
class Addition
{
state the variable purpose
These areargs
three) ints that are declared
static void Main( string[]
{
over several lines and only use one
string firstNumber,
// first string entered by user
semicolon.
Each is
separated
coma.
Thisentered
linebyisaconsidered
secondNumber; // second
string
by user a prompt
because it asks the user to input data.
int number1,
number2,
sum;
// first number to add
// second number to add
// 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();
Int12.Parse is used to convert the
The two numbers are added
givenasstring
into an integer. It is
readinsecond
number
from user
string
and //
stored
the variable
sum.
Console.Write( "\nPlease enter
the
second
then stored in a integer:
variable. " );
secondNumber = Console.ReadLine();
// convert numbers from type string to type int
number1 = Int12.Parse( firstNumber );
number2 = Int12.Parse( secondNumber );
// add numbers Console.ReadLine
sum = number1 + number2;
is used to take the
users input and place it into a variable.
2001 Prentice Hall, Inc.
All rights reserved.
19
32
31
34
35
36
37
Outline
// display results
Console.WriteLine( "\nThe sum is {0}.", sum );
} // end method Main
Addition.cs
} // end class Addition
Please enter the first integer: 45
Program Output
Please enter the second integer: 72
The sum is 117.
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.
2001 Prentice Hall, Inc.
All rights reserved.
20
21
TAKING NON-NUMERIC DATA FROM
KEYBOARD INTO CONSOLE APPLICATION
ReadLine () function works similar to scanf ()
function. Waits for the user until an input is given
from the keyboard
Write () and WriteLine () functions work similar
to printf () function
2001 Prentice Hall, Inc. All rights reserved.
22
TASK
Create console application in C# that prompt to
enter user name from keyboard.
2001 Prentice Hall, Inc. All rights reserved.
23
SOLUTION
2001 Prentice Hall, Inc. All rights reserved.
24
TAKING NUMERIC DATA IN CONSOLE
APPLICATION
ReadLine () function returns a string, so in case
we want to work with an integer number we have
to convert the string to integer by using
Convert.ToInt16 (string). According to the
integers size you can also use ToInt32, ToInt64
etc.
2001 Prentice Hall, Inc. All rights reserved.
25
TASK
Write a console application in C# that input user
age and display it.
2001 Prentice Hall, Inc. All rights reserved.
26
SOLUTION
2001 Prentice Hall, Inc. All rights reserved.
27
1.4 Memory Concepts
Memory locations
Each variable is a memory location
Contains name, type, size and value
When a new value is enter the old value is lost
Used variables maintain their data after use
2001 Prentice Hall, Inc. All rights reserved.
28
1.4 Memory Concepts
number1
45
Fig. 1.12 Memory location showing name and value of variable number1.
2001 Prentice Hall, Inc. All rights reserved.
29
1.5 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 (-) are the same
Must be written in a straight line
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
2001 Prentice Hall, Inc. All rights reserved.
30
1.5 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
2001 Prentice Hall, Inc. All rights reserved.
31
1.4 Memory Concepts
number1
45
number2
72
Fig. 1.11 Memory locations after values for variables number1 and number2 have been input.
2001 Prentice Hall, Inc. All rights reserved.
32
1.4 Memory Concepts
number1
45
number2
72
sum
117
Fig. 1.14 Memory locations after a calculation.
2001 Prentice Hall, Inc. All rights reserved.
33
1.5 Arithmetic
C# operation
Arithmetic operator
C# expression
Addition
f+7
f + 7
Subtraction
pc
p - c
Multiplication
bm
Division
x / y or
x / y
Modulus
r mod s
r % s
Fig. 3.15 Arithmetic operators.
Algebraic expression
2001 Prentice Hall, Inc. All rights reserved.
x
y
b * m
34
1.5 Arithmetic
Operator(s)
( )
Operation
Parentheses
*, / or %
Multiplication
Division
Modulus
Addition
Subtraction
+ or -
Fig. 3.16
Order of evaluation (precedence)
Evaluated first. If the parentheses are nested,
the expression in the innermost pair is
evaluated first. If there are several pairs of
parentheses on the same level (i.e., not
nested), they are evaluated left to right.
Evaluated second. If there are several such
operators, they are evaluated left to right.
Evaluated last. If there are several such
operators, they are evaluated left to right.
Precedence of arithmetic operators.
2001 Prentice Hall, Inc. All rights reserved.
35
1.5 Arithmetic
Step1.
y=2*5*5+1*5+7;
2*5is10(Leftmostmultiplication)
Step2.
y=10*5+1*5+7;
10*5is50(Leftmostmultiplication)
Step1.
Step4.
y=50+1*5+7;
1*5is15(Multiplicationbeforeaddition)
y=50+15+7;
50+15is65(Leftmostaddition)
Step5.
y=65+7;
65+7is72(Lastaddition)
Step6. y=72;(Lastoperationplace72intoy)
Fig. 1.17 Order in which a second-degree polynomial is evaluated.
2001 Prentice Hall, Inc. All rights reserved.
1.6 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
The start of an if statement should not end in a semicolon
(;)
Fig. 1.18 lists the equality and rational operators
There should be no spaces separating the operators
2001 Prentice Hall, Inc. All rights reserved.
36
1.6 Decision Making: Equality and
Relational Operators
Standard
C# equality
algebraic
or relational
equality
operator
operator or
relational
operator
Equality operators
==
!=
Relational operators
>
>
<
<
>=
Example
of C#
condition
x <= y
Fig. 3.18
<=
x
x
x
x
x
== y
!= y
x is equal to y
x is not equal to y
> y
< y
>= y
x is greater than y
x is less than y
x is greater than or equal to
y
x is less than or equal to y
Equality and relational operators.
2001 Prentice Hall, Inc. All rights reserved.
Meaning of
C# condition
37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Outline
// Fig. 1.19: Comparison.cs
// Using if statements, relational operators and equality
// operators.
Comparison.cs
using System;
class Comparison
{
static void Main( string[] args )
{
int number1,
// first number to compare
number2;
// second number to compare
// read in first number from user
Console.Write( "Please enter first integer: " );
number1 = Int12.Parse( Console.ReadLine() );
read in
second
from user
If //
number1
is the
samenumber
as
Console.Write( "\nPlease enter second integer: " );
number2
line is preformed
number2this
= Int12.Parse(
Console.ReadLine()
Combining these);two methods eliminates
If number1 does not equal
the number2
need for a temporary string variable.
if ( number1 == number2 )
thisIfline
of code
executed.
number1
is is
less
than number2
Console.WriteLine(
number1
+ " == " + number2 );
the program will use this line
if ( number1 != number2 If
) number1 is greater than number2
Console.WriteLine( number1
" !=be" preformed
+ number2 );
this line+ will
if ( number1 < number2 )
Console.WriteLine( number1 + " < " + number2 );
if ( number1 > number2 )
Console.WriteLine( number1 + " > " +
number2 );
2001 Prentice Hall, Inc.
All rights reserved.
38
14
15
16
17
18
19
40
41
42
Outline
if ( number1 <= number2 )
Console.WriteLine( number1 + " <= " + number2 );
if ( number1 >= number2 )
Console.WriteLine( number1 + " >= " + number2 );
Comparison.cs
} // end method Main
} // end class Comparison
Please enter first integer: 2000
Please enter second integer: 1000
2000 != 1000
2000 > 1000
2000 >= 1000
If number1 is less than or equal to
Lastly then
if number1
is greater
number2
this code
will be used
than or equal to number2 then
this code will be executed
Program Output
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
2001 Prentice Hall, Inc.
All rights reserved.
39
40
TASK
Write a program in C# that takes a name as input
which should be 10 characters long. If not then it
will display an error message.
2001 Prentice Hall, Inc. All rights reserved.
41
SOLUTION
2001 Prentice Hall, Inc. All rights reserved.
1.6 Decision Making: Equality and
Relational Operators
Operators
()
* / %
+ < <= > >=
== !=
=
Associativity
left to right
left to right
left to right
left to right
left to right
right to left
Type
parentheses
multiplicative
additive
relational
equality
assignment
Fig. 3.20 Precedence and associativity of operators discussed in this
chapter.
2001 Prentice Hall, Inc. All rights reserved.
42