BİL527 – Bilgisayar Programlama I Functions 1. Contents Functions Delegates 2.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Programming Dr. Abraham Most slides are from your textbook.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
GTECH 731 Lab Session 2 Lab 1 Review, Lab 2 Intro 9/6/10 Lab 1 Review Lab 2 Overview.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
C# Tutorial From C++ to C#. Some useful links Msdn C# us/library/kx37x362.aspxhttp://msdn.microsoft.com/en- us/library/kx37x362.aspx.
Teach.NET Workshop Series Track 4: AP Computer Science with.NET and J#
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Web Services Week 2 Aims: Getting started with creating simple C# applications within Visual Studio.NET Objectives: –An introduction to the syntax of C#.NET.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
Introduction to C# C# is - elegant, type-safe, object oriented language enabling to build applications that run on the.NET framework - types of applications.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CMPS 211 JavaScript Topic 2 Functions and Arrays.
BIM313 – Advanced Programming Techniques Strings and Functions 1.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
ILM Proprietary and Confidential -
Java Classes. Consider this simplistic class public class ProjInfo {ProjInfo() {System.out.println("This program computes factorial of number"); System.out.println("passed.
Procedural programming in Java Methods, parameters and return values.
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Java Arrays and Methods MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
Variable Argument Lists CS 112 (slides from Marc Lihan)
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
CSI 3125, Preliminaries, page 1 Compiling the Program.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
Method Parameters and Overloading Version 1.0. Topics The run-time stack Pass-by-value Pass-by-reference Method overloading Stub and driver methods.
Outline Class and Object-Oriented Programing –Encapsulation and inheritance Example –Commission Employee –Encapsulation and inheritance Strings and Formatting.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
BIL528 – Bilgisayar Programlama II Methods 1. Contents Methods 2.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Final Review Author: Thanachat Thanomkulabut Edited by Supaporn Erjongmanee Final Review 22 September 2011.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
C# Programming Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Classes - Intermediate
Methods.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
The need for Programming Languages
Chapter 7: User-Defined Functions II
C# — Console Application
BİL527 – Bilgisayar Programlama I
Programmazione I a.a. 2017/2018.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Starting Out with Java: From Control Structures through Objects
Lecture 3 Functions Simple functions
An Introduction to Java – Part I, language basics
Group Status Project Status.
Chapter 6 Methods.
Week 4 Lecture-2 Chapter 6 (Methods).
Methods and Data Passing
Corresponds with Chapter 5
Presentation transcript:

BİL527 – Bilgisayar Programlama I Functions 1

Contents Functions Delegates 2

Functions Some tasks may need to be performed at several points in a program – e.g. finding the highest number in an array Solution: Write the code in a function and call it several times In object-oriented programming languages, functions of objects are named as methods 3

Function Example class Program { static void DrawBorder() { Console.WriteLine(“ ”); } static void Main(string[] args) { DrawBorder(); Console.WriteLine(“| Hello! |”); DrawBorder(); } | Hello! | Don’t forget to use the word ‘static’!

Functions that return a value static int ReadAge() { Console.Write(“Enter your age: ”); int age = int.Parse(Console.ReadLine()); if (age < 1) return 1; else if (age > 120) return 120; else return age; } 5

Functions that take parameters static double Product(double a, double b) { return a * b; } 6

Functions that take array as parameter class Program { static int MaxValue(int[] intArray) { int maxVal = intArray[0]; for (int i = 1; i < intArray.Length; i++) { if (intArray[i] > maxVal) maxVal = intArray[i]; } return maxVal; } static void Main(string[] args) { int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 }; int maxVal = MaxValue(myArray); Console.WriteLine("The maximum value in myArray is {0}", maxVal); } 7

Parameter Arrays If your function may take variable amount of parameters, then you can use the parameter arrays – Think of Console.WriteLine(format, params) – You can use any amount of parameters after the format string Parameter arrays can be declared with the keyword params Parameter array should be the last parameter in the parameter list of the function 8

params Example class Program { static int SumVals(params int[] vals) { int sum = 0; foreach (int val in vals) { sum += val; } return sum; } static void Main(string[] args) { int sum = SumVals(1, 5, 2, 9, 8); Console.WriteLine("Summed Values = {0}", sum); } 9

Call By Value and Call By Reference If you change a value-type parameter in the function, it doesn’t affect the value in the main function – because, only the value is transferred However, if you change a reference-type parameter’s elements, then the argument in the main function is also changed – because the object itself is transferred You can think arrays as reference-types 10

Call By Value static void ShowDouble(int val) { val *= 2; Console.WriteLine(“val doubled = {0}”, val); } static void Main(string[] args) { int myNumber = 5; ShowDouble(myNumber); Console.WriteLine(“myNumber in main: ” + myNumber); } 11 val doubled = 10 myNumber in main: 5

Call By Reference static void ChangeFirst(int[] arr) { arr[0] = 99; } static void Main(string[] args) { int[] myArr = {1, 2, 3, 4, 5}; DisplayArray(myArr); ChangeFirst(myArr); DisplayArray(myArr); }

ref and out You can change the value of argument in the Main function via a function using the ref keyword You can declare a parameter as the output of a function with the out keyword – out parameters does not have to be initialized before the function call (their values are set by the function) 13

ref Example static void ShowDouble(ref int val) { val *= 2; Console.WriteLine(“val doubled = {0}”, val); } static void Main(string[] args) { int myNumber = 5; ShowDouble(ref myNumber); Console.WriteLine(“myNumber in main: ” + myNumber); } 14 val doubled = 10 myNumber in main: 10

out Example static void FindAvgAndSum(int[] arr, out double avg, out int sum) { sum = 0; foreach (int num in arr) { sum += num; } avg = (double) sum / arr.Lenght; } static void Main(string[] args) { int sum; double avg; int[] myArray = {3, 4, 8, 2, 7}; FindAvgAndSum(myArray, out avg, out sum); } 15

Another Example for out static int MaxValue(int[] intArray, out int maxIndex) { int maxVal = intArray[0]; maxIndex = 0; for (int i = 1; i < intArray.Length; i++) { if (intArray[i] > maxVal) { maxVal = intArray[i]; maxIndex = i; } return maxVal; } 16

Variable Scope Variables in a functions are not accessible by other functions – they are called local variables The variables declared in the class definition are accessible by all functions in the class – they are called global variables – they should be static so that static functions can access them Variables declared in a block (for, while, {}, etc.) are only accessible in that block 17

The Main Function The Main function is the entry point in a C# program It takes a string array parameter, whose elements are called command-line parameters The following declarations of Main are all valid: – static void Main() – static void Main(string[] args) – static int Main() – static int Main(string[] args) 18

Command-Line Parameters class Program { static void Main(string[] args) { Console.WriteLine("{0} command line arguments were specified:", args.Length); foreach (string arg in args) { Console.WriteLine(arg); } 19

Specifying Command-Line Arguments in Visual Studio Right-click on the project name in the Solution Explorer window and select Properties Select the Debug pane Write command-line arguments into the box Run the application 20

Specifying Command-Line Arguments in Command Prompt Open a command prompt Go to the folder of the executable output of the program Write the name of the executable followed by the command-line arguments – prog.exe 256 myfile.txt “a longer argument” 21

struct Functions struct CustomerName { public string firstName, lastName; public string Name() { return firstName + " " + lastName; } 22

Calling struct Function CustomerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; Console.WriteLine(myCustomer.Name()); 23

Overloading Functions A function may have several signatures – i.e. same function name but different parameters – e.g. Console.WriteLine() Intellisense feature of the Visual Studio helps us to select the correct function 24

Example 1 static int MaxValue(int[] intArray) { … } static double MaxValue(double[] doubleArray) { … } static void Main(string[] args) { int[] arr1 = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 }; double[] arr2 = { 0.1, 0.8, 0.3, 1.6, 0.2}; int maxVal1 = MaxValue(arr1); double maxVal2 = MaxValue(arr2); } 25

Example 2 static void func(ref int val) { … } static void func(int val) { … } func(ref val); func(val); 26 Signatures are different, so usage is valid! The ref keyword differentiates the functions!

Delegates References to functions – “Function Pointers” in C and C++ Declaration: Specify a return type and parameter list Assignment: Convert function reference to a delegate Calling: Just use the delegate’s name 27

Delegate Example delegate double MyDelegate(double num1, double num2); static double Multiply(double param1, double param2) { return param1 * param2; } static double Divide(double param1, double param2) { return param1 / param2; } 28 Declaration

Delegate Example (continued) static void Main(string[] args) { MyDelegate process; double param1 = 5; double param2 = 3, process = new MyDelegate(Multiply); Console.WriteLine("Result: {0}", process(param1, param2)); process = new MyDelegate(Divide); Console.WriteLine("Result: {0}", process(param1, param2)); } 29

Easier Way static void Main(string[] args) { MyDelegate process; double param1 = 5; double param2 = 3, process = Multiply; Console.WriteLine("Result: {0}", process(param1, param2)); process = Divide; Console.WriteLine("Result: {0}", process(param1, param2)); } 30