0% found this document useful (0 votes)
44 views175 pages

Lec 1 Introduction To C Merged

Uploaded by

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

Lec 1 Introduction To C Merged

Uploaded by

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

Introduction to C#

Lecture 1
INTERMEDIATE PROGRAMMING

Engr. Jennelyn P. Cabale


Objectives
• C# Overview
• Strong Programming Features of C#
• C# Environment
• C# Program Structure
• C# Graphical User Interface

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 2


What is C#?
• C# is pronounced "C-Sharp".

• It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.

• C# has roots from the C family, and the language is close to other popular languages like C++ and Java.

• The first version was released in year 2002. The latest version, C# 8, was released in September 2019.

• C# is used for:
– Mobile applications
– Desktop applications
– Web applications
– Web services
– Web sites
– Games
– VR
– Database applications

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 3


Why Use C#?
• It is one of the most popular programming language in the world

• It is easy to learn and simple to use

• It has a huge community support

• C# is an object oriented language which gives a clear structure to programs and


allows code to be reused, lowering development costs.

• As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or


vice versa

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 4


C# Overview
• C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved
by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).

• C# was developed by Anders Hejlsberg and his team during the development of .Net Framework.

• C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime
environment that allows use of various high-level languages on different computer platforms and architectures.

• The following reasons make C# a widely used professional language −


– It is a modern, general-purpose programming language
– It is object oriented.
– It is component oriented.
– It is easy to learn.
– It is a structured language.
– It produces efficient programs.
– It can be compiled on a variety of computer platforms.
– It is a part of .Net Framework.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 5


Strong Programming Features of C#
• Boolean Conditions
• Automatic Garbage Collection
• Standard Library
• Assembly Versioning
• Properties and Events
• Delegates and Events Management
• Easy-to-use Generics
• Indexers
• Conditional Compilation
• Simple Multithreading
• LINQ and Lambda Expressions
• Integration with Windows

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 6


C# Environment
• The .Net Framework • Some of the components of the .Net
– Windows applications framework:
– Web applications – Common Language Runtime (CLR)
– Web services – The .Net Framework Class Library
– Common Language Specification
– Common Type System
– Metadata and Assemblies
– Windows Forms
– ASP.Net and ASP.Net AJAX
– ADO.Net
– Windows Workflow Foundation (WF)
– Windows Presentation Foundation
– Windows Communication Foundation (WCF)
– LINQ

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 7


• Common Language Runtime or CLR
–It performs memory management, exception handling, debugging, security checking, thread
execution, code execution, code safety, verification, and compilation. The code that is directly
managed by the CLR is called the managed code. When the managed code is compiled, the compiler
converts the source code into a CPU independent intermediate language (IL) code. A Just In
Time(JIT) compiler compiles the IL code into native code, which is CPU specific.

• .Net Framework Class Library


–It contains a huge library of reusable types, classes, interfaces, structures, and enumerated values,
which are collectively called types.

• Common Language Specification


–It contains the specifications for the .Net supported languages and implementation of language
integration.

• Common Type System


–It provides guidelines for declaring, using, and managing types at runtime, and cross-language
communication.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 8


• Metadata and Assemblies
– Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or
in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code, and a set of
resources like image files.

• Windows Forms
– Windows Forms contain the graphical representation of any window displayed in the application.

• ASP.NET and ASP.NET AJAX


– ASP.NET is the web development model and AJAX is an extension of ASP.NET for developing and implementing AJAX
functionality. ASP.NET AJAX contains the components that allow the developer to update data on a website without a
complete reload of the page.

• ADO.NET
– It is the technology used for working with data and databases. It provides access to data sources like SQL server, OLE
DB, XML etc. The ADO.NET allows connection to data sources for retrieving, manipulating, and updating data.

• Windows Workflow Foundation (WF)


– It helps in building workflow-based applications in Windows. It contains activities, workflow runtime, workflow
designer, and a rules engine.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 9


• Windows Presentation Foundation
–It provides a separation between the user interface and the business logic. It helps in
developing visually stunning interfaces using documents, media, two and three
dimensional graphics, animations, and more.

• Windows Communication Foundation (WCF)


–It is the technology used for building and executing connected systems.

• Windows CardSpace
–It provides safety for accessing resources and sharing personal information on the internet.

• LINQ
–It imparts data querying capabilities to .Net languages using a syntax which is similar to the
tradition query language SQL.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 10


Integrated Development Environment (IDE) for C#
• Microsoft provides the following development tools for C# programming −
– Visual Studio 2010 (VS)
– Visual C# 2010 Express (VCE)
– Visual Web Developer

• Can write all kinds of C# programs from simple command-line applications to more complex
applications.

• Can also write C# source code files using a basic text editor, like Notepad, and compile the code into
assemblies using the command-line compiler

• Visual C# Express and Visual Web Developer Express edition are trimmed down versions of Visual
Studio and has the same appearance.

• https://visualstudio.microsoft.com/vs/community/.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 11


C# Install

• Once the Visual Studio Installer is downloaded and installed, choose the
.NET workload and click on the Modify/Install button:

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 12


• After the installation is complete, click on the Launch button to get
started with Visual Studio.
• On the start window, choose Create a new project:

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 13


• Then click on the "Install more tools and features" button:

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 14


• Choose "Console App (.NET Core)" from the list and click on the Next
button:

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 15


• Enter a name for your project, and click on the Create button:

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 16


• Visual Studio will automatically generate some code for your project:

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 17


Visual Studio Key Features
1. Creation of an application in any .Net language– The Visual Studio IDE can be used to create an
application in any .Net language. Hence, a developer can use C#, VB.Net or even F# to develop an
application.

2. Creation of any application type – The Visual Studio IDE can be used to create an application of any
type. (Web-based application or Windows Forms-based application).

3. Debug Applications on the fly – Applications can be tested as they are being built. The IDE allows
one to run the program at any point of time during the development process. Hence, a developer
can check for any errors during the development phase itself.

4. Extensions –The IDE has the facility to install third-party extensions. An example can be Subversion,
which is used for source code repository management. Subversion is used to upload code to a
central repository. This is done so that a copy of the code will always exist. Visual Studio has the
facility to integrate with such software from the IDE itself. Hence, a developer can work with code
repositories from the IDE itself.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 18


