You are on page 1of 119

STD 511: C# Programming

Introduction to Computers, Programs and C#


2

What is a
Computer?
A computer consists of a CPU,
memory, hard disk, floppy disk,
monitor, printer, and communication
devices.
Bus

Storage Memory CPU Communication Input


Output
Devices Devices Devices Device
s
e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,
and Tape and NIC Mouse Printer
3

Programs
Computer programs,
known as software,
are instructions to the
computer.
You tell a computer what to do through programs. Without
programs, a computer is an empty machine. Computers do
not understand human languages, so you need to use
computer languages to communicate with them.

Programs are written using programming languages.


Programming
Languages
Machine Language Assembly Language 4
Machine language is a set of primitive
High-Level Language instructions
built into every computer. The instructions are in
the form of binary code.
For example, to add two numbers, you might write
an instruction in binary like this:

1101101010011010
Programming
Languages
Machine Language Assembly Language
Assembly languages were developed to make programming
High-Level Language
easy. Since the computer cannot understand assembly
language, however, a program called assembler is used to
convert assembly language programs into machine code.
For example, to add two numbers, you might write an
instruction in assembly code like this:
ADDF3 R1, R2, R3
5
Assembly Source File
Machine Code File


Assemble …
ADDF3 R1, R2, R3 1101101010011010
r
… …
Programming
Languages
Machine Language Assembly Language 6
The high-level languages are English-like
High-Level and easy to
Language
learn and program. For example, the following is a high-
level language statement that computes the area of a circle
with radius 5:
area = 5 * 5 * 3.1415;
7

Popular High-Level Languages


Language Description

Ad Named for Ada Lovelace, who worked on mechanical general-purpose computers. The Ada
a language was developed for the Department of Defense and is used mainly in defense
BASI projects.
C Beginner’s All-purpose Symbolic Instruction Code. It was designed to be learned and used
C easily
by beginners.
C+ Developed at Bell Laboratories. C combines the power of an assembly language with the
ease of
+ use and portability of a high-level language.
C# C++ is an object-oriented language, based on C.
COBOL Pronounced “C Sharp.” It is a hybrid of Java and C++ and was developed by Microsoft.
FORTRA COmmon Business Oriented Language. Used for business applications.
N FORmula TRANslation. Popular for scientific and mathematical applications.
Pasca
Java
l Developed by Sun Microsystems, now part of Oracle. It is widely used for developing
Python platform-
independent Internet applications.
Visua Named for Blaise Pascal, who pioneered calculating machines in the seventeenth century. It is
l a
Basic simple, structured, general-purpose language primarily for teaching programming.
8

Interpreting/Compiling Source
• A program written Code
in a high-level language is
called a source program or source code.
• Because a computer cannot understand a source
program, a source program must be translated
into machine code for execution.
• The translation can be done using another
programming tool called an interpreter or a
compiler.
9

Compiling Source
A compiler translatesCode
the entire source code into a
machine-code file, and the machine-code file is
then executed, as shown in the following figure.

High-level Source File Machine-code File

… … Output
Compile Executor
area = 5 * 5 * 3.1415; 0101100011011100
r 1111100011000100
...

1
0

The operating system (OS)


program that manages and is a Operating Systems
User
controls a computer ’s activities.
The popular operating Application Programs
systems for general-purpose
computers are Microsoft Operating System
Windows, Mac OS, and Linux.
Hardware
1
1

Why C#?
The answer is that C# enables users to develop and
deploy applications on the Internet for servers, desktop
computers, and small hand-held devices. The future of
computing is being profoundly influenced by the
Internet, and C# promises to remain a big part of that
future.

 C# has a large community, so the developments are


done to make it exist in the system and not become
extinct.
 C# is widely being used in Game Development too.
1
5

C#’s History
• An Object Oriented Programming (OOP)
language created by Microsoft
• Runs on the .Net Framework
• Similar to C/C++ and Java
• Developed by Anders Hejlsberg
• First version was released in 2002. Current
version is V9 released in 2020
• https://docs.microsoft.com/en-
us/dotnet/csharp/whats-new/csharp-version-
history
1
6

