0% found this document useful (0 votes)
53 views61 pages

4-Basics of C#

Uploaded by

210907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views61 pages

4-Basics of C#

Uploaded by

210907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Basic Elements of C#

Lecture 6

1
A C# Program
used to organize your code, use classes from the System namespace
and it is a container for classes
and other namespaces
container for data and methods, which brings functionality to your
program. Every line of code that runs in C# must be inside a class.

2
A C# Program

static: It means Main Method can be called without an object.


public: It is access modifiers which means the compiler can execute this
from anywhere.
void: The Main method doesn’t return anything.
Main(): It is the configured name of the Main method.
String []args: For accepting the zero-indexed command line arguments.
args is the user-defined name. So you can change it by a valid identifier.
[] must come before the args otherwise compiler will give errors.
Basic Elements of C#

1. Language Symbols

2. Variables

3. Comments

4. Constants

5. Reserved words

6. Operators and Expressions

7. User Input

4
Basic Elements of C#
Language Symbols

1. Language Symbols
- Letters and Characters (A- Z) or (a-z)

- Numbers(0-9)

- Special symbols

5
Special Symbols
• Token: the smallest individual unit of a
program written in any language excluding
whitespace or a comment
• C# tokens include special symbols, word
symbols, and identifiers
• Special symbols in C# include:

6
Variables

• Area in computer memory where a value of a


particular data type can be stored
– Declare a variable
– Allocate memory
• Syntax
– datatype identifier;
– Compile-time initialization
– Initialize a variable when it is declared
• Syntax
– datatype identifier = expression;
7
Integral Data Types

• Primary difference
– How much storage is needed
– Whether a negative value can be stored
• Includes number of types
– byte & sbyte
– char
– int & uint
– long & ulong
– short & ushort

8
Data Types

Table 1: Values and sizes for integral types 8


Examples of Integral Variable
Declarations

int studentName; // Name of a student


int age = 20; // age - originally initialized to 20
int examNumber; // number of exams
int score; // numbers obtained in a course

General Syntax
type identifier = expression;

10
Floating-Point Types

• Default type is double

Table 2: Values and sizes for floating-point types