• Start Page –easily open any latest projects or start a new one, to create C# program
or to get help how to use C#.

• Code Editor – keeps the program’s source code and allows opening and editing
multiple files.

• Error List –shows the errors in the program (if any).

• Solution Explorer – when no project is loaded, this window is empty. It will show the
structure of the project – all the files it contains, regardless if they are C# code,
images or some other type of code or resources.

• Properties – holds a list of the current object’s properties. Properties are used mainly
in the component-based programming, e.g. when we develop WPF, Windows Store or
ASP.NET Web Forms application.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 19


Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 20
Creating a New C# Project
• Steps:
–File -> New Project …
–The new project helper appears with all
the different types of projects we can
create listed. We can choose a project
type (e.g. Console Application or WPF
Application), programming language (e.g.
C# or VB.NET) and .NET Framework
version (e.g. .NET Framework 4.5)

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 21


C# - Program Structure
• A C# program consists of the following parts −
–Namespace declaration
–A class
–Class methods
–Class attributes
–A Main method
–Statements and Expressions
–Comments

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 22


• Line 1: using System means that we can use classes from the
System namespace.

• Line 2: A blank line. C# ignores white space. However,


multiple lines makes the code more readable.

• Line 3: namespace is used to organize code, and it is a


container for classes and other namespaces.

• Line 4: The curly braces {} marks the beginning and the end of
a block of code.

• Line 5: class is a container for data and methods.

• Line 7: Main method. Any code inside its curly brackets {} will
be executed.

• Line 9: Console is a class of the System namespace, which has


a WriteLine() method that is used to output/print text.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 23


WriteLine or Write
• The most common method to output something is WriteLine() or Write().

• WriteLine() prints the output on a new line while Write() prints on the same line

• Example
Console.WriteLine("Hello World!");
Console.WriteLine("I will print on a new line.");

Console.Write("Hello World! ");


Console.Write("I will print on the same line.");

• Result:

Hello World!
I will print on a new line.
Hello World! I will print on the same line.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 24


Compiling and Executing the Program
• Steps:

1. Start Visual Studio.

2. On the menu bar, choose File -> New -> Project.

3. Choose Visual C# from templates, and then choose Windows.

4. Choose Console Application.

5. Specify a name for your project and click OK button.

6. This creates a new project in Solution Explorer.

7. Write code in the Code Editor.

8. Click the Run button or press F5 key to execute the project. A Command Prompt window appears that contains the line Hello
World.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 25


C# Graphical User Interface
• Windows Forms Designer and Toolbox is the most rapid and convenient way
to create your user interface visually

• Windows Forms controls are reusable components that encapsulate user


interface functionality and are used in client side Windows based applications.

• A control is a component on a form used to display information or accept user


input.

• The Control class provides the base functionality for all controls that are
displayed on a Form.
Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 26
How to create a new project in C# ?
• Open your Visual Studio Environment and Click File->New Project

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 27


• Then you will get a New Project Dialogue Box asking in which language
you want to create a new project. Select Visual C# from the list.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 28


How to add controls to Form ?

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 29


C# Label Control
• Label control used to display text in a set location on the page.

• Label controls also used to add descriptive text to a Form to provide the
user with helpful information.

• The Label class is defined in the System.Windows.Forms namespace.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 30


Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 31
C# Button Control
• A button is a control, which is
an interactive component that
enables users to communicate
with an application.

• The Button class inherits


directly from the ButtonBase
class.

• A Button can be clicked by using


the mouse, ENTER key, or
SPACEBAR if the button has
focus.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 32


C# TextBox Control
• TextBox control is used to
display, or accept as input, a
single line of text also including
multiline editing and password
character masking.

• Text box object is used to


display text on a form or to get
user input while a C# program
is running. A user can type
data or paste it into the control
from the clipboard.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 33


C# TextBox Properties

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 34


• The below code set a textbox width as 250
and height as 50 through source code.

textBox1.Width = 250;
textBox1.Height = 50;

• Background Color and Foreground Color

textBox1.BackColor = Color.Blue;
textBox1.ForeColor = Color.White;

• Textbox BorderStyle
–Different types of border style: None, FixedSingle
and fixed3d.

textBox1.BorderStyle = BorderStyle.Fixed3D;

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 35


TextBox Events
• You can capture which key is pressed by the user using KeyDown event

• When user input or setting the Text property to a new value raises the TextChanged event

• Sets the maximum number of characters or words the user can input into the text box control.
textBox1.MaxLength = 40;

• When a program wants to prevent a user from changing the text that appears in a text box, the
program can set the controls Read-only property is to True.
textBox1.ReadOnly = true;

• You can use the Multiline and ScrollBars properties to enable multiple lines of text to be displayed or
entered.
textBox1.Multiline = true;

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 36


• TextBox controls can also be used to accept passwords and other sensitive information. You can use the PasswordChar property to mask
characters entered in a single line version of the control
textBox1.PasswordChar = '*';

• You can add new line in a textbox using many ways.


textBox1.Text += "your text" + "\r\n";
or
textBox1.Text += "your text" + Environment.NewLine;

• Retrieve integer values from textbox


int i;
i = int.Parse (textBox1.Text);

• Parse method converts the string representation of a number to its integer equivalent.

• String to Float conversion


float i;
i = float.Parse (textBox1.Text);

• String to Double conversion


double i;
i = float.Parse (textBox1.Text);

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 37


Hotel Room Selection
• PURPOSE: The hotel room selection program will allow a user to • NOTES AND RESTRICTIONS: The user should not be able to
view different room types and make a room selection. make a room selection until he or she has chosen a room type.

• PROGRAM PROCEDURES: From a window screen, the user • COMMENTS: The pictures shown in the windows should be
should choose the room type and then make a room selection. selected from the pictures available on the Web.

• ALGORITHMS, PROCESSING, AND CONDITIONS: • USE CASE DEFINITION:


1. The user must be able to view a standard room and a deluxe room 1. User clicks Standard Room or Deluxe Room button.
until he or she makes a room selection. 2. Program displays a picture of the room chosen by the user and
2. When the user chooses a room type, a picture of that room type enables the room selection button.
should appear in the window. 3. User clicks room buttons to view rooms if desired. The program
3. Only one picture should be displayed at a time, so if a user chooses a displays a picture of the chosen room.
standard room, only the standard room picture should be displayed; if 4. User clicks the Select Room button.
a user then chooses a deluxe room, the deluxe room picture should be 5. Program displays a room selection confirmation message and disables
displayed and the standard room picture should not be displayed. both room buttons and the elect Room button. The Exit Window
4. When the user makes a room selection, a confirming message should button becomes active.
be displayed. In addition, the user should be prevented from 6. User terminates the program by clicking the Exit Window button.
identifying the room type after the room selection is made.
5. After the user makes a room selection, the only allowable action is to
exit the window.

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 38


Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 39
THE END

Engr. Jenn P. Cabale Lecture 1 - INTRODUCTION TO C# 47


Primitive Types and Variables
Lecture 2
INTERMEDIATE PROGRAMMING

Engr. Jennelyn P. Cabale


Data Types
• Data types are sets of values that have similar characteristics.

• Name
• Size
• Default value

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 2


Data Types Default Value Minimum Value Maximum Value

sbyte 0 -128 127

byte 0 0 255

short 0 -32768 32767

ushort 0 0 65535

int 0 -2147483648 2147483647

uint 0u 0 4294967295

long 0L -9223372036854775808 9223372036854775807

ulong 0u 0 18446744073709551615

float 0.0f ±1.5×10-45 ±3.4×1038

double 0.0d ±5.0×10-324 ±1.7×10308

decimal 0.0m ±1.0×10-28 ±7.9×1028

bool False Two possible values: true and false

char '\u0000' '\u0000' '\uffff'

object null - -

string null - -
Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 3
Integer Types
• Integer types represent integer numbers and are sbyte, byte, short, ushort, int, uint, long
and ulong.

• sbyte type is an 8-bit signed integer and can be both, positive and negative. The minimum
value that can be stored is SByte.MinValue = -128 (-27), and the maximum value is
SByte.MaxValue = 127 (27-1). The default value is the number 0.

• byte type is an 8-bit unsigned integer type and can only be nonnegative. Its default value is
the number 0. The minimal taken value is Byte.MinValue = 0, and the maximum is
Byte.MaxValue = 255 (28-1).

• short type is a 16-bit signed integer. Its minimal value is Int16.MinValue = -32768 (-215), and
the maximum is Int16.MaxValue = 32767 (215-1). The default value is the number 0.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 4


• ushort type is 16-bit unsigned integer. The minimum value that it can store is
UInt16.MinValue = 0, and the minimum value is – UInt16.MaxValue = 65535 (216-1).
Its default value is the number 0.

• int type is a 32-bit signed integer. The default value is 0. Its minimal value is
Int32.MinValue = -2,147,483,648 (-231), and its maximum value is Int32.MaxValue =
2,147,483,647 (231-1).

• uint type is 32-bit unsigned integer type. Its default value is the number 0u or 0U.
The 'u' letter indicates that the number is of type uint. The minimum value that it can
take is UInt32.MinValue = 0, and the maximum value is UInt32.MaxValue =
4,294,967,295 (232-1).

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 5


• long type is a 64-bit signed type with a default
value of 0l or 0L. The 'L' letter indicates that the
number is of type long. The minimal value that
can be stored in the long type is Int64.MinValue
= -9,223,372,036,854,775,808 (-263) and its
maximum value is Int64.MaxValue =
9,223,372,036,854,775,807 (263-1).

• ulong type is a 64-bit unsigned type, which has


as a default value the number 0u, or 0U. The
suffix 'u' indicates that the number is of type
ulong. The minimum value that can be recorded
in the ulong type is UInt64.MinValue = 0 and
the maximum is UInt64.MaxValue =
18,446,744,073,709,551,615 (264-1).

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 6


Real Floating-Point Types
• Real types are represented by a floating-point according to the standard IEEE 754
and are float and double.

• Real Type Float


–32-bit real floating-point type float. It is also known as a single precision real number. Its default
value is 0.0f or 0.0F. The character 'f' put at the end explicitly indicates that the number is of type
float. It has an accuracy up to seven decimal places. The range of values, which can be hold in a
float type is from ±1.5 × 10-45 to ±3.4 × 1038.

• Special Values of the Real Types


– Negative infinity -∞ (Single.NegativeInfinity). It is obtained when dividing -1.0f by 0.0f.
– Positive infinity +∞ (Single.PositiveInfinity). It is obtained when dividing 1.0f by 0.0f.
– Uncertainty (Single.NaN) – means that an invalid operation is performed on real numbers. It
isobtained when calculating square root of a negative number.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 7


• Real Type Double
–double type is also called double precision real number and is a
64-bit type with a default value of 0.0d and 0.0D. This type has
precision of 15 to 16 decimal digits. The range of values, which can
be recorded in double is from ±5.0 × 10-324 to ±1.7 × 10308.

–The smallest real value of type double is the constant


Double.MinValue = -1.79769313486232e+308 and the largest
double value is Double.MaxValue = 1.79769313486232e+308.

–The closest to 0 positive number of type double is Double.Epsilon


≈ 4.94066e-324.

–As with the type float the variables of type double can take the
special values: Double.PositiveInfinity (+∞),
Double.NegativeInfinity (-∞) and Double.NaN (invalid number).

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 8


Boolean Type
• Boolean type is declared with the keyword
bool.

• It has two possible values: true and false.


Its default value is false.

• It is used most often to store the calculation


result of logical expressions.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 11


Character Type
• Character type is a single character (16-bit number
of a Unicode table character). It is declared in C#
with the keyword char. The Unicode table is a
technological standard that represents any
character (letter, punctuation, etc.) from all human
languages as writing systems (all languages and
alphabets) with an integer or a sequence of
integers. The smallest possible value of a char
variable is 0, and the largest one is 65535. The
values of type char are letters or other characters,
and are enclosed in apostrophes.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 12


Strings
• Strings are sequences of characters.

• Declared by the keyword string.

• Their default value is null.

• Strings are enclosed in quotation marks.

• Text-processing operations: concatenation,


splitting by a given separator, searching,
replacement of characters.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 13


Object Type
• Object type is a special type, which is
the parent of all other types in .NET
Framework.

• Declared with the keyword object.

• It is a reference type of a memory


area which stores the actual value.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 14


Nullable Types
• Nullable types are specific wrappers around the value types that allow
storing the null value in them. It holds an optional value.

• Wrapping a given type as nullable can be done in two ways:


nullable<int> i1 = null;
int? i2 = i1;

• Nullable types are reference types. They may or may not have a value and
can be used as normal primitive data types, but with some specificity.

• Nullable types are used for storing information, which is not mandatory.
• Example:
string firstName = "John";
string lastName = "Smith";
int? age = null;

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 15


Variables
• A variable is a container of information, which can change its value. It provides means for:
– storing information;
– retrieving the stored information;
– modifying the stored information.

• Characteristics of Variables
– name (identifier), for example age;
– type (of the information preserved in them), for example int;
– value (stored information), for example 25.

• A variable is a named area of memory, which stores a value from a particular data type, and that area of memory is accessible in the
program by its name.

• Variables can be stored directly in the operational memory of the program or in the dynamic memory

• Primitive data types are called value types

• Reference data types are an address. They can be dynamically allocated and released.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 16


Naming Variables – Rules
• Variable names can contain the letters a-z, A-Z, the digits 0-9 as well as the
character '_'.
• Variable names cannot start with a digit.
• Variable names cannot coincide with a keyword of the C# language.

• To name a variable like a keyword, add a prefix "@“. For example @char and
@null

• Examples:
–name
–first_Name
–_name1

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 17


Declaring Variables
• specify its type (such as int);
• specify its name (identifier, such as age);
• optionally specify initial value (such as 25) but this is not obligatory.

• The syntax for declaring variables in C# is as follows:


<data type> <identifier> [= <initialization>] ;

• Here is an example of declaring variables:


string name;
int age;

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 18


Assigning a Value
• Assigning a value to a variable is the act of providing a value to be stored
in it.

• This operation is performed by the assignment operator "=". On the left


side of the operator is the variable name and on the right side – its new
value.

• Here is an example of assigning values to variables:


name = "John Smith";
age = 25;
Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 19
Initialization of Variables
• The word initialization in programming means specifying an initial value.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 20


Value and Reference Types
• Value types are stored in the program execution stack and directly contain
value.

• Value types are the primitive numeric types, the character type and the
Boolean type: sbyte, byte, short, ushort, int, long, ulong, float, double,
decimal, char, bool.

• The memory allocated is released when the program exits their range.

• For example, a variable declared in the method Main() of the program is stored
in the stack until the program completes execution of this method
Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 21
• Reference types keep a reference in the program execution stack, and points to the
dynamic memory (heap), where the value is stored. The reference is a pointer
indicating the actual location of the value in the heap. All reference types can get
value null.

• Reference types allocate dynamic memory for the creation and release by the system
for memory cleaning. The reference types are slower than the value type.

• Reference data types’ size are unknown.

• Reference types are all classes, arrays and interfaces such as the types: object, string,
byte.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 22


Value and Reference Types and the Memory

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 23


Literals
• The Primitive type values specified in the source code of the program are
called literals.

• Example:
–bool result = true;
–char capitalC = 'C';
–byte b = 100;
–short s = 20000;
–int i = 300000;

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 24


Types of Literals
• Boolean

• Integer

• Real

• Character

• String

• Object literal null

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 25


Boolean Literals
• Boolean literals are:
–true
–false

• Example:
bool result = true;

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 26


Integer Literals
• Integer literals are sequences of digits, a sign (+, -), suffixes and prefixes.

• Prefixes can present integers in the program source in decimal or hexadecimal format.
– "0x" and "0X" as prefix indicates hexadecimal values, for example 0xA8F1;
– 'l' and 'L' as suffix indicates long type data, for example 357L.
– 'u' and 'U' as suffix indicates uint or ulong data type, for example 112u.

• By default (if no suffix is used) the integer literals are of type int.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 27


Real Literals
• Real literals are a sequence of digits, a sign (+, -), suffixes and the decimal
point character. We use them for values of type float, double and decimal.
Real literals can be represented in exponential format. They also use the
following indications:

–- 'f' and 'F' as suffixes mean data of type float;


–- 'd' and 'D' as suffixes mean data of type double;
–- 'm' and 'm' as suffixes mean data of type decimal;
–- 'e' is an exponent, for example, "e-5" means the integer part multiplied by 10-5.

• By default (if there is no suffix), the real numbers are of type double.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 28


Character Literals
• Character literals are (single characters enclosed in apostrophes. Used to set
the values of type char. The value of a character literal can be:
– a character, for example 'A';
– a character code, for example '\u0065';
– an escaping sequence;

• Escaping Sequences
– Cannot be represented directly in the source code of the program and needs special
techniques
– Special literals – a sequence of special characters. Example: “new line” character.
– Examples: a double quotation mark, tab, new line, backslash and others.
– Most frequently used escaping sequences:
• \' – single quote
• \" – double quotes
• \\ – backslash
• \n – new line
• \t – offset (tab)
• \uXXXX – char specified by its Unicode number, for example \u03A7

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 29


String Literals
• String literals are used for data of type string. They are a
sequence of characters enclosed in double quotation marks.

• All the escaping rules for the char type are also valid for
string literals.

• Strings can be preceded by the @ character that specifies


a quoted string. In quoted strings the rules for escaping are
not valid, i.e. the character \ means \ and is not an escaping
character. Only one character needs to be escaped in the
quoted strings – the character " (double-quotes) and it is
escaped in the following way – by repeating it "" (double
double-quotes). All other characters are treated literally,
even the new line. Quoted strings are often used for the file
system paths naming.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 30


C# User Input

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 31


Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 32
C# - Type Conversion
• Type conversion is converting one type of data to
another type. It is also known as Type Casting.

• Implicit type conversion − These conversions are


performed by C# in a type-safe manner. For
example, are conversions from smaller to larger
integral types and conversions from derived
classes to base classes.

• Explicit type conversion − These conversions are


done explicitly by users using the pre-defined
functions. Explicit conversions require a cast
operator.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 33


C# - Type Conversion
Method Description Method Description

ToBoolean Converts a type to a Boolean value, ToInt64 Converts a type to a 64-bit integer.
where possible.
ToSbyte Converts a type to a signed byte
ToByte Converts a type to a byte. type.
ToChar Converts a type to a single Unicode ToSingle Converts a type to a small floating
character, where possible. point number.
ToDateTime Converts a type (integer or string ToString Converts a type to a string.
type) to date-time structures.
ToType Converts a type to a specified type.
ToDecimal Converts a floating point or integer
type to a decimal type. ToUInt16 Converts a type to an unsigned int
ToDouble Converts a type to a double type. type.
ToUInt32 Converts a type to an unsigned long
ToInt16 Converts a type to a 16-bit integer. type.
ToInt32 Converts a type to a 32-bit integer. ToUInt64 Converts a type to an unsigned big
integer.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 34


Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 35
Digital Downloads
• PURPOSE: The Digital Downloads program allows the user to • COMMENTS:
enter the number of songs to be downloaded. The program – A graphic should depict a musical image named Music.
calculates the total cost of the downloads based on a price of
$0.99 per song.
• USE CASE DEFINITION:
1. The Windows application opens with a text box where the
• PROGRAM PROCEDURES: In a Windows application, the user user can enter the number of song downloads. The user
enters the number of songs she wants to download. The interface includes the text box, an area to display the total
program calculates the total cost of downloads. The user can cost of downloads, a Calculate Cost button, a Clear button,
clear the values on the screen and enter a new value for the and an Exit button.
number of downloads.
2. The user enters the number of songs downloads.
3. The user clicks the Calculate Cost button.
• ALGORITHMS, PROCESSING, AND CONDITIONS:
4. The program displays the total cost of the song downloads.
1. The user must be able to enter the number of songs to be
downloaded. 5. The user clicks the Clear button to clear the Number of Song
2. The user can initiate the calculation and display the total cost of the Downloads text box and erase the total cost of download
downloads. amount.
3. The application computes the total cost of downloads by multiplying 6. The user repeats steps 2-5 if desired.
the number of downloads times the cost per download ($0.99). 7. The user clicks the Exit button to terminate the application.
4. The total cost of downloads is displayed as a currency value. The user
should be able to clear the value entered for the number of
downloads and the total cost of downloads.
5. The user should be provided with a button to exit the program.

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 36


Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 37
THE END

Engr. Jenn P. Cabale Lecture 2 - PRIMITIVE TYPES AND VARIABLES 49


Operators and Expressions
Lecture 3
INTERMEDIATE PROGRAMMING

Engr. Jennelyn P. Cabale


Operators
• 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 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.
Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 2
• Arithmetic operators – they are used to perform simple mathematical
operations.

• Assignment operators – allow assigning values to variables.

• Comparison operators – allow comparison of two literals and/or variables.

• Logical operators – operators that work with Boolean data types and Boolean
expressions.

• Binary operators – used to perform operations on the binary representation of


numerical data.

• Type conversion operators – allow conversion of data from one type to


another.
Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 3
Operator Categories

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 4


Types of Operators by Number of Arguments
• All binary operators in C# are left-associative

• All assignment operators and conditional operators ?: and ??


are right-associative.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 5


Operator Precedence in C#
• To change the precedence of an
operator we can use brackets.

• When we write expressions that are


more complex or have many operators,
it is recommended to use brackets to
avoid difficulties in reading and
understanding the code.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 6


Arithmetical Operators
• The division operator / has different effect on integer and real numbers. When we divide an integer by an integer,
the returned value is an integer. Such division is called an integer division.

• Integer division by 0 is not allowed and causes a runtime exception DivideByZeroException. The remainder of
integer division of integers can be obtained by the operator %. For example, 7 % 3 = 1, and –10 % 2 = 0.

• When dividing two real numbers or two numbers, one of which is real, and the result is a real number with a
whole and a fractional part. For example: 5.0 / 2 = 2.5. In the division of real numbers it is allowed to divide by 0.0
and respectively the result is +∞ (Infinity), -∞ (-Infinity) or NaN (invalid value).

• The operator for increasing by one ++ adds one unit to the value of the variable, the operator -- (decrement)
subtracts one unit from the value. When we use the operators ++ and -- as a prefix, the new value is calculated
first and then the result is returned.

• When we use the same operators as post-fix the original value of the operand is returned first, then the addition
or subtraction is performed.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 7


Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 8
Logical Operators
• Logical (Boolean) operators take Boolean values and return a Boolean
result (true or false). The basic Boolean operators are "AND" (&&), "OR"
(||), "exclusive OR" (^) and logical negation (!).

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 9


Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 10
Laws of De Morgan
• Logical operations are governed by the laws of De Morgan from
mathematical logic

• The first law states that the negation of the conjunction (logical AND) of
two propositions is equal to the disjunction (logical OR) of their
negations.

• The second law states that the negation of the disjunction of both
statements is equivalent to the conjunction of their negations.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 11


Operator for Concatenation of Strings
• The operator + is used to join strings. It concatenates two or more
strings and returns the result as a new string. If at least one of the
arguments in the expression is of type string, and there are other
operands not of type string, they will automatically be converted to type
string to allow successful string concatenation.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 12


Bitwise Operators
• A bitwise operator is an operator that acts on the binary representation of numeric
types.

• Binary representation of data is convenient because zero and one in electronics can
be implemented by Boolean circuits, in which zero is represented as "no electricity"
or for example with a voltage of -5V and the one is presented as "have electricity" or
say with voltage +5V.

• Bitwise operators work on numerical values and are applied bitwise over their binary
representation, i.e., they work on the bits of the number.

• There are bitwise operators "AND" (&), bitwise "OR" (|), bitwise negation (~) and
excluding "OR" (^).

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 13


Bitwise Operators and Their Performance

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 14


Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 15
Comparison Operators
• Comparison operators in C# are used to compare two or more operands. C# supports the following
comparison operators:

– greater than (>)


– less than (<)
– greater than or equal to (>=)
– less than or equal to (<=)
– equality (==)
– difference (!=)

• All comparison operators in C# are binary and the returned result is a Boolean value (true or false).

• Comparison operators have lower priority than arithmetical operators but higher than the assignment
operators.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 16


Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 17
Assignment Operators
• The operator for assigning value to a variable is "=" (the character for
mathematical equation). The syntax used for assigning value is as it
follows

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 18


Cascade Assignment
• The assignment operator can be used in cascade (more than once in the
same expression). In this case assignments are carried out sequentially
from right to left.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 19


Compound Assignment Operators
• They help to reduce the volume of the code by typing two operations
together with an operator: operation and assignment.

• Compound operators have the following syntax:


Operand1 operator = operand2;

• The upper expression is like the following:


Operand1 = operand1 operator operand2;

• The most commonly used compound assignment operators


are += (adds value of operand2 to operand1), -= (subtracts the
value of the right operand from the value of the left one).

• Other compound assignment operators are *=, /= and %=.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 20


Conditional Operator ?:
• The conditional operator ?: uses the Boolean value of an expression to
determine which of two other expressions to be calculated and returned as a
result. The operator works on three operands and that is why it is called
ternary operator.

• The character "?" is placed between the first and second operand, and ":" is
placed between the second and third operand. The first operand (or
expression) must be Boolean, and the next two operands must be of the same
type, such as numbers or strings.

• The operator ?: has the following syntax:


operand1 ? operand2 : operand3

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 21


The "." Operator
• The access operator "." (dot) is used to access the member fields or
methods of a class or object.

• Example of usage of point operator:


Console.WriteLine(DateTime.Now); // Prints the date + time

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 22


Square Brackets [] Operator
• Square brackets [] are used to access elements of an array by index, they
are the so-called indexer.

• Indexers are also used for accessing characters in a string.

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 23


Expressions
• Expressions are sequences of operators, literals and variables that are
calculated to a value of some type (number, string, object or other type).

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 24


Sunshine Cellular Company
• Sunshine Cellular Company:
–Takes orders by phone for cell phones priced at $100 each
–Two colors: blue and silver
–Currently the salespeople calculate the order total

• Develop an order-taking application for this company

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 25


Identifying the Application’s Tasks

Figure 2-2: Current order form used by Sunshine Cellular

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 26


• First, review current user procedures and forms

• Ask these questions:


–What information must be displayed on screen and/or printed on a printer?
–What information will the user need to enter into the UI to produce the desired
display or printout?
–What information will the program need to calculate to produce the desired display
or printout?
–How will the user end the application?
–Will previous information need to be cleared from the screen before new
information is entered?

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 27


Figure 2-3: Tasks entered in a TOE chart

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 28


Identifying the Objects
• Assign each task to an object in the user interface

• Text box: a control that allows the user to enter data


• Use a button to initiate the calculations
• Use labels to guide the user
• Use buttons to clear the screen and to end the application

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 29


Figure 2-4: Tasks and objects entered in a TOE chart
Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 30
Identifying the Events
• Next, determine which objects need an event to occur to allow the
object to perform its task

• Text boxes: no special events needed for user to enter the text
• Labels: no special events needed to display the prompts
• Buttons: action must occur when each button is clicked

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 31


Figure 2-5: Completed TOE chart ordered by task
Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 32
Figure 2-6: Completed TOE chart ordered by object

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 33


Designing the User Interface
• Next step is to design the user interface

• Follow Windows GUI guidelines for:


–Consistency with Windows standards
–Ease of use
–Familiar look and feel makes the application easier to learn

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 34


Arranging the Controls on a Form
• Design guidelines:
–Information should flow either vertically or horizontally
–Most important information should be in upper-left corner of the screen
–Group related controls together using white space or container controls

• Container controls include:


–Group box control
–Panel control
–Table layout panel control

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 35


Figure 2-7: Vertical arrangement of the Sunshine Cellular interface

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 36


Figure 2-8: Horizontal arrangement of the Sunshine Cellular interface

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 37


• Label guidelines:
– Use a label to identify each text box
– Left-align the label’s text
– Position label to left of or above the text box it identifies
– Labels and button captions should be one to three words only and appear on one line
– Labels and captions should be meaningful
– An identifying label should include a colon (:)
– Use sentence capitalization for identifying labels

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 38


• Sentence capitalization: capitalize first letter in first word and any other words customarily capitalized
• Book title capitalization: capitalize first letter in each word (except articles, conjunctions, and prepositions that do
not occur at the beginning or end of the caption)
• Button guidelines:
– Size buttons relative to each other: same height
– If stacked horizontally, same width also
– Most commonly used button should be first
– Use book title capitalization for buttons

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 39


• Positioning guidelines:
–Maintain a consistent margin from all edges of the form
–Related controls should be placed close to each other
–Minimize the number of different margins by aligning control borders where possible using snap
lines or Format menu
–Interface should not distract the user from doing the work

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 40


Including Graphics in the User Interface

• Human eye is drawn to pictures before text

• Include graphics only if necessary


–Use for aesthetic purposes
–Keep them small
–Use to clarify a portion of the screen

• Graphics can add a personal touch to a form

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 41


Including Different Fonts
in the User Interface
• Font property: used to change the type, style, and size of the font

• Font guidelines:
–Use only one font type for all text in the interface
–Use Segoe UI font for Windows 7 or Windows Vista
–Avoid italics and underlining
–Limit bold text to titles, headings, and key items

• Change the form’s Font property before adding controls


–Controls will default to the font that is set for the form

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 42


Including Color in the User Interface
• Human eye is drawn to color before B&W

• Color guidelines:
–Use color sparingly
–Some people have trouble distinguishing colors
–What is “acceptable” in colors is subjective
–Color may have specific meaning in certain cultures
–Use black or dark text on a white or light background
–Use maximum of three different colors that complement each other
–Do not use color as the only means of identification

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 43


Borders and Sizing of Controls
• BorderStyle property: determines the style of a control’s border
–Settings: None, FixedSingle, Fixed3D

• Identifying labels should be set to None

• Labels that display output should be set to FixedSingle

• AutoSize property: determines if a label control automatically sizes to fit


its current contents
Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 44
Assigning Access Keys
• Access key:
– Allows user to select an object using Alt + access key
– May or may not appear underlined on the control’s text
• Can display temporarily or hide by pressing the Alt key
– Is not case sensitive

• Access key guidelines:


– Assign access keys to each control that can accept user input
(exceptions: OK and Cancel buttons)
– Each access key should be unique
– Follow Windows standards for choice of access keys

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 45


• Advantages of using access keys:
–User does not need mouse to navigate and activate controls
–Allows fast typists to keep hands on keyboard
–Facilitates use of the application by people with disabilities

• Include & in front of the character to be used as the access key:


–&Calculate Order → Calculate Order

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 46


Controlling the Tab Order
• TabIndex property:
–Determines the order in which a control receives the focus when the Tab key is pressed
–Starts at 0
–Assigned by default as the order in which controls are added to the form at design time
–Should be set to the order in which the user will want to access the controls

• Focus: the state of being able to accept user input

• Set TabIndex using the Properties window or the Tab Order option on the View
menu

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 47


17

0 1 14

2 3 15

4 5
16
6 7 8 9

10 11 18 20

12 13 19 21

Figure 2-12: Correct TabIndex values

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 48


THE END

Engr. Jenn P. Cabale Lecture 3 - OPERATORS AND EXPRESSIONS 50


Conditional Statements
Lecture 4
INTERMEDIATE PROGRAMMING

Engr. Jennelyn P. Cabale


Comparison Operators
• Comparison operators can be used to compare expressions such as two
numbers, two numerical expressions, or a number and a variable. The
result of the comparison is a Boolean value (true or false).

• In C# several types of data that can be compared:


–numbers (int, long, float, double, ushort, decimal, …)
–characters (char)
–Booleans (bool)
–References to objects, also known as object pointers (string, object, arrays and
others)
Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 2
Operator Action
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 3


Comparison of Integers and Characters
• When comparing integers and characters, we directly compare their
binary representation in memory.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 4


Comparison of References to Objects
• In .NET Framework there are
reference data types that do not
contain their value, but contain
the address of the memory in the
heap where their value is located.

• Strings, arrays and classes are


such types. They behave like a
pointer to some value and can
have the value null, i.e. no value.

• When comparing reference type


variables, we compare the
addresses they hold, i.e. we check
whether they point to the same
location in the memory, i.e. to the
same object.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 5


Logical Operators
• The logical operators && (logical AND) and || (logical OR) are only used
on Boolean expressions (values of type bool). In order for the result – of
comparing two expressions with the operator && – to be true (true),
both operands must have the value true. For instance:
• bool result = (2 < 3) && (3 < 4);

• Similarly, the operator || returns true if at least one of the two operands
has the value "true". Example:
• bool result = (2 < 3) || (1 == 2);

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 6


Conditional Statements "if" and "if-else"
if (Boolean expression)
{
Body of the conditional statement;
}

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 7


Conditional Statement "if-else"
if (Boolean expression)
{
Body of the conditional statement;
}
else
{
Body of the else statement;
}

• The format of the if-else structure consists of the reserved word if, Boolean expression, body
of a conditional statement, reserved word else and else-body statement. The body of else-
structure may consist of one or more operators, enclosed in curly brackets, same as the body
of a conditional statement.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 8


Nested "if" Statements

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 9


Sequences of "if-else-if-else-…"

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 10


Conditional "if" Statements – Good Practices
• Use blocks, surrounded by curly brackets {} after if and else in order to
avoid ambiguity

• Always format the code correctly by offsetting it with one tab inwards
after if and else, for readability and avoiding ambiguity.

• Prefer switch-case structure to of a series of if-else-if-else-… structures or


nested if-else statement, if possible.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 11


Conditional Statement "switch-case"
• The structure switch-case chooses which part of the programming code
to execute based on the calculated value of a certain expression (most
often of integer type).

• The selector is an expression returning a resulting value that can be


compared, like a number or string.

• The switch operator compares the result of the selector to every value
listed in the case labels in the body of the switch structure.

• If a match is found in a case label, the corresponding structure is


executed (simple or complex). If no match is found, the default statement
is executed (when such exists).

• The value of the selector must be calculated before comparing it to the


values inside the switch structure. The labels should not have repeating
values, they must be unique.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 12


Rules for Expressions in Switch
• It requires a selector, which is calculated to a certain value.

• The selector type could be an integer number, char, string or enum. If we


want to use for example an array or a float as a selector, it will not work.

• For non-integer data types, we should use a series of if statements.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 13


Using Multiple Labels

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 14


Good Practices When Using "switch-case"
• A good practice when using the switch statement is to put the default statement at the end, in order
to have easier to read code.

• It’s good to place first the cases, which handle the most common situations. Case statements, which
handle situations occurring rarely, can be placed at the end of the structure.

• If the values in the case labels are integer, it’s recommended that they be arranged in ascending order.

• If the values in the case labels are of character type, it’s recommended that the case labels are sorted
alphabetically.

• It’s advisable to always use a default block to handle situations that cannot be processed in the normal
operation of the program. If in the normal operation of the program the default block should not be
reachable, you could put in it a code reporting an error.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 15


Example
• Mountain Biking wants an application that allows
the store clerk to enter an item’s price and the
quantity purchased by a customer. The
application should calculate the total amount the
customer owes by multiplying the price by the
quantity purchased and then subtracting the
discount. It then should display the total amount
owed. Mountain Biking gives customers a 10%
discount when the quantity purchased is over
five; otherwise, it gives a 5% discount.

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 16


Example
• Auction House application displays highest and lowest of two bids
entered by the user

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 18


Example
• Addition and Subtraction Calculator application: displays the sum or
difference of two numbers

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 20


Example
• Check boxes: used to offer the user one or more independent and
nonexclusive items from which to choose

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 22


THE END

Engr. Jenn P. Cabale Lecture 4 - CONDITIONAL STATEMENTS 25


Looping Statements
Lecture 5
INTERMEDIATE PROGRAMMING

Engr. Jennelyn P. Cabale


Loop
• A loop is a basic programming construct that allows repeated execution
of a fragment of source code. Depending on the type of the loop, the
code in it is repeated a fixed number of times or repeats until a given
condition is true (exists).

• Loops that never end are called infinite loops. Using an infinite loop is
rarely needed except in cases where somewhere in the body of the loop
a break operator is used to terminate its execution prematurely.

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 2


While Loops
while (condition)
{
loop body;
}

• condition is any expression that returns a Boolean result – true or false.


It determines how long the loop body will be repeated and is called
the loop condition.

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 3


Do-While Loops
• The do-while loop is similar to the while loop, but it checks the
condition after each execution of its loop body. This type of loops is
called loops with condition at the end (post-test loop). A do-while
loop looks like this:

do
{
executable code;
} while (condition);

• Initially the loop body is executed. Then its condition is checked. If it


is true, the loop’s body is repeated, otherwise the loop ends. This
logic is repeated until the condition of the loop is broken. The body
of the loop is executed at least once. If the loop’s condition is
constantly true, the loop never ends.

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 4


For Loops

• They contain an initialization block


(A), condition (B), body (D) and
updating commands for the loop
variables (C).

for (initialization; condition; update)


{
loop's body;
}

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 5


Example : Printing 1-10

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 6


Example
• The Getting to a Million Club wants an application that allows a club
member to enter two items: the amount of money deposited into a
savings account at the beginning of the year and the annual interest rate.
The application should display the balance in the savings account at the
end of the year, assuming the interest is compounded annually and no
withdrawals or additional deposits are made.

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 8


Example
• The Sales Express Company wants an application
that displays the average amount the company
sold during the prior year. The sales manager will
enter the amount of each salesperson’s sales.
The application will use a counter to keep track of
the number of sales amounts entered and an
accumulator to total the sales amounts. When
the sales manager has finished entering the sales
amounts, the application will calculate the
average sales amount by dividing the value
stored in the accumulator by the value stored in
the counter. It then will display the average sales
amount. If the sales manager does not enter any
sales amounts, the application should display the
message “N/A” (for “not available”).

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 10


The InputBox Function
• Displays a predefined dialog box that allows the user to enter data
• Contains a text message, an OK button, a Cancel button, and an input
area
• Syntax:
–InputBox(Prompt, Title, defaultResponse)

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 12


Including a List Box in an Interface
• Displays a list of choices from which the user can select zero or more
choices

• SelectionMode property: controls the number of choices a user can


select
–None: user can scroll but not select anything
–One: user can select one item
–MultiSimple and MultiExtended: user can select multiple items

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 13


Adding Items to a List Box
• Items collection: a collection of the items in a list box

• Collection: a group of one or more individual objects treated as one unit

• Load event of a form: occurs when an application is started and the form
is displayed for the first time

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 14


• Syntax:
–object.Items.Add(item);

• Add method: adds an item to the list box’s Items collection


• Items to be added must be converted to String
• String Collection Editor window can be used to specify list items during
design time

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 15


Example

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 16


Example

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 19


Sorted Property
• Determines if the list box items are sorted
• Sort order is dictionary order

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 21


Accessing Items in a List Box
• Index:
–A unique number that identifies an item in a collection
–Is zero-relative: the first item has index of 0

• Syntax:
–object.Items(Index);

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 23


Determining the Number of Items
in a List Box
• Items.Count property: stores the number of items in a list box
–Count value is always one higher than the highest index in the list box

• Syntax:
–object.Items.Count;

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 24


The SelectedItem and SelectedIndex Properties
• SelectedItem property:
–Contains the value of the selected item in the list
–If nothing is selected, it contains the empty string

• SelectedIndex property:
–Contains the index of the selected item in the list
–If nothing is selected, it contains the value -1

• Default list box item:


–the item that is selected by default when the interface first appears

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 25


THE END

Engr. Jenn P. Cabale Lecture 5 - LOOPING STATEMENTS 30


C# Array
Lecture 6
INTERMEDIATE PROGRAMMING

Engr. Jennelyn P. Cabale


C# Arrays
• An array is a group of like-typed variables that are referred to by a common
name.

• Each data item is called an element of the array.

• The data types of the elements may be any valid data type like char, int, float,
etc. and the elements are stored in a contiguous location.

• Length of the array specifies the number of elements present in the array.

• The allocation of memory for the arrays is done dynamically.


Important Points to Remember About Arrays in C#
• All arrays are dynamically allocated.

• Find their length using member length.

• Array variable can also be declared like other variables with [] after the data type.

• The variables in the array are ordered and each has an index beginning from 0.

• C# array is an object of base type System.Array.

• Default values of numeric array and reference type elements are set to be respectively zero and null.

• Array elements can be of any type, including an array type.

• Array types are reference types which are derived from the abstract base type Array.
Array Declaration
• Syntax : • Example :
< Data Type > [ ] < Name_Array >
int[] x;
string[] s;
double[] d;
Student[] stud1;
Array Initialization
• Syntax :
type [ ] < Name_Array > = new < datatype > [size];

• Example:
int[] intArray1 = new int[5];
int[] intArray2 = new int[5]{1, 2, 3, 4, 5};
int[] intArray3 = {1, 2, 3, 4, 5};
Initialization of an Array after Declaration
Example: Example : Wrong Declaration for initializing
an array
// Declaration of the array
string[] str1, str2; // compile-time error: must give size of an
array
// Initialization of array int[] intArray = new int[];
str1 = new string[5]{ “Element 1”, “Element
2”, “Element 3”, “Element 4”, “Element 5” }; // error : wrong initialization of an array
string[] str1;
str2 = new string[5]{ “Element 1”, “Element str1 = {“Element 1”, “Element 2”, “Element
2”, “Element 3”, “Element 4”, “Element 5” }; 3”, “Element 4” };
Accessing Array Elements
One Dimensional Array
Multidimensional Arrays
• It is also known as a Rectangular Array in C#
• It can be a 2D-array or 3D-array or more.
• To storing and accessing the values of the array, one required the nested loop.
THE END

You might also like