Characteristics of C#
• C# Is Simple
• C# Is Object-Oriented
• C# Is Distributed
• C# Is Interpreted
• C# Is Robust
• C# Is Secure
• C# is Performance driven
• C# Is Multithreaded
• C# Is Dynamic
1
6

The .Net Framework


• . NET is a software framework that is designed and developed
by Microsoft
• It is a virtual machine to compile and run programs written in
different languages like C#, VB.Net, etc.
• It is used to develop Form-based applications, Web-based
applications, and Web services.
• Currently supports over 60 programming languages besides
C# and VB.Net
1
6

Components of the .Net Framework


1
7

A Simple C# Program
Public class Welcome
{
public static void Main(string[] args){
Console.WriteLine(“Welcome to C#!”);
}
}
Creating, Compiling,
and Running Programs
Create/Modify Source Code

Source code (developed by the programmer)


Saved on the disk
public class Welcome {
public static void Main(string[] args) {
Console.WriteLine("Welcome to C#!"); Source Code
}
}

Compile Source Code


i.e., javac Welcome.java
.dll or .exe file (generated
by the C#
compiler into IL i.e. Interpreted
language code which is saved in *.dll If compilation errors
or *.exe formatunderstand) stored on the disk

.exe or .dll file .Exe or


.dll file

Run .exe file


Using JIT compiler i.e. Just-in-time
compiler, the IL code is translated
into machine code or native code
The JIT compiler is named as such because it compiles
IL code at the moment that the user tries to use it;
for example, when you double-click the .exe file. Result

If runtime errors or incorrect result 20


2
1

Trace a Program
Execution Enter main method

//This program prints Welcome to C#!


public class Welcome {
public static void Main(string[] args) {
Console.WriteLine("Welcome to
C#!");
}
}
2
2

Trace a Program
Execution Execute statement

//This program prints Welcome to C#!


public class Welcome {
public static void Main(string[]
Console.WriteLine("Welcome
args) { to C#!");

}
}
2
4

Anatomy of a C# Program
• Class name
• Main method
• Statements
• Statement terminator
• Reserved words
• Comments
• Blocks
2
5

Class
Name
Every C# program must have at least one class.
Each class has a name. By convention, class names
start with an uppercase letter. In this example, the
class name is Welcome.

//This program prints Welcome to C#!


public class Welcom {
e void Main(string[] args) {
public static
Console.WriteLine("Welcome to C#!");
}
}
2
6

Main
Method
Line 2 defines the main method. In order to run a
class, the class must contain a method named
Main. The program is executed from the Main
method.

//This program prints Welcome to C#!


public class Welcome {
public static void Main(string[] args) {
Console.WriteLine("Welcome to
C#!");
}
}
2
7

Stateme
ntrepresents an action or a sequence of
A statement
actions. The statement Console.WriteLine("Welcome to
C#!") in the program in Listing 1.1 is a statement to
display the greeting "Welcome to C#!“.

//This program prints Welcome to C#!


public class Welcome {
public static void Main(string[]
args) {
Console.WriteLine("Welcome to C#!");

}
}
2
8

Statement
Terminator
Every statement in C# ends with a semicolon (;).

//This program prints Welcome to C#!


public class Welcome {
public static void Main(string[] args) {
;
Console.WriteLine("Welcome to C#!")
}
}
2
9

Reserved
words
Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used for
other purposes in the program.

//This program prints Welcome to C#!


public class Welcome {
public static void main(string[] args) {
Console.WriteLine("Welcome to C#!");
}
}
3
0

Block
s
A pair of braces in a program forms a block that groups
components of a program.

public class Test {


Class block
public static void Main(string[] args) {
Console.WriteLine("Welcome to C#!"); Method block
}
}
3
1

Special
Character Name Description
Symbols
{} Opening and closing Denotes a block to enclose statements.
braces
() Opening and closing Used with methods.
parentheses
[] Opening and closing Denotes an array.
brackets
// Double slashes Precedes a comment line.

" " Opening and closing Enclosing a string (i.e., sequence of characters).
quotation marks
; Semicolon Marks the end of a statement.
3
2

{ …}

// This program prints Welcome to C#!


public class Welcome {
public static void Main(string[] args) {
Console.WriteLine("Welcome to C#!");
}
}
3
3

( … )

// This program prints Welcome to C#!


public class Welcome {
public static void Main (String[] args)
{ Console.WriteLine( "Welcome to C#!" );
}
}
3
4

// This program prints Welcome to C#!


public class Welcome {
public static void Main(string[] args) {
;
Console.WriteLine("Welcome to C#!")
}
}
3
5

// …

// This program prints Welcome to C#!


public class Welcome {
public static void Main(String[] args) {
Console.WriteLine("Welcome to C#!");
}
}
3
6

"…"

// This program prints Welcome to C#!


public class Welcome {
public static void Main(string[] args) {
"
Console.WriteLine( Welcome to C#! ;")
}
}
4
1
Programming Style
and
Documentation
• Appropriate Comments
• Naming Conventions
• Prope Indentation and Spacing
r
Lines
• Block
Styles
4
2

Appropriate
Comments
Include a summary at the beginning of the
program to explain what the program does, its key
features, its supporting data structures, and any
unique techniques it uses.

Include your name, class section, instructor, date,


and a brief description at the beginning of the
program.
4
3

Naming
• Conventions
Choose meaningful and descriptive names.
• Class names:
– Capitalize the first letter of each word in the
name. For example, the class name
ComputeExpression.
4
4

Proper Indentation and Spacing

• Indentation
– Indent two spaces.

• Spacing
– Use blank line to separate segments of the
code.
4
5

Block
Styles
Next-line
Use end-of-line
public class Test
style {
style for braces.
public static void Main(string[] args)
{
Console.WriteLine("Block Styles");
}
}

End-of-line
style
public class Test {
public static void Main(string[] args) {
Console.WriteLine("Block Styles");
}
}
4
6

Programming
• Syntax Errors Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result
4
7

Syntax
public class Errors
ShowSyntaxErrors {
public static void Main(string[] args)
{ Console.WriteLine("Welcome to C#);
}
}
4
8

Runtime
public class Errors
ShowRuntimeErrors {
public static void Main(string[] args) {
Console.WriteLine(1 / 0);
}
}
4
9

Logic
public class ShowLogicErrors {
public static void Main(string[] Errors
args)
{ Console.WriteLine("Celsius 35 is Fahrenheit degree
"); Console.WriteLine((9 / 5) * 35 + 32);
}
}
5
0
Escape Sequences for Special Characters

Description Escape Sequence


Tab \t
Linefeed \n
Carriage return \r
Backslash \\
Single Quote \'
Double Quote \"
STD511: C# Programming

Pseudocode and Flowcharts


PROGRAM DESIGNING TECHNIQUES

• PSEUDOCODE

• ALGORITHM

• FLOWCHART
DESIGNING TECHNIQUES
• A typical programming task can be divided in two
phases:
1) Problem solving phase
produce an ordered sequence of steps that
describe
solution of problem
this sequence of steps is called an algorithm
2) Implementation phase
implement the program in some programming
language
STEPS IN PROBLEM SOLVING

• First, produce a general algorithm (one can


use
pseudocode)
• Refine the algorithm successively to get step by
step detailed algorithm that is very close to a
computer language.

• Pseudocode is an artificial and informal language


that helps programmers develop algorithms.

• Pseudocode is very similar to everyday English.


PSEUDO CODE &
ALGORITHM
Example 1: Write a pseudocode and
an algorithm to convert the length in
feet to inches.
PSEUDO CODE FOR EXAMPLE 1

• Input the length in feet


• Calculate the length in inches by multiplying
• length in feet with 12
• Print length in inches.
ALGORITH
M

Step 1: Input L_ft


Step 2: L_inches  L_ft x 12
Step 3: Print L_inches
THE FLOWCHART
• A schematic representation of a sequence of
operations , as in a manufacturing process or
computer program.
• It is a graphic representation of how a process
works, showing , at a minimum, the sequence of
steps.
• A flowchart consist of a sequence of instructions
linked together by arrow to show the order in
Cont...

 Each instruction is put into a box. The boxes are


different shapes depending upon what the
instruction is.

 Different symbols are used to draw each type


of flowchart.
Cont..

shows logic of an algorithm

emphasizes individual steps and their
interconnections

e.g. control flow from one action to the
next
FLOWCHART SYMBOLS
Name S y m bo l U s e in F l o w c h a r t

Ova D e n o t e s t h e b e g i n n i n g o r e n d of t h e p r o g r a m
l

Parallelogra D e n o tes an i n p u t o p e r a tion


m

R e c ta n g l D e n o t e s a p r o c e s s to b e c a r r i e d o u t
e e . g. a d d i t i o n , s u b t r a c t i o n , d i v i s i o n
e tc .

D e n o t e s a d e c i s i o n ( o r b r a n c h ) to b e m a d e .
Diamon
T h e p r o g r a m s h o u l d c o n t i n u e a l o n g o n e of
d
t w o r o u te s . ( e . g . IF / T H E N / E L S E )

Hybri D e n o tes an ou tput o p e r a t i o n


d

Flowlin D e n o t e s t h e d i r e c t i o n of l o g i c f l o w in t h e p r o g r a
e m
EXAMPLE 2

Write an algorithm and draw a flowchart to convert the


length in feet to centimeter.
Pseudocode:
• Input the length in feet (Lft)
• Calculate the length in cm (Lcm) by multiplying LFT with
30
• Print length in cm (LCM)
EXAMPLE 2

Algorithm FLOWCHART
Step 1: Input
L_ft
Step 2:
STAR
Lcm  L_ft x 30 T

Step 3: Print L_cm Input


L_ft

Lcm  L_ft x 30

Print

L_cm

STOP
EXAMPLE 3

Write an algorithm and draw a flowchart that


will read the two sides of a rectangle and
calculate its area.
Pseudocode
• Input the width (W) and Length (L) of
a rectangle
• Calculate the area (A) by multiplying L
with W
• Print A
EXAMPLE 3

Algorithm
STAR
Step 1: Input W,L T

Step 2: AL x W Inpu


t W,
Step 3: Print A L

A LxW

Print
A

STOP
EXAMPLE 4

• Write an algorithm and draw a flowchart that will calculate


the roots of a quadratic equation
ax2 bxc  0
• Hint: d = sqrt (b² – 4ac), and the roots are: x1 = (–b +
d)/2a
and x2 = (–b – d)/2a
EXAMPLE 4

Pseudocode:
• Input the coefficients (a, b, c) of the quadratic
equation
• Calculate d
• Calculate x1
• Calculate x2
• Print x1 and x2
EXAMPLE 4
STAR
T
Algorithm:
Input
Step 1: Input a, b, c a, b, c
Step 2: d  sqrt ( b x b – 4 x a x c
) d  sqrt(b x b – 4 x a x c)
Step 3:
Step 4: x1  (–b + d) / (2 x a)
x2  (–b – d) / (2 x a) x1 (–b + d) / (2 x a)
Step 5:
Print x1, x2
X2  (–b – d) / (2 x a)

Print
x1 ,x2

STOP
DESIGN STRUCTURES

• The expression A>B is a logical


expression
• it describes a condition we want to test
• if A>B is true (if A is greater than B)
we take the action on left
• print the value of A
• if A>B is false (if A is not greater than
B)
we take the action on right
• print the value of B
DECISION STRUCTURES

Y N
is
A>B

Print Print B
A
IF – THEN – ELSE STRUCTURE

• The structure is as follows


If condition then
true alternative
else
false alternative
endif
IF – THEN – ELSE STRUCTURE

If A>B then
print
Y N
A is
A>B
else B
print
Print B
endifPrint A
RELATIONAL OPERATORS

• Insert textRelational Operators


here
• Second line
Operator Description
> Greater than
• So< on Less than
= Equal to

 Greater than or equal to


 Less than or equal to
 Not equal to
EXAMPLE 5
• Write an algorithm that reads two values, determines
the largest value and prints the largest value with an
identifying message.
ALGORITHM
Step 1:
Step 2: • Input VALUE1, VALUE2
• if (VALUE1 > VALUE2) then
• MAX  VALUE1
• else
• MAX  VALUE2
Step 3: • endif
• Print “The largest value is”, MAX
EXAMPLE 5
STAR
T

Input
VALUE1,VALUE2

Y is N
VALUE1>VALUE2

MAX  VALUE1 MAX  VALUE2

Print
“The largest value is”, MAX

STOP
NESTED IFS

• One of the alternatives within an IF–


THEN–ELSE statement
–may involve further IF–THEN–
ELSE statement
EXAMPLE 6

• Write an algorithm that reads three


numbers and prints the value of the
largest number.
EXAMPLE 6
Step 1: Input N1, N2, N3
Step 2: if (N1>N2) then
if (N1>N3) then
MAX  N1 [N1>N2, N1>N3]
else
MAX  N3 [N3>N1>N2]
endif
else
if (N2>N3) then
MAX [N2>N1, N2>N3]

 N2 [N3>N2>N1]
else
MAX  N3
endif
Step 3: Print “The largest number is”, MAX
endif
EXAMPLE 6

• Flowchart: Draw the flowchart of the above Algorithm.


FLOWCHART
EXAMPLE 7
 Write and algorithm and draw a flowchart to
read an employee name (NAME), overtime
hours worked
(OVERTIME), hours absent (ABSENT) and
determine the bonus payment (PAYMENT).
EXAMPLE 7
Bonus Schedule

OVERTIME – (2/3)*ABSENT Bonus Paid

>40 hours $50


>30 but  40 hours $40
>20 but  30 hours $30
>10 but  20 hours $20
 10 hours $10
ALGORITHM

Step 1: Input NAME,OVERTIME,ABSENT


Step 2: if (OVERTIME–(2/3)*ABSENT > 40 ) then
PAYMENT  50
else if (OVERTIME–(2/3)*ABSENT > 30 &&
OVERTIME–(2/3)*ABSENT<= 40 ) then
PAYMENT  40
else if (OVERTIME–(2/3)*ABSENT > 20 &&
OVERTIME–(2/3)*ABSENT<= 30 ) then
PAYMENT  30
Cont...
else if (OVERTIME–(2/3)*ABSENT > 10 &&
OVERTIME–(2/3)*ABSENT<= 20) then
PAYMENT 20
else
PAYMENT  10
endif
Step 3: Print “Bonus for”, NAME “is $”,
PAYMENT
EXAMPLE 7

• Flowchart: Draw the flowchart of the above


algorithm?
LOOPS

• Computers are particularly well suited to


applications in which operations are repeated
many times.
• If the same task is repeated over and over
again a loop can be used to reduce program
size and complexity
EXAMPLE 8
Flowchart for finding the sum of first five natural numbers
EXAMPLE 9
FLOWCHART TO FIND THE SUM OF FIRST 50 NATURAL
NUMBERS.
EXAMPLE 10

• Writedown an algorithm and draw a


flowchart to find and print the largest of
N (N can be any number) numbers.
(Assume N to be 5 and the following set
to be the numbers {1 4 2 6 8 })
ALGORITHM
• Step 1: Input N
• Step 2: Input Current
• Step 3: Max 
• Step 4: Current
• Step 5: Counter 1
While
• Step 6: (Counter < N)
• Step 7: Repeat
• Step 8: steps 5
through
8
• Step 9: Counter 
Counter + 1
Input Next
FLOWCHART
START

Input
N, Current

Max  Current

Counter 1

Counter < N N

Y Print
Counter  Counter +1
Max
Input STOP
Next

Next

>Max
Y
STD511: C# Programming

Basics of C# Programming
9
4

Identifier
• s
An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_),
or a dollar sign ($). It cannot start with a digit.
– An identifier cannot be a reserved word.
• An identifier cannot be true, false, or
null.
• An identifier can be of any length.
9
5

Declaring
int x;
Variables
// Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
9
6

Assignment
x = 1; Statements
// Assign 1 to x;

// Assign 1.0 to radius;


radius = 1.0;
// Assign 'A' to a;
a = 'A';
9
7

Declaring and Initializing


in One Step
• int x = 1;

• double d = 1.4;
9
8

Named
const datatype Constants=
CONSTANTNAME VALUE;

const double PI = 3.14159;

const int SIZE = 3;


9
9

Naming
• Conventions
Choose meaningful and descriptive names.
• Variables and method names:
– Use lowercase. If the name consists of several
words, concatenate all in one, use lowercase
for the first word, and capitalize the first letter
of each subsequent word in the name. For
example, the variables radius and area,
and the method computeArea.
Naming Conventions,
• Class names: cont.
– Capitalize the first letter of each word in
the name. For example, the class name
ComputeArea.

• Constants:
– Capitalize all letters in constants, and use
underscores to connect words.
For example, the constant PI and
MAX_VALUE

100
Arithmetic
• operators
Arithmetic calculations used in most programs
– Usage
• * for multiplication
• / for division
• % for remainder
• +, -
– Integer division truncates remainder
7 / 5 evaluates to 1
– Remainder operator % returns the remainder
7 % 5 evaluates to 2

102
Operator precedence -
• Operator precedence I
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables b and
• Do a,
not use: a + b + c / 3 c
• Use: a + b + c ) /
( 3

103
Operator precedence -
II

104
How to Evaluate an Expression

3 + 4 * 4 + 5 * (4 + 3)
- 1 (1) inside parentheses
3 + 4 * 4 + 5 * 7 first
– 1 (2) multiplication
3 + 16 + 5 * 7
– 1 (3) multiplication
3 + 16 + 35 –
1 (4) addition
19 + 35 –
1 (5) addition
54 -
1 (6) subtraction
5
3

105
Arithmetic
Expressions

is translated to:

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x +


(9+x)/y)

106
1
0
6

Introducing Programming with an Example

A program to compute the area of the circle.


1 animation
0
7
Trace a Program Execution
public class ComputeArea { allocate memory
/** Main method */ for radius
public static void Main(string[] args) {
double radius; radius no value
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
Console.WriteLine("The area for the circle of radius " +
radius + " is " + area);
}
}
1 animation
0
8
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void Main(string[] args) {
double radius; radius no value
double area; no value
area
// Assign a radius
radius = 20;
allocate memory
// Compute area for area
area = radius * radius * 3.14159;

// Display results
Console.WriteLine("The area for the circle of radius " +
radius + " is " + area);
}
}
1 animation
0
9
Trace a Program Execution
public class ComputeArea { assign 20 to radius
/** Main method */
public static void Main(string[] args) {
double radius; 20
radius
double area; no value
area
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
Console.WriteLine("The area for the circle of radius " +
radius + " is " + area);
}
}
1 animation
1
0

public class ComputeArea { Trace a gram memory


/** Main method */
Pro
public static void Main(string[] args) { Execution20
double radius; radius
double area;
area 1256.636
// Assign a radius
radius = 20;
compute area and assign it
// Compute area
area = radius * radius * 3.14159; to variable area

// Display results
Console.WriteLine("The area for the circle of radius " +
radius + " is " + area);
}
}
1 animation
1
1
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void Main(string[] args) {
double radius; 20
radius
double area; 1256.636
area
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
Console.WriteLine("The area for the circle of radius " +
radius + " is " + area);
}
}
The area for the circle of radius 5 is 78.53975
1
1
2

Reading Input from the


Console
1.We use Console.ReadLine() to take user input in C#
2.Use the userName
string static methods To.Int32(), To.Double() of the
= Console.ReadLine();
Convert class in case of taking user inputs for numeric types
For example,
Console.WriteLine("Enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“Your age is: “ + age);
1
1
3

Exercise
• Draw a flowchart and write a C# program to
read the radius from the console and compute
the area of the circle.

• Draw a flowchart and write a C# program to


read three numbers and compute their
average.
1
1
4

Problem: Displaying
Time
Write a program that obtains hours and
minutes from seconds.
1
1
5

Problem: Converting Temperatures


Write a program that converts a Fahrenheit degree
to Celsius using the formula:

Note: you have to write


celsius = (5.0 / 9) *
(fahrenheit – 32)
1
1
6

Exponent
Operations
Console.WriteLine(Math.pow(2, 3));
// Displays 8.0
Console.WriteLine(Math.pow(4, 0.5));
// Displays 2.0
Console.WriteLine(Math.pow(2.5, 2));
// Displays 6.25
Console.WriteLine(Math.pow(2.5, -2));
// Displays 0.16
1
1
7

Number Literals
A literal is a constant value that appears directly
in the program. For example, 34, 1,000,000, and
5.0 are literals in the following statements:

int i = 34;
long x = 1000000;
double d = 5.0;
1
1
8

Shortcut Assignment Operators


Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
1
1
9

Increment and
Decrement Operators
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and
evaluates to the new value in var after the increment.

var++ postincrement The expression (var++) evaluates to the original


value in var and increments var by 1.

--var predecrement The expression (--var) decrements var by 1 and evaluates


to the new value in var after the decrement.

var-- postdecrement The expression (var--) evaluates to the original


value in var and decrements var by 1.
1
2
0

Increment and
Decrement Operators, cont.
1
2
1

Type Casting
Implicit casting
double d = 3; (type widening)

Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is
truncated)

range increases

byte, short, int, long, float,


double
1
2
2

The String Type


The char type only represents one character. To
represent a string of characters, use the data type called
String. For example,

String message = "Welcome to Java";


1
2
3

String
Concatenation
// Three strings are concatenated
string message = "Welcome " + "to " + "X#";

// String is concatenated with number


string s = "Chapter" + 2; // s becomes Chapter2

// String is concatenated with character


string s1 = "Section" + 'B'; // s1 becomes SectionB
1
2
4

Converting Strings to
Integers
To convert a string into an int value, you can use the
static ToInt32 method in the Convert class as
follows:

int intValue = Convert.ToInt32(intString);

where intString is a numeric string such as “123”.


1
2
5

Converting Strings to
Doubles
To convert a string into a double value, you can use the
static ToDouble method in the Convert class as
follows:

double doubleValue
=Convert.ToDouble(doubleString);

where doubleString is a numeric string such


as “123.45”.
1
3
1

Debugging
• Logic errors are called bugs. The process of finding and
correcting errors is called debugging.

• You can hand-trace the program (i.e., catch errors by


reading the program), or

• you can insert print statements in order to show the


values of the variables or the execution flow of the
program.
1
3
2

Debugger
Debugger is a program that facilitates debugging. You
can use a debugger to
•Execute a single statement at a time.
•Trace into or stepping over a method.
•Set breakpoints.
•Display variables.
•Display call stack.
•Modify variables.
References
• C# Programming for Absolute Beginners;
Radek Vystavel.
• https://www.geeksforgeeks.org/csharp-progr
amming-language/
• https://docs.microsoft.com/en-us/dotnet/csh
arp/

• https://www.w3schools.com/cs

You might also like