11
Examples of Floating-Point
Declarations
double extraPerson = 3.50; // extraPerson originally set
// to 3.50
double averageScore = 70.0; // averageScore originally set
// to 70.0
double priceOfTicket; // cost of a movie ticket
float totalAmount = 23.57f; // note the f must be placed after
// the value for float types
* It is mandantory to suffix number with f or F of float type,
otherwise the number is assumed to be of double.
* Common Error Message: “Literal of type double cannot be
implicitly converted to type `float'”
12
Decimal Types
• Monetary data items
• As with the float, must attach the suffix ‘m’ or ‘M’
onto the end of a number to indicate decimal
– Float attach ‘f’ or ‘F’

Table 3: Value and size for decimal data type


• Examples
decimal endowmentAmount =
33897698.26M; decimal deficit;
13
Boolean Variables

• Based on true/false, on/off logic


• Boolean type in C# → bool
• Does not accept integer values such as 0, 1,
or -1
bool undergraduateStudent;
bool moreData = true;

14
Strings
• Represents a string of Unicode characters

string studentName;
string courseName = "C# Programming";
string twoLines = "Line1\nLine2";

15
Identifiers

• Identifier: the name of something that


appears in a program
– Consists of letters, digits, and the underscore
character (_)
– Must begin with a letter or underscore
• C# is case sensitive
– NUMBER is not the same as number
• Avoid using reserved words as identifiers,
they have special meanings to compiler.
16
Identifiers (cont'd.)
• Legal identifiers in C#:
– first
– conversion
– payRate

Table Invalid identifier


4: 17
Examples of Valid Names (Identifiers)

Table 5: Valid
identifiers 18
Examples of Invalid Identifiers

Table 2- Invalid identifier


6 19
Variables and Data Types
• A variable is nothing but a name given
to a storage area that our programs can
manipulate.
• Each variable in C# has a specific type,
which determines the size and layout
of the variable's memory; the range of
values that can be stored within that
memory; and the set of operations that
can be applied to the variable.

20
Variable Definition in C#
• - Syntax for variable definition in C# is:
<data_type> <variable_list>;
- Examples:
int counter;
double interestRate;
char grade;

21
Allocating Memory with Constants and
Variables (cont’d.)
• Variable: memory location whose content
may change during execution
• Syntax to declare a named constant:

22
Variable Initialization in C#
• Variables are initialized (assigned a value) with an equal
sign followed by a constant expression. The general form
of initialization is:
variable_name = value;

23
Variable Initialization in C#

• Variables can be initialized (assigned an initial value)


in their declaration. The initialize consists of an equal
sign followed by a constant expression as:

24
Example

namespace VariDbleDefinition

class Program

st:at:1c void Ma1n args


)
( st:ring[ shont: aj
1nt b ;
double c;

/” actuaL 1n1t1a11zat::zon */

b = 28 ,
c = a + b;
Console . IJr 1teL1ne ( "a = {8), b = •J}, c = {2}", a, b, c
);
Console.ieadLine();

When the above code is compiled and executed, it produces the following result:

a = lB, b = 20, c = 30
Comments
• Single-line comments start with two forward slashes (//).
• Any text between // and the end of the line is ignored by C# (will not be
executed).

•Multi-line comments start with /* and ends with */.


• Any text between /* and */ will be ignored by C#.
Constants

• Add the keyword const to a declaration of identifier


• Value cannot be altered
• Despite of a variable, it is constant
• Syntax
const datatype identifier = expression;
const double TAX_RATE =
0.0675; const int SPEED = 70;
const char HIGHEST_GRADE =
'A';

27
Constants(con..)

class Oalendar2

CDns I: 1nt: cont: hs = weeks = 52, days = 365 j


12

class Calendar3

const int months =


12; coast int weeks
= 52; coast int
days = 365;

coast double
daysPerMeek =
(double) days /
(double) weeks;
coast double
daysPerMonth =
(double) days /
(double) months;
28
Reserved Words in C#

Table 7:
C# keywords/
reserved words

29
Basic Elements of C# Operators

Operators (Expressions) :
 Arithmetic Operators (+, -, *, /, %).
 Relational Operators (<, >, <=, >=).
 Equality Operators (==, !=).
 Logical Operators (!, &&, ||).
 Increment and Decrement Operators (++, --).
 Assignment Operators (=, +=, -=, *=, /=, %=).

30
Arithmetic Operators, Operator
Precedence, and Expressions
• C# arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% modulus (or remainder) operator
• +, -, *, and / can be used with integral
and floating-point data types
• Use % only with integral data types
31
Arithmetic Operations
• Simplest form of an assignment statement
resultVariable = operand1 operator operand2;
• Readability
– Space before and after everyoperator

Table 8: Basic arithmetic operators


32
Expressions

• Integral expression: all operands are


integers
– Yields an integral result
– Example: 2 + 3 * 5
• Floating-point expression: all operands are
floating-point
– Yields a floating-point result
– Example: 12.8 * 17.5 - 34.50

33
Mixed Expressions
• Mixed expression:
– Has operands of different data types
– Contains integers and floating-point
• Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2

34
Order of Precedence

• Order of operations
– Order in which the calculations are performed
• Example
– answer = 100;
– answer = answer + 50 * 3 / 25 – 2;
50 * 3 = 150
150 / 25 = 6
6– 2= 4
100 + 4 = 104

35
Order of Operations

Table 9:
Operator precedence
• Associatively of operators
– Left
– Right
36
Precedence of arithmetic operators

37
Basic Arithmetic Operations

• Plus (+) with string Identifiers


– Concatenates operand2 onto end of
operand1

string result;
string fullName;
string firstName = "Muhammad";
string lastName = "Ahmad";

fullName = firstName + " "


+ lastName; 38
Concatenation

Figure 10: String concatenation


39
Equality and Relational operators

40
Increment and Decrement Operators

• Increment operator: increase variable by 1


– Pre-increment: ++variable
– Post-increment: variable++
• Decrement operator: decrease variable by 1
– Pre-decrement: --variable
– Post-decrement: variable—
• What is the difference between the following?
x = 5; x = 5;
y = ++x; y = x++;
41
Increment and Decrement Operators
(continued)
• Increment and Decrement Operations
– Unary operator
num++; // num = num + 1;
--value1; // value = value – 1;
– Preincrement/predecrement versus
post

int num = 100;


Console.WriteLine(num++); // Displays
100 Console.WriteLine(num); //
Display 101 Console.WriteLine(++num); //
42
Displays 102
Increment and Decrement operators

43
Basic Arithmetic Operations
(continued)

Fig 11: Change in memory after count++; statement


executed 44
Basic Arithmetic Operations (continued)

Figure 12: Results after statement is executed


45
Increment and Decrement operators

46
Increment and Decrement operators

47
Assignment Operators

• Assignment expression abbreviations


– Addition assignment operator
• Example
c = c + 3; abbreviates to c += 3;
• Statements of the form
variable = variable operator expression;

can be rewritten as
variable operator= expression;
• Other assignment operators
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
x %= 9 (x = x % 9) 46
Assignment Statement
• The assignment statement takes the
form:

• Expression is evaluated and its value is


assigned to the variable on the left
side
• A variable is said to be initialized
the first time a value is placed into it
• In C#, = is called the assignment
operator 49
Examples of Assignment Statements

int
numberOfMinutes
, count,
minIntValue;

numberOfMinutes = 45;
count = 0;
minIntValue = -214;

50
Examples of Assignment Statements

char firstInitial,
yearInSchool,
punctuation;
enterKey,
lastChar;

firstInitial = 'B';
yearInSchool = '1';
punctuation = '; ';
enterKey = '\n'; // newline escape character
lastChar = '\u005A'; // Unicode character 'Z'
51
Examples of Assignment
Statements (continued)

double accountBalance,
weight;
bool isFinished;

accountBalance = 4783.68;
weight = 1.7E-3; //scientific notation may be used

isFinished = false; //declared previously as a bool


//Notice – no quotes used

52
Examples of Assignment
Statements (continued)

decimal amountOwed,
deficitValue;

amountOwed = 3000.50m; // m or M must be suffixed to


// decimal data types
deficitValue = -328672.50M;

53
Examples of Assignment Statements
(continued)

Figure 2-7 Impact of assignment


statement 54
Arithmetic assignment operators

55
User Input
User Input

• The Console.ReadLine() method returns a string. Therefore, you cannot get


information from another data type, such as int.
• The following program will cause an error:
User Input
Whitespaces
• Every C# program contains whitespaces
– Include blanks, tabs, and newline characters
• Used to separate special symbols, reserved
words, and identifiers
• Proper utilization of whitespaces is
important
– Can be used to make the program more
readable

59
Summary
• C# program: collection of functions, one
of which is always called main
• Identifiers consist of letters, digits, and
underscores, and begins with letter or
underscore
• The arithmetic operators in C# are
addition (+), subtraction (-),
multiplication (*), division (/), and
modulus (%)
• Arithmetic expressions are evaluated
using the precedence associativity rules 60
Summary (cont’d.)

• All operands in an integral expression are


integers
• All operands in a floating-point expression are
decimal numbers
• Mixed expression: contains both integers and
decimal numbers
• Use the cast operator to explicitly convert
values from one data type to another
• A named constant is initialized when
declared
• All variables must be declared before 61

You might also like