Title: Advanced Programming
1Advanced Programming
C Introduction
2Application Types
- Console Application
- Has standard streams (out, in, err)
- GUI can be added manually
- Windows Application
- GUI based
- No standard streams (out, in, err)
- Main thread is shared by the GUI message pump
your code - Service
- No standard streams (out, in, err)
- Main thread is commandeered by the SCM
- No GUI
3Start Visual Studio
4New Project
5Windows Application
6Simple Program console application
// A first program in C. using System class
Welcome1 static void Main( string args
) Console.WriteLine( "Welcome to C
Programming!" )
7Constructions of Note
- using
- like import in Java bring in namespaces
- namespace
- disambiguation of names
- like Internet hierarchical names and C naming
- class
- like in C or Java
- single inheritance up to object
8Constructions of Note
- static void Main()
- Defines the entry point for an assembly.
- Four different overloads taking string
arguments and returning ints. - Console.Write(Line)
- Takes a formatted string Composite Format
- Indexed elements e.g., 0
- can be used multiple times
- only evaluated once
- index ,alignmentformatting
9Common Type System (CTS)
From MSDN
10Atomic Data
11Simple Program Add Integers
- Primitive data types
- Data types that are built into C
- string, int, double, char, long
- 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
12Built-in Types
- C predefined types
- The root object
- Logical bool
- Signed sbyte, short, int, long
- Unsigned byte, ushort, uint, ulong
- Floating-point float, double, decimal
- Textual char, string
- Textual types use Unicode (16-bit characters)
13Types Unified Type System
- Value types
- Directly contain data
- Cannot be null
- Reference types
- Contain references to objects
- May be null
int i 123 string s "Hello world"
14Programs
- Write a C program to read three integer numbers
and find their average.
15Predefined TypesValue Types
- All are predefined structs
Signed sbyte, short, int, long
Unsigned byte, ushort, uint, ulong
Character char
Floating point float, double, decimal
Logical bool
16Predefined TypesIntegral Types
C Type System Type Size (bytes) Signed?
sbyte System.Sbyte 1 Yes
short System.Int16 2 Yes
int System.Int32 4 Yes
long System.Int64 8 Yes
byte System.Byte 1 No
ushort System.UInt16 2 No
uint System.UInt32 4 No
ulong System.UInt64 8 No
17Predefined TypesFloating Point Types
- Follows IEEE 754 specification
- Supports 0, Infinity, NaN
C Type System Type Size (bytes)
float System.Single 4
double System.Double 8
18Predefined Typesdecimal
- 128 bits
- Essentially a 96 bit value scaled by a power of
10 - Decimal values represented precisely
- Doesnt support signed zeros, infinities or NaN
C Type System Type Size (bytes)
decimal System.Decimal 16
19Predefined Typesbool
- Represents logical values
- Literal values are true and false
- Cannot use 1 and 0 as boolean values
- No standard conversion between other types and
bool
C Type System Type Size (bytes)
bool System.Boolean 1 (2 for arrays)
20Predefined Typeschar
- Represents a Unicode character
- Literals
- A // Simple character
- \u0041 // Unicode
- \x0041 // Unsigned short hexadecimal
- \n // Escape sequence character
C Type System Type Size (bytes)
Char System.Char 2
21Predefined Typesstring
- An immutable sequence of Unicode characters
- Reference type
- Special syntax for literals
- string s I am a string
C Type System Type Size (bytes)
String System.String 20 minimum
22Type System
- Value types
- Primitives int i
- Enums enum State Off, On
- Structs struct Point int x, y
- Reference types
- Classes class Foo Bar, IFoo ...
- Interfaces interface IFoo IBar ...
- Arrays string a new string10
- Delegates delegate void Empty()
23Example
- Assume you work for the Alexandria Electricity
company and you need a program to help you
calculate the electricity bill for each customer.
The program input should be the old meter
reading and the new meter reading. Given that the
price is 0.10 pounds per kilowatt.
24Program StructureMain Method
- Execution begins at the static Main() method
- Can have only one method with one of the
following signatures in an assembly - static void Main()
- static int Main()
- static void Main(string args)
- static int Main(string args)
25C
- Comments
- Comments can be created using //
- Multi-lines comments use / /
- Comments are ignored by the compiler
26Program StructureSyntax
- Identifiers
- Names for types, methods, fields, etc.
- Must be whole word no white space
- Unicode characters
- Begins with letter or underscore
- Case sensitive
- Must not clash with keyword
- Unless prefixed with _at_
27Identifiers Keywords
- Often we use special identifiers called keywords
that already have a predefined meaning in the
language - Example class
- A keyword cannot be used in any other way
All C keywords are lowercase!
28Arithmetic
- Arithmetic operations
- Asterisk () is multiplication
- Slash (/) is division
- Percent sign () is the modulus operator
- Plus () and minus (-) are the same
- There are no exponents
29OperatorsAssociativity
- Assignment and ternary conditional operators are
right-associative - Operations performed right to left
- x y z evaluates as x (y z)
- All other binary operators are left-associative
- Operations performed left to right
- x y z evaluates as (x y) z
- Use parentheses to control order
30C
- Keywords
- Words that cannot be used as variable or class
names - Have a specific unchangeable function within the
language - Example class
31C 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 (_at_)
32C Class
- 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
33C Statements
- Anything in quotes () is considered a string
- Every statement must end in a semicolon ()
34C
35NameSpaces
- You import namespaces when you want to be able to
refer to classes by their short name, rather than
full name - For example, import System.XML allows
XmlDataDocument and XmlNode rather than
System.XML.XmlDataDocument and System.XML.XmlNode
to be in your code.
36Program StructureNamespaces
namespace N1 // N1 class C1 //
N1.C1 class C2 // N1.C1.C2
namespace N2 // N1.N2 class C2
// N1.N2.C2
37Program StructureNamespaces
- The using statement lets you use types without
typing the fully qualified name - Can always use a fully qualified name
using N1 C1 a // The N1. is implicit N1.C1
b // Fully qualified name C2 c // Error! C2
is undefined N1.N2.C2 d // One of the C2
classes C1.C2 e // The other one
38Program StructureNamespaces
- Best practice Put all of your types in a unique
namespace - Have a namespace for your company, project,
product, etc. - Look at how the .NET Framework classes are
organized
39Namespaces
- Partition the name space to avoid name conflict!
- All .NET library code are organized using
namespaces! - By default, C code is contained in the global
namespace - To refer to code within a namespace, must use
qualified name (as in System.Console) or import
explicitly (as in using System )
using System class HelloWorld static void
Main(string args) Console.WriteLine(He
llo World!)
class HelloWorld static void Main(string
args) System.Console.WriteLine(Hello
World!)
40Welcome4.cs
- // Printing multiple lines in a dialog Box.
- using System
- using System.Windows.Forms
- class Welcome4
-
- static void Main( string args )
-
- MessageBox.Show( "Welcome \n to \n C \n
programming!" )
41StatementsOverview
- Loop Statements
- while
- do
- for
- foreach
- Jump Statements
- break
- continue
- goto
- return
- throw
- Exception handling
- try
- throw
- Statement lists
- Block statements
- Labeled statements
- Declarations
- Constants
- Variables
- Expression statements
- checked, unchecked
- lock
- using
- Conditionals
- if
- switch
42StatementsExpression Statements
- Statements must do work
- Assignment, method call, , --, new
static void Main() int a, b 2, c 3 a
b c a Console.WriteLine(a b c) a
2 // ERROR!
43Events
- Events are a way for an object to communicate
with those that are interested in what it has to
offer, like a button has a click event - Interested parties use Event Handlers, which are
a way of subscribing to the event
44 Math Class Methods
- The Math class
- Allows the user to perform common math
calculations - Using methods
- ClassName.MethodName( argument1, arument2, )
- Constants
- Math.PI 3.1415926535
- Math.E 2.7182818285
45Math Class Methods
46Example
- A motor car uses 8 liters of fuel per 100 km on
normal roads and 15 more fuel on rough roads.
Write a program to print out the distance the car
can travel on full tank of 40 liters of fuel on
both normal and rough roads.
47StatementsVariables and Constants
static void Main() const float pi 3.14f
const int r 123 Console.WriteLine(pi r
r) int a int b 2, c 3 a 1
Console.WriteLine(a b c)
48Example
- Write a program to ask you for the temperature in
Fahrenheit and then convert it to Celsius. Given - C 5/9 (F-32)
- Write a program to ask you for the temperature in
Celsius and then convert it to Fahrenheit.
49Programs
- Write a program to ask a person for his height in
feet and inches and then tell them his height in
cms. Given that 1 foot 30 cms and 1 inch 2.5
cms.
50Examples
- Write a program to ask the user for the width and
length of a piece of land and then tell him how
many orange trees he can grow on it. Given that
each orange tree requires 4 m2.
51Examples
- Write a program to ask the user for the radius of
a circle, and then display its area and
circumference.