Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Similar documents
Methods: A Deeper Look

CT 229 Java Syntax Continued

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

C Functions. 5.2 Program Modules in C

Chapter 6: Using Arrays

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Functions. Systems Programming Concepts

Pace University. Fundamental Concepts of CS121 1

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

1001ICT Introduction To Programming Lecture Notes

Introduction to Programming

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Introduction to Programming Using Java (98-388)

CSC Java Programming, Fall Java Data Types and Control Constructs

Chapter 3 - Functions

Functions and Recursion

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

CSE123. Program Design and Modular Programming Functions 1-1

What did we talk about last time? Examples switch statements

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

CS313D: ADVANCED PROGRAMMING LANGUAGE

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Macro Programming Reference Guide. Copyright 2005 Scott Martinez

Methods CSC 121 Fall 2016 Howard Rosenthal

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Variables. location where in memory is the information stored type what sort of information is stored in that memory

Arithmetic and Logic Blocks

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

204111: Computer and Programming

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

4/29/03 Doc 25 C# Arrays, Indexers & Exceptions slide # 1

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Operators. Java operators are classified into three categories:

Methods CSC 121 Spring 2017 Howard Rosenthal

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Methods CSC 121 Fall 2014 Howard Rosenthal

How to Design Programs Languages

Flow Control. CSC215 Lecture

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Basic types and definitions. Chapter 3 of Thompson

Introduction to C Language

Accelerating Information Technology Innovation

(Not Quite) Minijava

Downloaded from Chapter 2. Functions

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

DEPARTMENT OF MATHS, MJ COLLEGE

The Java language has a wide variety of modifiers, including the following:

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

CS111: PROGRAMMING LANGUAGE II

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

The Warhol Language Reference Manual

