PROG103 Madrid - Advance Computer Programming 2 C
PROG103 Madrid - Advance Computer Programming 2 C
IGNATIUS
TECHNICAL INSTITUTE OF BUSINESS AND ARTS
C# is used to develop web apps, desktop apps, mobile apps, games and much
more.
C# is pronounced "C-Sharp".
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
And much, much more!
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
C# - Environment
In this chapter, we will discuss the tools required for creating C#
programming. We have already mentioned that C# is part of .Net framework
and is used for writing .Net applications. Therefore, before discussing the
available tools for running a C# program, let us understand how C# relates to
the .Net framework.
The .Net framework is a revolutionary platform that helps you to write the
following types of applications −
Windows applications
Web applications
Web services
The .Net framework applications are multi-platform applications. The
framework has been designed in such a way that it can be used from any of
the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these
languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the
client languages such as C#. Following are some of the components of the .Net
framework −
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World"
The most common method to output something in C# is WriteLine(), but you can
also use Write().
The difference is that WriteLine() prints the output on a new line each time,
while Write() prints on the same line (note that you should remember to add
spaces when needed, for better readability):
_____________2. The first line of the program - the using keyword is used to include
the namespace in the program. A program generally has multiple using statements.
_____________4. This is the method which is the entry point for all c# programs.
_____________5. This metyhod specifies its behavior with the statement to write
the output.
Test II
Insert the missing part of the code below to output "Hello World!".
Lesson 3
Advance Computer Programming 2
C# Basic Syntax and Comments
The using keyword is used for including the namespaces in the program. A
program can include multiple using statements.
Member Variables
Variables are attributes or data members of a class, used for storing data. In
the preceding program, the Rectangle class has two member variables
named length and width.
Member Functions
Functions are set of statements that perform a specific task. The member
functions of a class are declared within the class. Our sample class Rectangle
contains three member functions: AcceptDetails, GetArea and Display.
Instantiating a Class
Identifiers
C# Keywords
C# Variables
In C#, there are different types of variables (defined with different keywords),
for example:
To create a variable, you must specify the type and assign it a value:
Where type is a C# type (such as int or string), and variableName is the name
of the variable (such as x or name). The equal sign is used to assign values to
the variable.
To create a variable that should store text, look at the following example:
Sample Output
To create a variable that should store a number, look at the following example:
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Constants
However, you can add the const keyword if you don't want others (or yourself)
to overwrite existing values (this will declare the variable as "constant", which
means unchangeable and read-only):
Other Types
The WriteLine() method is often used to display variable values to the console
window.
You can also use the + character to add a variable to another variable:
Declare Many Variables
To declare more than one variable of the same type, use a comma-separated
list:
C# Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain
whitespace
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or double) cannot be used
as names
Activity No. 4
___________2. This Variable stores values with two states: true or false.
___________3. This Variable stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
___________4. This variable stores floating point numbers, with decimals, such
as 19.99 or -19.99
___________5. This Variable stores text, such as "Hello World". String values
are surrounded by double quotes.
Application: 5pts
Lesson 5
Advance Computer Programming 2
C# Data Types
Value types
Reference types
Pointer types
C# Data Types
Sample
Sample Output
Value Type
Value type variables can be assigned a value directly. They are derived from
the class System.ValueType.
The value types directly contain data. Some examples are int, char, and float,
which stores numbers, alphabets, and floating point numbers, respectively.
When you declare an int type, the system allocates memory to store the value.
A data type specifies the size and type of variable values. It is important to use
the correct data type for the corresponding variable; to avoid errors, to save
time and memory, but it will also make your code more maintainable and
readable. The most common data types are:
Numbers
Integer Types
Int
The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the preferred
data type when we create variables with a numeric value.
Example:
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
Floating Point Types
You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038.
Note that you should end the value with an "F":
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you can end the value with a "D" (although not required):
Reference Type
The reference types do not contain the actual data stored in a variable, but
they contain a reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the
reference types can refer to a memory location. If the data in the memory
location is changed by one of the variables, the other variable automatically
reflects this change in value. Example of built-in reference types
are: object, dynamic, and string.
Object Type
The Object Type is the ultimate base class for all data types in C# Common
Type System (CTS). Object is an alias for System.Object class. The object types
can be assigned values of any other types, value types, reference types,
predefined or user-defined types. However, before assigning values, it needs
type conversion.
When a value type is converted to object type, it is called boxing and on the
other hand, when an object type is converted to a value type, it is
called unboxing.
Dynamic Type
You can store any type of value in the dynamic data type variable. Type
checking for these types of variables takes place at run-time.
Syntax for declaring a dynamic type is −
For example,
Dynamic types are similar to object types except that type checking for object
type variables takes place at compile time, whereas that for the dynamic type
variables takes place at run time.
Pointer Type
Pointer type variables store the memory address of another type. Pointers in
C# have the same capabilities as the pointers in C or C++.
Syntax for declaring a pointer type is
For example,
Booleans
A boolean data type is declared with the bool keyword and can only take the
values true or false:
Example
Boolean values are mostly used for conditional testing, which you will learn
more about in a later chapter.
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Strings
The string data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
Example
String Type
The String Type allows you to assign any string values to a variable. The
string type is an alias for the System.String class. It is derived from object
type. The value for a string type can be assigned using string literals in two
forms: quoted and @quoted.
For example,
_____________ 1. This data types directly contain data. Some examples are int,
char, and float, which stores numbers, alphabets, and floating point numbers,
respectively.
______________2. This data types do not contain the actual data stored in a
variable, but they contain a reference to the variables.
______________4. This data type is declared with the bool keyword and can only
take the values true or false:
Application:
6 – 10. Add the correct data type for the following variables:
Type casting is when you assign a value of one data type to another type.
Implicit Casting
Example:
Explicit Casting
____________1. This These conversions are done explicitly by users using the
pre-defined functions.
In the following example, the user can input his or hers username, which is
stored in the variable userName. Then we print the value of userName:
Sample Output
User Input and Numbers
Like the error message says, you cannot implicitly convert type 'string' to 'int'.
Luckily, for you, you just learned from the previous chapter (Type Casting),
that you can convert any type explicitly, by using one of
the Convert.To methods:
Activity No. 7 (10pts.)
1. Fill in the missing parts to get user input, stored in the variable userName:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Comparison Operators
This lesson explains the arithmetic, relational, logical, bitwise, assignment, and
other operators one by one.
Arithmetic Operators
Relational Operators
Following table shows all the relational operators supported by C#. Assume
variable A holds 10 and variable B holds 20, then
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth
tables for &, |, and ^ are as follows:
Assume if A = 60; and B = 13; then in the binary format they are as follows −
A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then
Assignment Operators
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
There are few other important operators including sizeof, typeof and ?
: supported by C#.
C# Comparison Operators
Logical operators are used to determine the logic between variables or values:
Operator Precedence in C#
1.
2.
3.
4.
5.
6.
7.
Test II Application
C# Strings
Sample Program
String Length
Sample Program
Sample Output
Other Methods
There are many string methods available, for example ToUpper() and ToLower(),
which returns a copy of the string converted to uppercase or lowercase:
Sample Program
Sample Output
String Concatenation
You can also use the string.Concat() method to concatenate two strings:
String Interpolation
Sample Output
Access Strings
You can access the characters in a string by referring to its index number
inside square brackets [].
Special Characters
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string
characters:
Sample Output
1. Fill in the missing part to create a greeting variable of type string and
assign it the value Hello.
4. Access the first character (H) in myString and print the result:
Lesson 11
Advance Computer Programming 2
C# Booleans
C# Booleans
Very often, in programming, you will need a data type that can only have one of
two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, C# has a bool data type, which can take the values true or false.
Boolean Values
A boolean type is declared with the bool keyword and can only take the
values true or false:
You can use a comparison operator, such as the greater than (>) operator to
find out if an expression (or a variable) is true:
Sample Program
Sample Output
Or even easier:
Sample Program
Sample Output
Sample program
Sample Output
Sample Program
Sample Output
Activity No. 11
1. Fill in the missing parts to print the values True and False:
You can use these conditions to perform different actions for different
decisions.
The if Statement
Syntax
In the example below, we test two values to find out if 20 is greater than 18. If the
condition is True, print some text:
Sample Program Sample Output
Example explained
In the example above we use two variables, x and y, to test whether x is greater
than y (using the > operator). As x is 20, and y is 18, and we know that 20 is
greater than 18, we print to the screen that "x is greater than y".
The else Statement
Syntax
Example explained
In the example above, time (20) is greater than 18, so the condition is False.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
The else if Statement
Use the else if statement to specify a new condition if the first condition
is False.
Syntax
In the example above, time (22) is greater than 10, so the first
condition is False. The next condition, in the else if statement, is also False,
so we move on to the else condition since condition1 and condition2 is
both False - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Syntax
C# Switch Statements
Use the switch statement to select one of many code blocks to be executed.
Syntax
The example below uses the weekday number to calculate the weekday name:
Sample Program Sample Output
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
The default keyword is optional and specifies some code to run if there is no
case match:
2. Complete the switch statement, and add the correct keyword at the end to
specify some code to run if there is no case match in the switch statement.
Lesson 14
Advance Computer Programming 2
C# Loops
There may be a situation, when you need to execute a block of code several
number of times. In general, the statements are executed sequentially: The
first statement in a function is executed first, followed by the second, and so
on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or a group of statements
multiple times and following is the general from of a loop statement in most of
the programming languages
C# provides following types of loop to handle looping requirements. Click the
following links to check their detail.
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
C# provides the following control statements.
Infinite Loop
A loop becomes infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that
form the for loop are required, you can make an endless loop by leaving the
conditional expression empty.
Example:
Test I.
_____________5. It Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
Lesson 15
Advance Computer Programming 2
C# While Loop /Do While Loop
A while loop statement in C# repeatedly executes a target statement as long as a given
condition is true.
Syntax
Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body is skipped and the
first statement after the while loop is executed.
In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:
Sample Program Sample Output
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.
Syntax
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
Syntax
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Nested Loop
C# allows using one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax
A final note on loop nesting is that you can put any type of loop inside of any
other type of loop.
Assessment No. 16 (10 pts.)
Syntax
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
C# Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.