Variables Expressions

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 62

1.

C# code is made up of a series of statements, each of


which is terminated with a semicolon.
2. C# compilers ignore additional spacing in code,
whether it results from spaces, tab characters
(collectively known as whitespace characters).
3. C# is a block-structured language, meaning statements
are part of a block of code.
For example, a simple block of C# code could take the
following form:
{
<code line 1, statement 1>;
<code line 2, statement 2> ;
<code line 3, statement 2>;
}
4. Blocks of code may be nested inside each other
(that is, blocks may contain other blocks), in which
case nested blocks will be indented further:
{
<code line 1>;
{
<code line 2>;
<code line 3>;
}
<code line 4>;
}
5. C# code are comments
you use /* characters at the start of the comment and */ characters at
the end. These may occur on a single line, or on different lines, in
which case all lines in between are part of the comment.
6. C# code is that it is case sensitive
CHAPTER 3- Variables and Expressions
1.Variables
a) Simple types
b) Variable naming
Naming conventions
c) Literal Values
String Literals
Variable declaration and assignment
2.Expressions
Mathematical operators
Assignment operators
Operator Precedence
Namespaces
• To use variables, you have to declare them. This means that you
have to assign them a name and a type.
• After you have declared variables, you can use them as storage
units for the type of data that you declared them to hold.
• C# syntax for declaring variables merely specifies the type and
variable name:
<type> <name>;
Simple Types
 Simple types include types such as numbers and
Boolean (true or false) values that make up the
fundamental building blocks for your
applications.
 Unlike complex types, simple types cannot have
children or attributes.
 Most of the simple types available are numeric
The reason for the plethora of numeric types is because of the
mechanics of storing numbers as a series of 0s and 1s in the memory
of a computer.
For integer values, you simply take a number of bits (individual
digits that can be 0 or 1) and represent your number in binary
format.
A variable storing N bits enables you to represent any number
between 0 and (2N– 1).
For example, suppose you have a variable that can
store two bits.
The mapping between integers and the bits
representing those integers is therefore as follows:
0 = 00
1 = 01
2 = 10
3 = 11
In order to store more numbers, you need more
bits (three bits enable you to store the numbers
from 0 to 7, for example).
Instead, a number of different integer types can be
used to store various ranges of numbers, which
take up differing amounts of memory (up to 64
bits). These types are shown in the following table.
In addition to numeric types, three other simple
types are available:
Variable Naming
The basic variable naming rules are as follows:
➤ The first character of a variable name must be either a letter, an underscore
character (_), or the at symbol (@).
➤ Subsequent characters may be letters, underscore characters, or numbers.

There are also certain keywords that have a specialized meaning to the C#
compiler, such as the using and namespace keywords.
If you use one of these by mistake, the compiler complains, however, so don’t
worry about it.
For example, the following variable names are fine:
myBigVar
VAR1
_test
These are not, however:
99BottlesOfBeer
namespace
It’s-All-Over
Using SimpleTypeVariables
static void Main(string[] args)
{
int myInteger;
string myString;
myInteger = 17;
myString = "\"myInteger\" is";
Console.WriteLine("{0} {1}.", myString, myInteger);
Console.ReadKey();
}
Naming Conventions
Currently, two naming conventions are used in the .NET Framework
namespaces:
PascalCase and CamelCase.
The case used in the names indicates their usage.
They both apply to names that comprise multiple words and they
both specify that each word in a name should be in lowercase except
for its first letter, which should be uppercase.
For camelCase terms, there is an additional rule: The first word
should start with a lowercase letter.
The following are camelCase variable names:
age
firstName
timeOfDeath

These are PascalCase:


Age
LastName
WinterOfDiscontent

For your simple variables, stick to camelCase.