FORM 2 (Please put your name and form # on the scantron!!!!)

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Introduction to C# Applications

C Programs: Simple Statements and Expressions

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:


INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Quick Reference Guide

First Name: Last: ID# 1. Hexadecimal uses the symbols 1, 2, 3, 4, 5, 6, 7 8, 9, A, B, C, D, E, F,G.

ECE 122. Engineering Problem Solving with Java

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS110: PROGRAMMING LANGUAGE I

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Darshan Institute of Engineering & Technology for Diploma Studies

Fundamentals of Computer Programming Using C

Scheme Quick Reference

The pixelman Language Reference Manual. Anthony Chan, Teresa Choe, Gabriel Kramer-Garcia, Brian Tsau

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions

Fundamentals of Programming & Procedural Programming

Scheme Quick Reference

The return Statement

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

3. You are writing code for a business application by using C#. You write the following statement to declare an array:

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Arrays and Collections. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Object-Based Programming. Programming with Objects

CS 61B Data Structures and Programming Methodology. June David Sun

ECE 122. Engineering Problem Solving with Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

Arrays. Structure programming. Section-(6) Array Initialization. <Type> [] identifier;

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Transcription:

INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals alfy@kfupm.edu.sa Objectives Learn about the C# operators and how they are evaluated in expressions Learn the jump and selection constructs Learn the loop constructs Learn how to declare, instantiate, initialize and use arrays 2 1

Operators & Expressions An expression is a sequence of operators and operands that specifies a computation C# has almost identical set of operators as Java Operands can be variables, constants, method calls, or an expression The precedence of the operators controls the order in which the individual operators are evaluated Operators of the same precedence are evaluated according to their associativity Except for assignment operator, all other binary operators are left-associative and are evaluated from left to right. The assignment operator, the unary operator and the conditional operator are evaluated from right to left. Category Operators Primary [ ] dot new typeof sizeof Unary + -! ~ ++x --x (casting)x Multiplicative * / % Additive + - Shift << >> Relational and type testing Equality ==!= Logical AND & Logical XOR Logical OR Conditional AND < > <= >= is as ^ && Conditional OR Conditional?: Assignment = *= /= %= += -= <<= >>= &= ^= = 3 Operators The typeof operator is used to obtain the System.Type object for a type. 1. using System; 2. class Test 3. { 4. static void Main() { 5. Type t1 = typeof(int); 6. Type t2 = typeof(string); 7. Console.WriteLine(t1.FullName); 8. Console.WriteLine(t2.FullName); 9. } 10. } 4 2

Allows the user to perform common math calculations Constants Math.PI = 3.1415926535 Math.E = 2.7182818285 Using methods Math.MethodName(argument1, arument2, ) area = Math.PI * Math.Pow(radius, 2); Math Class Method Description Exa m p le Abs( x ) absolute value of x Abs( 23.7 ) is 23.7 Abs( 0 ) is 0 Abs( -23.7 ) is 23.7 Ceiling( x ) rounds x to the smallest integer not less than x Ceiling( 9.2 ) is 10.0 Ceiling( -9.8 ) is -9.0 Cos( x ) trigonometric cosine of x Cos( 0.0 ) is 1.0 (x in radians) Exp( x ) exponential method ex Exp( 1.0 ) is approximately 2.7182818284590451 Exp( 2.0 ) is approximately 7.3890560989306504 Floor( x ) rounds x to the largest integer Floor( 9.2 ) is 9.0 not greater than x Floor( -9.8 ) is -10.0 Log( x ) natural logarithm of x (base e) Log( 2.7182818284590451 ) is approximately 1.0 Log( 7.3890560989306504 ) is approximately 2.0 Max( x, y ) larger value of x and y Max( 2.3, 12.7 ) is 12.7 (also has versions for float, Max( -2.3, -12.7 ) is -2.3 int and long values) Min( x, y ) smaller value of x and y Min( 2.3, 12.7 ) is 2.3 (also has versions for float, Min( -2.3, -12.7 ) is -12.7 int and long values) Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 Pow( 9.0,.5 ) is 3.0 Sin( x ) trigonometric sine of x Sin( 0.0 ) is 0.0 (x in radians) Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0 Sqrt( 9.0 ) is 3.0 Tan( x ) trigonometric tangent of x Tan( 0.0 ) is 0.0 (x in radians) 5 Random Numbers Generated in the.net Framework by making use of the System.Random class Random x = new Random(); Generate a random whole number >= 1 and < 2,147,483,647 int rnum = x.next(); Generate a random whole number >= 5 and < 10 int rnum = x.next(5, 10); Generate a random whole number >= 0 and < 10 int rnum = x.next(10); Generate a random number >= 0.0 and < 1.0 double rnum = x.nextdouble(); 6 3

Flow Control Structures C# statements are evaluated in order (sequential flow) unless there is a flow control statement Unconditional branching statements (jump) Method invocation return (terminate current method and return to the invoking method) continue (jump to the next loop iteration) break (breaking a loop) Throw (exceptions) goto (jump to a labeled statement; but not recommended) Conditional branching statements (decision making, selection) if, if-else, if-else-if statements switch statement Loops (Repetition) Iterative statements (while, do-while, for, foreach) Recursive methods 7 Method Invocation 1. using System; return 2. class Test 3. { 4. static void Main() { 5. int x = 5, y = 8; 6. int z = Max(x, y); 7. Console.WriteLine( the max of {0} and {1} is {2}, 8. x, y, z); 9. Console.WriteLine( the max of {0} and {1} is {2}, 10. x, y, Math.Max(x, y)); 11. } 12. 13. static int Max(int a, int b){ 14. return a>b? a: b; 15. } 16. } 8 4

Selection Statements C# offers the same basic types of selection statements as Java if - else statement (2-way branching) false Grade >= 60 true print Failed print Passed 1. if (grade >= 60) 2. Console.WriteLine( Passed"); 3. else 4. Console.WriteLine( Failed"); 9 Selection Statements You can have if without else (one-way branching) Grade >= 60 true print Passed false 1. if (grade >= 60) 2. Console.WriteLine( Passed"); 10 5

Selection Statements switch statement Has similar syntax as in Java. Unlike Java, automatic fall-through between cases (if a break statement t tis not used) is not allowed in C#. explicitly use a break or goto statement to indicate where control should jump to. 1. int a = 2; 2. switch(a) { 3. case 1: 4. Console.WriteLine("a>0"); 5. goto case 2; 6. case 2: 7. Console.WriteLine(" and a>1"); 8. break; 9. default: 10. Console.WriteLine("a is not set"); 11. break; 12. } 11 Selection Statements switch statement An exception to this rule is when a case does not specify an action as in the following example: 1. switch(a) { 2. case 1: 3. case 2: 4. Console.WriteLine(" and a>0"); 5. break; 6. default: 7. Console.WriteLine( WriteLine("a is not set"); 8. break; 9. } 12 6

Conditional Operator The conditional operator returns one of two values, depending upon the value of a boolean expression. int i = (x > y)? 1 : 0 ; Equivalent to int i; if(x>y) i=1; else i=0; 13 Iteration Statements While loop A 'while' loop executes a statement, or a block of statements, repeatedly until the condition specified by the boolean expression returns false. while loop syntax: while (boolean_expression) statement product <= 1000 true product = 2 * product 1. double product = 1; 2. while (product <= 1000) 3. product = 2 * product; false 14 7

Iteration Statements do-while loop Unlike the while loop, the condition is tested after executing the body Hence, the body of a while loop may never execute (if the condition is initially false) do-while is used when we need the body to execute at least once even if the condition is initially false do-while loop syntax: do statement while (boolean_expression); 1. int a = 4; 2. do{ 3. System.Console.WriteLine(a); 4. a++; 5. } while (a < 3); Output: 4 15 Iteration Statements for loop A compact form for counter-controlled loops for loop syntax: for (initializers; expression; iterators) statement 1. for (int a = 0; a<3; a++) 2. System.Console.WriteLine(a); Output: 0 1 2 16 8

Nested Loops Loops of any type can be completely nested (no overlap is allowed) 1. for(int i = 1; i<=5; i++){ 2. for(int j = i; j<=5; j++) 3. Console.Write( {0}x{1}={2},, i, j, i*j); 4. Console.WriteLine(); 5. } 17 Recursive Methods For a non-negative integer n, the factorial function is defined as 1 n! = n( n 1)! n = 0 n > 0 1. public static long fact (int n) 2. { 3. if (n==0) 4. return 1; 5. else 6. return n*fact(n-1); 7. } 18 9

Other flow control statements goto statement (usage is not recommended) Used to make a jump to a particular labeled part of the program code It is also used in the 'switch' statement to jump to another case We can use a 'goto' statement to construct a loop continue statement Used to return to the top of a loop without executing the remaining statements in the loop break Used to break out of a loop and immediately end all further work within the loop Used to get out of a case in a 'switch' statement return Exit out of a method and return to the calling method throw Throws an exception and exit out of a block foreach Iterating through a collection of items (such as an array) 19 Arrays An array is an indexed collection of objects, all of the same type C# supports one-dimensional arrays, multidimensional arrays (rectangular arrays) and array-of-arrays (jagged arrays) Dealing with arrays Declaring arrays Initializing arrays Accessing array members Arrays are objects Using foreach with arrays Array properties and methods 20 10

Declaring Arrays When declaring an array, the square brackets [ ] must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C# Array types derive from System.Array. s 1. // declare a one-dimensional array 2. int[] grades; // not int grades[]; 3. 4. // declare 2-dimensional array (table) 5. int[,] grades; 6. 7. // declare a jagged array (array-of-arrays) 8. int[][] grades; 21 Creating Array Declaring arrays does not actually create the arrays In C#, arrays are objects and must be instantiated Once an array has been created, its length can't be changed All elements are automatically initialized to default values 1. //declare and create 1D array having 10 elements 2. int[] grades = new int[10]; 3. 4. //declare and create 2D array (table) 5. int[,] grades = new int[3, 4]; 6. 7. //declare and create a jagged array 8. byte[][] scores = new byte[5][]; 9. for (int x = 0; x< scores.length; x++) 10. { 11. scores[x] = new byte[4]; 12. } 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 22 11

Initializing Arrays It is possible to initialize the contents of an array at the time it is instantiated by providing a list of values delimited by curly brackets {}. C# provides a longer and a shorter syntax: 0 1 2 3 4 int[] myintarray = {2,4,6,8,10}; 2 4 6 8 10 Rectangular arrays can be initialized as follows int[,] rectangulararray = {{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} }; Jagged arrays can be initialized as follows int[][] jaggedarray = { new int[] {0,2}, new int[] {3,4,5}, new int [] {6,7,8}}; // new int[] is necessary 23 Accessing Array Members Access the elements of an array using indexed variables The number of elements in an array is given by the property Length Array objects can be indexed from 0 to Length-1 1. // double [] scores 2. for(int i = 0; i<scores.length; i++) 3. Console.WriteLine(scores[i]); 1. // double [, ] scores 2. // scores.length gives the total number of elements 3. // scores.getlength(0) number of rows 4. // scores.getlength(1) number of columns 5. for(int i = 0; i<scores.getlength(0); i++) 6. for(int j = 0; j<scores.getlength(1); j++) 7. Console.WriteLine(scores[i][i]); 24 12

Accessing Array Members foreach loop Used to iterate through all the items in a collection (such as a one-dimensional array) foreach loop syntax foreach (itemtype variable1 in variable2) Statement[s]; int[] a = {1, 3, 5, 7, 9}; foreach (int i in a) Console.WriteLine(i); 25 Accessing Array Members Rectangular arrays Console.WriteLine(scores[2, 1]); Jagged arrays Console.WriteLine(scores[2][1]); 26 13

Method or property Array Properties and Methods System.Array class provides methods for creating, manipulating, searching, and sorting arrays. BinarySearch( ) Clear( ) Copy( ) CreateInstance( ) IndexOf( ) LastIndexOf( ) Reverse( ) Sort( ) Purpose Overloaded public static method; searches a 1D sorted array. Public static method; sets a range of elements in the array either to 0 or to a null reference. Overloaded public static method; copies a section of one array to another array. Overloaded public static method; instantiates a new instance of an array. Overloaded public static method; returns the index (offset) of the first instance of a value in a 1D array. Overloaded public static method; returns the index of the last instance of a value in a 1D array. Overloaded public static method; reverses the order of the elements in a 1D array. Overloaded public static method; sorts the values in a 1D array. 27 Array Properties and Methods Length Rank Equals() GetLength( ) GetLowerBound( ) GetUpperBound( ) GetType( ) GetValue( ) Initialize( ) SetValue( ) Public property; returns the length of the array. Public property; p returns the number of dimensions of the array. Overloaded; returns a boolean value that specifies whether two Object instances are equal Public method; returns the length of the specified dimension in the array. Public method; returns the lower boundary of the specified dimension of the array. Public method; returns the upper boundary of the specified dimension of the array. Returns the type of the current instance Overloaded; returns the element at the specified index in a 1D array Initializes all values in a value type array by calling the default constructor for each value. With reference arrays, all elements in the array are set to null. Overloaded public method; sets the specified array elements to a value. 28 14

1 Practice using flow control, arrays and strings 1. using System; 2. public class ControlStructures { 3. public static void Main() { 4. String input; 5. do { 6. Console.Write("Type int values to add or stop to exit: "); 7. input = Console.ReadLine(); 8. if (input.tolower()!= "stop") { 9. char[] delimiters = {' ', '\t', ','}; 10. String[] tokens = input.split(delimiters); 11. int sum = 0; 12. foreach (String token in tokens) 13. sum += int.parse(token); 14. Console.WriteLine("The sum is: "+sum); 15. } 16. } while (input.tolower()!= "stop"); // compare strings 17. } 18. } 29 Resources MSDN Library http://msdn.microsoft.com/en-us/default.aspx Books C# 3.0 The Complete Reference, 3E, 2005 C# 3.0 in a Nutshell: A Desktop Quick Reference, 2007 Pro C# 2008 and the.net 3.5 Platform, 4E, 2007 C# How to Program, By Deitel Richard Blum, C# Network Programming. Sybex 2002. Lecture notes of previous offerings of SWE344 and ICS343 Some other web sites and books; check the course website at http://faculty.kfupm.edu.sa/ics/alfy/files/teaching/swe344/index.htm 30 15