Quick C - PowerPoint PPT Presentation

1 / 52
About This Presentation
Title:

Quick C

Description:

Declares two variables as 32-bit, signed integer values. ... Arrays can also be 'jagged'. int[ ][ ] AnArray; AnArray = new int[3][ ]; AnArray[0]=new int[10] ... – PowerPoint PPT presentation

Number of Views:42
Avg rating:3.0/5.0
Slides: 53
Provided by: gtho6
Category:
Tags: jagged | quick

less

Transcript and Presenter's Notes

Title: Quick C


1
Quick C Rules Best to Memorize
1. C is CASE SENSITIVE int i 6 int I
9 txtOutput.Text "I is " I.ToString()
"\r\n" "i is " i.ToString() Declares
two variables as 32-bit, signed integer values.
They are NOT the same variables.
2
Quick Rules on C Best to Memorize
2. Every C statement must be terminated by a
int i 6 int I 9 txtOutput.Text
"I is " I.ToString() "\r\n" "i is
" i.ToString() int I 6 must be terminated
with a
3
Quick Rules on C Best to Memorize
3. When calling a method in C, parentheses must
be used Even if there are no parameters to pass
to the method. int i 6 int I
9 MessageBox.Show("I is " I.ToString "\n"
"i is " i.ToString()) Build error
because I.ToString is missing required () pair
4
A C Program is structured as Program File
F1.cs File F2.cs File Fn.cs namespace NS1
namespace NS1 namespace NSn class
C1 class C2 class C3
If there is no namespace specified, the classes
are contained in anonymous default
namespace. Namespaces may also contain structs,
interfaces, enums and delegates Namespaces may be
used in other files.
5
C Predefined Types
  • Reference Types
  • object and string
  • Value Types
  • integral sbyte, short, int, long, byte,
    ushort, uint and ulong
  • floating point float and double
  • other bool, char and double