Use PascalCase for certain more advanced naming,
which is the Microsoft recommendation
Literal Values
Two examples of literal values:
integer and string.
The other variable types also have associated literal values, as shown
in the following table.
Many of these involve suffixes, whereby you add a sequence of
characters to the end of the literal value to specify the type desired.
Some literals have multiple types, determined at compile time by
the compiler based on their context (also shown in the following
table).
String Literals
Variable Declaration and Assignment
Declare variables simply using their type and name:
int age;
You then assign values to variables using the =
assignment operator:
age = 25;
Declare multiple variables of the same type at the same
time by separating their names with commas after the type,
as follows:
int xSize, ySize;
Here, xSize and ySize are both declared as integer types.
The second technique you are likely to see is assigning
values to variables when you declare them, which
basically means combining two lines of code:
int age = 25;
You can use both techniques together:
int xSize = 4, ySize = 5;
Here, both xSize and ySize are assigned different values.
Note that
int xSize, ySize = 5;
results in only ySize being initialized — xSize is just
declared, and it still needs to be initialized before it’s used
EXPRESSIONS
• Combining operators with variables and literal values
(together referred to as operands when used with
operators), you can create expressions, which are the
basic building blocks of computation.
• Operators can be roughly classified into three categories:
➤ Unary— Act on single operands
➤ Binary—Act on two operands
➤ Ternary—Act on three operands
• Most operators fall into the binary category, with a
few unary ones, and a single ternary one called the
conditional operator.
Mathematical Operators
• There are five simple mathematical operators, two of which
(+ and -) have both binary and unary forms. The following table
lists each of these operators, along with a short example of its use
and the result when it’s used with simple numeric types (integer
and floating point).
• The binary + operator does make sense when used with
string type variables. In this case, the table entry should
read as shown in the following table:
• The other two operators you should look at here are the
increment and decrement operators, both of which are
unary operators that can be used in two ways: either
immediately before or immediately after the operand.
The results obtained in simple expressions are shown in
the next table:
Manipulating Variables with Mathematical Operators
static void Main(string[] args)
{
double firstNumber, secondNumber;
string userName;

Console.WriteLine("Enter your name:");


userName = Console.ReadLine();
Console.WriteLine("Welcome {0}!", userName);

Console.WriteLine(“Enter First number:");


firstNumber = Convert.ToDouble(Console.ReadLine());

Console.WriteLine(“Enter Second number:");


secondNumber = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("The sum of {0} and {1} is
{2}.", firstNumber, secondNumber, firstNumber +
secondNumber);

Console.WriteLine("The result of subtracting {0}


from {1} is {2}.",secondNumber, firstNumber,
firstNumber - secondNumber);
Console.WriteLine("The product of {0} and {1} is {2}.",
firstNumber, secondNumber, firstNumber * secondNumber);

Console.WriteLine("The result of dividing {0} by {1} is {2}.",


firstNumber, secondNumber, firstNumber / secondNumber);

Console.WriteLine("The remainder after dividing {0} by {1} is


{2}.", firstNumber, secondNumber, firstNumber %
secondNumber);
Console.ReadKey();
}
• Assignment Operators

As you can see, the additional operators result in var1 being


included in the calculation, so code like
var1 += var2;
has exactly the same result as
var1 = var1 + var2;
OPERATOR NAME DESCRIPTION EXAMPLE
= Equal to It is used to assign the values to variables. int a; a = 10

+= Addition It performs the addition of left and right a += 10 is equals to


Assignment operands and assigns a result to the left a = a + 10
operand.

-= Subtraction It performs the subtraction of left and right a -= 10 is equals to


Assignment operands and assigns a result to the left a = a - 10
operand.

*= Multiplication It performs the multiplication of left and right a *= 10 is equals to


Assignment operands and assigns a result to the left a = a * 10
operand.

/= Division It performs the division of left and right a /= 10 is equals to


Assignment operands and assigns a result to the left a = a / 10
operand.
%= Modulo It performs the modulo operation on two a %= 10 is equals to
Assignment operands and assigns a result to the left a = a % 10
operand.

&= Bitwise AND It performs the Bitwise AND operation on a &= 10 is equals to
Assignment two operands and assigns a result to the a = a & 10
left operand.

|= Bitwise OR It performs the Bitwise OR operation on a |= 10 is equals to


Assignment two operands and assigns a result to the a = a | 10
left operand.

^= Bitwise Exclusive It performs the Bitwise XOR operation on a ^= 10 is equals to


OR Assignment two operands and assigns a result to the a = a ^ 10
left operand.

>>= Right Shift It moves the left operand bit values to a >>= 2 is equals to
Assignment the right based on the number of a = a >> 2
positions specified by the second
operand.
<<= Left Shift It moves the left operand bit values to a <<= 2 is equals to
Assignment the left based on the number of positions a = a << 2
specified by the second operand.
namespace Assignmentoperator
{
class Program
{
static void Main(string[] args)
{

int x = 20;

x += 10;
Console.WriteLine("Add Assignment: " + x);

x *= 4;
Console.WriteLine("Multiply Assignment: " + x);
x %= 7;
Console.WriteLine("Modulo Assignment: " + x)

x &= 10;
Console.WriteLine("Bitwise And Assignment: " + x);

x ^= 12;
Console.WriteLine("Bitwise XOR Assignment: " + x);
x >>= 3;
Console.WriteLine("Right Shift Assignment: " + x);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
Operator Precedence
• When an expression is evaluated, each operator is
processed in sequence, but this doesn’t necessarily mean
evaluating these operators from left to right. As a trivial
example, consider the following:
var1 = var2 + var3;
• Here, the + operator acts before the = operator. There are
other situations where operator precedence isn’t so
obvious, as shown here:
var1 = var2 + var3 * var4;
• The following table shows the order of
precedence for the operators you’ve encountered
so far, whereby operators of equal precedence
(such as * and /) are evaluated from left to right:
namespace operatorprecendence
{
class Program
{
static void Main(string[] args)
{

int x = 20, y = 5, z = 4;
int result = x / y + z;
Console.WriteLine("Result1: "+result);

bool result2 = z <= y + x;

Console.WriteLine("Result2: "+result2);

Console.WriteLine("Press Enter Key to Exit..");

Console.ReadLine();
}
}
}
Operators allow processing of primitive data types and
objects. They take as an input one or more operands and
return some value as a result.

 Operators in C# are special characters (such as "+",


".", "^", etc.) and they perform specific transformations
on one, two or three operands.
 Examples of operators in C# are the signs for adding,
subtracting, multiplication and division from math
(+, -, *, /) and the operations they perform on the
integers and the real numbers.
Operators in C#
Operators in C# can be separated in several different
categories:
1. Arithmetic operators – they are used to perform simple
mathematical operations.
2. Assignment operators – allow assigning values to
variables.
3. Comparison operators – allow comparison of two literals
and/or variables.
4. Logical operators – operators that work with Boolean data
types and Boolean expressions.
5. Binary operators – used to perform operations on the
binary representation of numerical data.
6. Type conversion operators – allow conversion of data
from one type to another.
Operator Categories
Below is a list of the operators, separated into
categories:
Types of Operators by Number of Arguments
Operators can be separated into different types
according to the number of arguments they take:
All binary operators in C# are left-associative, i.e.
the expressions are calculated from left to right,
except for the assignment operators.
• Some of the operators in C# perform different
operations on the different data types.
• For example the operator +. When it is used on numeric
data types (int, long, float, etc.), the operator is does
mathematical addition.
• However, when we use it on strings, the operator
concatenates (joins together) the content of the two
variables/literals and returns the new string.
Example:
int a = 7 + 9;
Console.WriteLine(a); // 16

string firstName = "John";


string lastName = "Doe";

// Do not forget the space between them


string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // John Doe

when the operator + is used on numbers it returns a numerical value,


and when it is used on strings it returns concatenated strings.
C# Arithmetic Operators
EXAMPLE
namespace Arithmeticoperators
{
class Program
{
static void Main(string[] args)
{

int result;
int x = 20, y = 10;

result = (x + y);
Console.WriteLine("Addition Operator: " + result);

result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);

result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
result = (x / y);
Console.WriteLine("Division Operator: " + result);

result = (x % y);
Console.WriteLine("Modulo Operator: " + result);

Console.WriteLine("Press Enter Key to Exit..");


Console.ReadLine();
}
}
}
Relational Operators
Relational operators are used to check the relationship
between two operands. If the relationship is true the result
will be true, otherwise it will result in false.
Relational operators are used in decision making and loops.
C# Relational Operators
Relational Operators
Relational operators are used to check the relationship
between two operands. If the relationship is true the result
will be true, otherwise it will result in false.
Relational operators are used in decision making and loops.
C# Relational Operators
namespace Relationaloperators
{
class Program
{
static void Main(string[] args)
{

bool result;
int x = 10, y = 20;

result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
result = (x > y);
Console.WriteLine("Greater than Operator: " + result)

result = (x <= y);


Console.WriteLine("Lesser than or Equal to: "+ result);

result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
Unary Operators
Unlike other operators, the unary operators
operates on a single operand.
Logical Operators
Logical (Boolean) operators take Boolean values
and return Boolean result (true or false).
The basic Boolean operators are "AND" (&&), "OR"
(||), "exclusive OR" (^) and logical negation (!).
The following table contains the logical operators in
C# and the operations that they perform:
namespace LogicalOperator
{
class Program
{
static void Main(string[] args)
{

int x = 15, y = 10;


bool a = true, result;

// AND operator
result = (x <= y) && (x > 10);
Console.WriteLine("AND Operator: " + result);
// OR operator
result = (x >= y) || (x < 5);
Console.WriteLine("OR Operator: " + result);

//NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
The table and the following example show that the logical
"AND" (&&) returns true only when both variables contain
truth.
Logical "OR" (||) returns true when at least one of the
operands is true.
The logical negation operator (!) changes the value of the
argument. For example, if the operand has a value true and
a negation operator is applied, the new value will be false.
The negation operator is a unary operator and it is placed
before the argument.
Exclusive "OR" (^) returns true if only one of the two
operands has the value true. If the two operands have
different values, exclusive "OR" will return the result true, if
they have the same values it will return false.
Using Statement
1. using statement doesn’t in itself give you access to names in
another namespace.
2. Unless the code in a namespace is in some way linked to your
project, by being defined in a source file in the project or being
defined in some other code linked to the project, you won’t have
access to the names contained.
3. In addition, if code containing a namespace is linked to your
project, then you have access to the names contained in that code,
regardless of whether you use using.
4. using simply makes it easier for you to access these names, and it
can shorten otherwise lengthy code to make it more readable.
Code in ConsoleApplication1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
...
}
The four lines that start with the using keyword are used to declare
that the System,
 System.Collections.Generic, System.Linq, and System.Text
namespaces will be used in this C# code and should be accessible
from all namespaces in this file without classification.
 The System namespace is the root namespace for .NET
Framework applications and contains all the basic functionality
you need for console applications.
 The other two namespaces are very often used in console
applications, so they are there just in case.

Finally, a namespace is declared for the application code itself,


ConsoleApplication1.

You might also like