Duhok Polytechnic University Amedi Technical Institute/ IT Dept. By Halkawt Rajab Hussain 2016-04-02
Overview. C# program structure. Variables and Constant. Conditional statement (if, if/else, nested if and switch statement). Repetition Control Structures 1. while. 2. Do while. 3. for Statement. Flow control statements (continue and break) Array ( One and Two dimensional array) 10/16/2016 1
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 highlevel languages on different computer platforms and architectures. 10/16/2016 2
Overview. Anders Hejlsberg 10/16/2016 3
C# program structure: Code NamespaceBlock namespace NamespaceName NamespaceBody identifier(system) Class Block public class Class Name ClassBody identifier(myclass) Class Members 10/16/2016 4
C# program structure: Creating Hello World Program: A C# program consists of the following parts: 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": 10/16/2016 5
C# program structure: using System; namespace HelloWorldApplication class HelloWorld static void Main(string[] args) /* my first program in C# */ Console.WriteLine("Hello World"); Console.ReadKey(); 10/16/2016 6
Variables and Constant Unified Type System: Types Value Types reference Types Pointer Simple Types Enums Structs Int, bool, double, long, ulong, byte, short, ushort, char, float, sbyte, unit, decimal. Class Interface Delegates Array 10/16/2016 7
Variables and Constant Defining Variables Syntax for variable definition in C# is: <data_type> <variable_list>; Declar Variables: byte MyByteVariable; int _Value123; ulong AVeryLargeNumber; Naming Your Variables: Each variable that you use in your C# code must have a name. Variable names are interpreted as identifiers by the C# compiler and must follow the naming conventions for an identifier: The first character in an identifier must start with an uppercase or lowercase letter or an underscore character. The characters following the first character can be any of the following: An uppercase or lowercase letter A digit An underscore 10/16/2016 8
Variables and Constant Using Default Values for Variables: int MyVariable; System.Console.WriteLine(MyVariable); ******* OutPut: error CS0165: Use of unassigned local variable 'MyVariable' Initializing Variables: variable_name = value; int d = 3, f = 5; /* initializing d and f. */ byte z = 22; /* initializes z. */ double pi = 3.14159; /* declares an approximation of pi. */ char x = 'x'; /* the variable x has the value 'x'. */ 10/16/2016 9
Variables and Constant Accepting Values from User: The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable. For example/ int num; num = Convert.ToInt32(Console.ReadLine()); 10/16/2016 10
Variables and Constant 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. 10/16/2016 11
Variables and Constant Value Type : namespace DataTypeApplication class Program static void Main(string[] args) Console.WriteLine("Size of int: 0", sizeof(int)); Console.ReadLine(); Result Size of int: 4 10/16/2016 12
Variables and Constant 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. 10/16/2016 13
Variables and Constant 1. 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. The other hand, when an object type is converted to a value type, it is called unboxing. Example: object obj; int i; obj = 100; // this is boxing i=(int) obj; //unboxing 10/16/2016 14
Variables and Constant 2. 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. Dynamic types are similar to object types except that type checking for object type variables takes place at compile time. Syntax for declaring a dynamic type is: dynamic <variable_name> = value; For example, dynamic d = 20; 10/16/2016 15
Variables and Constant 3. 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, String str = "Tutorials Point"; @"Tutorials Point"; 10/16/2016 16
Variables and Constant 4. 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: type* identifier; For example, char* cptr; int* iptr; 10/16/2016 17
Variables and Constant Constant: Constants: are variables whose values, once defined, can not be changed by the program. Constant variables are declared using the const keyword, like: const double PI = 3.142; Constant variables must be initialized as they are declared. It is a syntax error to write: const int MARKS; It is conventional to use capital letters when naming constant variables. 10/16/2016 18
Conditional statement Conditional Logic: To be able to control the flow in your program is important in every programming language. The two most important techniques are: 1. The if Statement 2. The switch Statement 1. If Statement: An if statement allows you to take different paths of logic, depending on a given condition. When the condition evaluates to a boolean true, a block of code for that true condition will execute. bool mytest; mytest=false; if (mytest==false) MessageBox.Show("Hello"); 10/16/2016 19
Conditional statement If we have more than one line of code that that shall be executed, we need to use braces. bool mytest; mytest=false; if (mytest == false) MessageBox.Show("Hello1"); MessageBox.Show("Hello2"); 10/16/2016 20
Conditional statement 2. If..else Statement: For more complex logic we use the if else statement. bool mytest; mytest=true; if (mytest == false) MessageBox.Show("Hello1"); else MessageBox.Show("Hello2"); 10/16/2016 21
Conditional statement 3. Nested If..else Statement: Start int mytest; mytest=2; if (mytest == 1) MessageBox.Show("Hello1"); else if (mytest == 2) MessageBox.Show("Hello2"); else MessageBox.Show("Hello3"); S1 F Is This True F S2 T Is This True T S3 End 10/16/2016 22
Conditional statement 4. The? : Operator: We have covered conditional operator? : It has the following general form: Exp1? Exp2 : Exp3; Example in if else statement x=10; If(x>10) x/=2 else x/=4; Example in conditional operator x=10; x=x>10? x/2 : x/4; Homework// Convert the if..else if conditional statement that shown bellow, to form of conditional operator?:. int z=10; int x = 10; int y = 5; if (x == y) Console.WriteLine(z += x); else if (x == z) Console.WriteLine(z += y); else Console.WriteLine(z += 1); 10/16/2016 23
Conditional statement 5. Switch Statement: Another form of selection statement is the switch statement, which executes a set of logic depending on the value of a given parameter. 10/16/2016 24
Conditional statement Example: switch (mytest) case 1: MessageBox.Show("Hello1"); break; case 2: MessageBox.Show("Hello2"); break; default: MessageBox.Show("Hello3"); break; 5. Repetition Control Structures:(while, Do while, for Statements) 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: 10/16/2016 25
Repetition Control Structures Loop: 1. While Loop: A while loop statement in C# repeatedly executes a target statement as long as a given condition is true. Syntax The syntax of a while loop in C# is: while(condition) statement(s); 10/16/2016 26
Repetition Control Structures Example/// using System; namespace Loops class Program static void Main(string[] args) /* local variable definition */ int a = 10; while loop execution */ while (a < 20) Console.WriteLine("value of a: 0", a); a++; Console.ReadLine(); 10/16/2016 27
Repetition Control Structures 2. Do While Loop: Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop checks its condition at the end of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax: The syntax of a do...while loop in C# is: do statement(s); while( condition ); 10/16/2016 28
Repetition Control Structures Example using System; namespace Loops class Program static void Main(string[] args) /* local variable definition */ int a = 10; /* do loop execution */ do Console.WriteLine("value of a: 0", a); a = a + 1; while (a < 20); Console.ReadLine(); 10/16/2016 29
Repetition Control Structures 3. For Loop: 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: The syntax of a for loop in C# is: for ( int ; condition; increment ) statement(s); 10/16/2016 30
Repetition Control Structures Example// using System; namespace Loops class Program static void Main(string[] args) /* for loop execution */ for (int a = 10; a < 20; a = a + 1) Console.WriteLine("value of a: 0", a); Console.ReadLine(); 10/16/2016 31
Repetition Control Structures 5. Foreach Loop: Foreach uses no integer index. Instead, it is used on a collection it returns each element in order. Example_1 Example_2 using System; string s = "ABC"; foreach(char c in s) Console.WriteLine(c); class Program static void Main() string[] pets = "dog", "cat", "bird" ; Homework. Given an example using nested loops? //... Loop with the foreach keyword. foreach (string value in pets) Console.WriteLine(value); 10/16/2016 32
Flow Control(Continue and Break) Flow Control 1. Continue: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. using System; namespace Loops class Program static void Main(string[] args) int a = 10; do if (a == 15) a = a + 1; continue; Console.WriteLine("value of a: 0", a); a++; while (a < 20); Console.ReadLine(); 10/16/2016 33
Flow Control(Continue and Break) 2. Break: The break statement in C# has following two usage: 1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. 2. It can be used to terminate a case in the switch statement. using System; namespace Loops class Program static void Main(string[] args) int a = 10; while (a < 20) Console.WriteLine("value of a: 0", a); a++; if (a > 15) break; //End Loop Console.ReadLine(); 3. Return statements..?????? in void and function methods 10/16/2016 34
Array in C# Array An array stores a fixed-size sequential collection of elements of the same type. array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contigeous memory locations. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays: datatype[] arrayname; for Example.. int[] marks; Initializing an Array: Array is a reference type, so you need to use the new keyword to create an instance of the array. For example, int[] marks= new int[10]; 10/16/2016 35
Array in C# Assigning Values to an Array: You can assign values to individual array elements, by using the index number, like: int[] marks= new int[10]; marks[0] = 80; You can assign values to the array at the time of declaration as shown: int[] balance = 2340.0, 4523.69, 3421.0; You can also create and initialize an array as shown: int[] marks = new int[5] 99, 98, 92, 97, 95; You may also omit the size of the array as shown: int[] marks = new int[] 99, 98, 92, 97, 95; You can copy an array variable into another target array variable In such case, both the target and source point to the same memory location: int [] marks = new int[] 99, 98, 92, 97, 95; int[] score = marks 10/16/2016 36
Array in C# Accessing Array Elements: An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example, double salary = balance[9]; Example. using System; namespace ArrayApplication class MyArray static void Main(string[] args) int [] n = new int[10]; int i,j; for ( i = 0; i < 10; i++ ) n[ i ] = i + 100; for (j = 0; j < 10; j++ ) Console.WriteLine("Element[0] = 1", j, n[j]); Console.ReadKey(); Homework Display the elements of array n[], using the foreach loop? 10/16/2016 37
Array in C# 1. One Dimensional Array: You can declare a single-dimensional array of five integers as shown in the following example: int[] array = new int[5]; An array that stores string elements can be declared in the same way. For example: string[] stringarray = new string[6]; Initializing array int[] array1 = new int[] 1, 3, 5, 7, 9 ; string[] weekdays = "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ; int[] array2 = 1, 3, 5, 7, 9 ; string[] weekdays2 = "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ; int[] array3; array3 = new int[] 1, 3, 5, 7, 9 ; // OK //array3 = 1, 3, 5, 7, 9; // Error 10/16/2016 38
Array in C# Example Write a program in C# using Console application to get one dimension array string[5], input name of five subjects and display them? using System; using System.Collections.Generic; using System.Linq; using System.Text; Console.WriteLine("All the element of Books array is:\n\n"); namespace One_Dimensional_Array class Program static void Main(string[] args) //Declaring single dimensional array string[] Books = new string[5]; Books[0] = "C#"; Books[1] = "Java"; Books[2] = "VB.NET"; Books[3] = "C++"; Books[4] = "C"; int i = 0; //Formatting Output Console.Write("\t1\t2\t3\t4\t5\n\n\t"); for (i = 0; i < 5; i++) Console.Write("0\t", Books[i]); Console.ReadLine(); 10/16/2016 39
Array in C# Homework 1. Write a program to find the size or the length of 1d array? 2. If we have array size of 5 integer number how to resize it at run time to add 10 integer numbers? 3. Write a program in c# to create an array with different data type? 4. How to sort an integer number? sol int[] array = new int[] 3, 1, 4, 5, 2 ; Array.Sort(array); foreach (var str in array) Console.writeline(str.ToString()); 5. Sort an Integer array in descending order? 10/16/2016 40
Array in C# 2. Two Dimensional Array: C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can declare a 2-dimensional array of strings as: string [,] names; or, a 3-dimensional array of int variables as: int [,, ] m; The simplest form of the multidimensional array is the 2-dimensional array. A 2- dimensional array is a list of one-dimensional arrays. Initializing Two-Dimensional Arrays: Multidimensional arrays may be initialized by specifying bracketed values for each row. The following array is with 3 rows and each row has 4 columns. int [,] a = int [3,4] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11; Accessing Two-Dimensional Array Elements An element in 2-dimensional array is accessed by using the subscripts.that is, row index and column index of the array. For example, int val = a[2,3]; 10/16/2016 41
Array in C# Homework 1. Write a program to creates a 2x2 string array and then prints out all four elements using while loop? 2. What is the value of the UpperBound(0) method of the 2d array that show bellow double[,] price= double[10,5]; 3. How to know home many row in the array of two dimension array? Sol. int[,] n= new int[,]; Console.Writline(n.getliength(0)); 4. What is the output for this segment code? string[] names = new string "John", "Tom", "Peter" ; foreach (string name in names) if (name == "Tom") continue; Console.WriteLine(name); 10/16/2016 42
Thanks Any Questions 10/16/2016 43