6
C Integer Types
7
C Floating Point Types
8
decimal type
type decimal alias for System.Decimal occupies
128 bits (16 bytes) of memory represents 28 - 29
significant digits range is 1.0  10-28 to
7.9x1028 suffix is M or m
9
Other Predefined Types
bool represents the values true and false bool
isDefined false char represents a 16 bit
Unicode character char oneChar 'h' string
represents text, a series of Unicode
characters string oneLine "one line of
output\r\n" object the ultimate base type of
all other types object onject1
"abcdefgh" object object2 txtOutput
10
Widening/Narrowing
Consider the code int i 10 long j j
i Can this cause a problem? (i.e., is there any
value of i that cannot be assigned to j without
loss of accuracy?)
11
Widening/Narrowing
Consider the code int i long j i
Convert.ToInt32(txtInput.Text) j i Can this
cause a problem? (i.e., is there any value of i
that cannot be assigned to j without loss of
accuracy?) No. Any 32 bit, signed integer
values can be stored as a 64 bit, signed integer
value without any possibility of losing accuracy.
12
Widening/Narrowing
Consider the code int i long j j
Convert.ToInt64(txtInput.Text) i j Can this
cause a problem? (i.e., is there any value of j
that cannot be assigned to i without loss of
accuracy?)
13
Widening/Narrowing
Consider the code int i long j, lngValue //
assign a value to lngValue j lngValue i
j Can this cause a problem? (i.e., is there any
value of j that cannot be assigned to i without
loss of accuracy?) Yes. Try int i long j,
lngValue // assign a value to lngValue j
lngValue i j Assigning an Int64 value to an
Int32 variable is narrowing.
14
Widening/Narrowing cont.
Whenever the C compiler detects widening, it
will implicitly generate the necessary code to
convert the value from the first type to the
second. So, the first example works. Whenever
the C compiler detects narrowing, it will
generate the build error message Cannot
implicitly convert type t1 to t2. The second
example fails with this build error on the
statement i j You must explicitly cast the
value being narrowed as in int i long j,
lngValue // assign a value to lngValue i
(int)j
15
Implicit Casting
When a value would be widened, C automatically
generates the code to convert the value from the
more narrow to the wider type/ This is called
Implicit Casting. You can rely on implicit
casting to convert values as shown
below double float long int short sbyte
ulong uint ushort byte
char
16
Explicit Casting
Whenever the conversion would narrow the value,
you must explicitly cast values of one type to
the desired type. int i 500 long k short
j byte n float a 6f double b 3.2D decimal
c 22.45M k (long) c j (short) a n
(byte)i txtOutput.Text "int i is "
i.ToString() "\r\n" "long k is "
k.ToString() "\r\n" "short j is "
j.ToString() "\r\n" "byte n is "
n.ToString() "\r\n" "float a is "
a.ToString() "\r\n" "double b is "
b.ToString() "\r\n" "decimal c is "
c.ToString()
17
C Operators
Arithmetic addition - subtraction multipli
cation / division modulus (remainder) These
operators are binary. (They must have two
operands.) Avaluation depends on the operand
types. If these are different, the less precise
is implicitly cast to the more precise. For
example. int ii 4 float b 3.75f b b
ii // implicitly converted to b b
(float)ii
18
Operators - Exponentiation
VB int I 2 5 assigns the value 32 to I The
C operator does not raise to a power. To
exponentiate, you should use the Math.Pow()
method int I (int)Math.Pow((double)2,
(double)5) The parameters expected by the Pow()
method must both be double. The result returned
by the method is also double. The cast (int)
above is required. The other casts are not
required. (If you omit them, C will implicitly
cast the parameter values to type double for you.)
19
Try This
int i int j int k float a float b i 98 /
11 a 98 / 11 b 98F / 11 i 98 / 3
3 // breakpoint here j (int)(98/3 3F) k
(int)(98F / 3 3) Type of arithmetic
determined by types of operand(s).
20
C Operators
-- int i 7, j 3, k -4 // Declare
Initialize vars k // Increment
k --k // Decrement k i j k // Use
value then increment i j k //
Increment then use value - /
int i 7, j 3, k -4 k 1 //
same as k k 1 k - 1 // same as k k -
1 k i // same as k k 1 k /
j // same as k k / 1 k j // same as
k k 1
21
Arrays
One dimensional arrays. int a //
Declare array a new int5 // Instantiate
(create) // Declare Instantiate in one
statement float S new float10 //
Declare, Instantiate and Initialize string
Days "Sun","Mon","Tue,"Wed","Thu","Fri","Sat"
object SomeThing new object20
SomeThing0 0 // Assign values to first
three elements SomeThing0 "A string of
characters" SomeThing1 .475F SomeThing2
button1
22
MultiDimension Arrays
Arrays can be rectangular int,
AnArray AnArray new int3,5 for (int i
0 i lt 3 i) for (int j 0 j lt 5
j) AnArrayi, j (i2) (j -
3)
23
MultiDimension Arrays
Arrays can also be jagged. int
AnArray AnArray new int3
AnArray0new int10 AnArray1 new
int50 AnArray2 new int4
24
MultiDimension Arrays
You can even do something such as (but
why?) int a a new int5
a0 new int10 a00
new int15 for (int i 0 i lt15
i) a00i new int3
25
Statements
Empty statement Assignment int i, j, k k
1 i j k 1 i j k i j
k
26
Statements Method Declaration
Method with no parameters private void
ClearTextBoxes() foreach (Object Obj in
this.Controls) TextBox txtBox if
((Obj.GetType().ToString() "System.Windows.Form
s.TextBox")) txtBox (TextBox)Obj t
xtBox.Clear() Declares a Method
named ClearTextBoxes which a) does not return a
value and b) accepts no arguments as inputs. It
will clear (almost) all TextBoxes on a form.
27
Method Declaration Cont.
Method returning a value of type bool private
bool DataValid() if (txtInput.Text
null) return false try intIn
putValue Convert.ToInt32(txtInput.Text) c
atch return false return true
28
Method Declaration Cont.
Multiple Methods can be declared with the same
name so long as each has a unique
signature. private int intMin(int a, int
b) private int intMin(int a, long
b) private int intMin(int a, int b, int
c) private int intMin(int a, int b, intc, int
d) private int intMin(int a)
29
Call by value/Call by reference
By default method parameters are passed by
value private int intMin(int a, int
b) private int intMin(int a, int b, int c) If
you wish, you can pass parameters by reference as
in private int intMin(ref int a, ref int
b) private int intMin(ref int a) When passed
by reference, you must specify this when calling
the method intMin(ref int1, ref
int2) intMin(ref b) // b declared as
int b
30
Statements Method Call
Method Call string s "a,b,c" string
parts s.Split(',') txtOutput.Text "s is "
s "\r\n" for (int i 0 i lt parts.Length
i) txtOutput.Text "parts"
i.ToString() " is " partsi
"\r\n" Suggestion Carefully check out the
methods of the String Class for those that can be
used to manipulate/search strings.
31
Statements -- if
if Statement int k string Suffix Random
rndGen new Random() k rndGen.Next(10) if
(k 1) Suffix "st" else if (k
2) Suffix "nd" else Suffix
"th" txtOutput.Text "k is "
k.ToString() " Suffix is " Suffix
32
Statements -- switch
Switch Statement int i int j // code to
assign values to i and j i 4 j 4 switch
(i j) case true // executable code
here txtOutput.Text "i j is " (i
j) break case false // more
executable code txtOutput.Text "i j is
" (i j) break
33
Statements
Switch Recap Order of the cases is
immaterial Unlike VB, can an only test for
constant value Fall Through not allowed break
is required Each case can only occur
once Each case must have a break
statement If no case matches value then default
block, if any, is executed.
34
Statements -- switch
Switch Statement Random rndNo new
Random() int i rndNo.Next(1000) switch (I
10) case 1 case 3 // executable
code here followed by break case 2 case
4 // executable code here followed by
break default // executable code
here followed by break
35
Statements -- for
int n 6 int sum 0 int i for (i 0 i
lt n i) sum i is shorthand
for sum 0 int i 0 // initial value
to assign i while (i lt n) // termination
condition sum i i // increment
i
36
Statements -- for
  • In the following, what is the scope of i?
  • int n 6
  • int sum 0
  • int i
  • for (i 0 i lt n i)
  • sum i
  • MessageBox.Show(i.ToString())

37
Statements -- for
  • In the following, what is the scope of i?
  • int n 6
  • int sum 0
  • for (int i 0 i lt n i)
  • sum i
  • MessageBox.Show(i.ToString())

38
Statements -- while/do ... while
while while (condition) // statements //
presumably one (or more) statements will //
ultimately cause condition to be false. do
... while do // statements //
presumably one (or more) statements will //
ultimately cause condition to be false. while
(condition)
39
checked operator
Do you remember? // Code from Intro.ppt slide
10 int i long j 3000000000 i
(int)j txtOutput.Text "i is equal to "
i.ToString() What happened?
40
checked operator
Do you remember? int i long j 3000000000 i
(int)j txtOutput.Text "i is equal to "
i.ToString() What happened? Change it
to checked int i long j 3000000000 i
(int)j txtOutput.Text "i is equal to "
i.ToString()
41
Handling Exceptions 1
Consider the following code try checked
int i long j 3000000000 i
(int)j txtOutput.Text "i is equal to "
i.ToString() catch (Exception
ex) txtOutput.Text ex.Message "\r\n"
"\r\n" ex.ToString()
42
Statement -- return
private int intMax(int k) int j
int.MinValue foreach (int i in k) if (i gt
j) j i return j Note. The
type of the value returned MUST be the same as
the type of the method.
43
Handling Exceptions 2
try checked int i long j
3000000000 i (int)j txtOutput.Text "i
is equal to " i.ToString() catch
(OverflowException ex) txtOutput.Text
ex.Message "\r\n" "\r\n" ex.ToString() ca
tch (Exception ex) txtOutput.Text ex.Message
"\r\n" "\r\n" ex.ToString()
44
finally
Try checked long j 3000000000 int i
(int)j txtOutput.Text "i is equal to "
i.ToString() catch (OverflowException
ex) txtOutput.Text ex.Message "\r\n"
"\r\n" ex.ToString() catch (Exception
ex) txtOutput.Text ex.Message "\r\n"
"\r\n" ex.ToString() finally txtOutput.Tex
t "\r\n" "\r\n" "in the finally block"
45
Some Specific Exceptions
The following is an incomplete list of
Exceptions ArgumentOutOfRangeException Arithme
ticException DivideByZeroException IndexOutOfRan
geException InvalidCastException NullReferenceEx
ception OverflowException StackOverflowException
Yes, case does matter in entering these. And,
there are others. That's why you always want to
have as the last catch catch (Exception
ex) txtOutput.Text ex.Message "\r\n"
"\r\n" ex.ToString()
46
Statements -- throw
Of course, you can generate your own Exceptions.
For example, to catch division by zero and
eliminate the Nan and Infinity values for type
float. try float a 0 float b 0 if (b
0f) throw new DivideByZeroException()
catch (Exception ex) txtOutput.Text
ex.Message "\r\n" "\r\n" ex.ToString()
47
throw (more)
You can even create your own exceptions try fl
oat a 0 float b 0 if (b 0f)
throw new Exception("Only dummies divide by
zero!!") float c a / b txtOutput.Text
"setting c 0/0 yields " c.ToString() catc
h (Exception ex) txtOutput.Text ex.Message
"\r\n" "\r\n" ex.ToString()
48
Statements -- foreach
A Collection is a class that implements
the System.Collections.IEnumerable interface.
this means, it provides some representation of
where we are in the collection and a way to move
to the next element, if any, in the collection.
(Much more on interfaces later.) private void
b(string c) foreach (string x in
c) txtOutput.Text x.PadLeft(12)
"\r\n"
49
Statements -- break
The break statement can be used to exit from for,
while, do ... while and foreach loops and must be
used to exit the cases in a switch statement.
After a break statement control switches to the
statement immediately after the end of the
loop. txtOutput.Text "" for (int i 20 i gt
-1 i--) if (i lt 10) break txtOutput.
Text i.ToString().PadLeft(10) "\r\n"
50
Statement -- return
Every method should contain a return statement.
non-void methods MUST contain at least one return
statement that returns a value whose type matches
the methods. private void b(string
c) txtOutput.Clear() foreach (string x in
c) txtOutput.Text x.PadLeft(12)
"\r\n" return // technically this
statement is not needed
51
Statement -- return 2
private int intMax(int k) int j
int.MinValue foreach (int i in k) if (i gt
j) j i return j Note. The
type of the value returned MUST be the same as
the type of the method.
52
Statements Recap
With C, you have the following executable
statements // empty statement i 42
b // assignment b() // method call if
(ib) // if switch (expr) // switch Case
in VB for (int i 0 i lt10 i) // for
initial value termination // condition
increment while (condition) // while do ...
while (condition) // do ... while No Until as
in VB try // Exception Handling throw
(expression) // Exception foreach (element in
Collection) // loop through all
elements break // exit loop or case return
expression // return
Write a Comment
User Comments (0)
About PowerShow.com