Subroutines in Computer Programming Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Spring Semester 2013 Lecture 5
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
Solving Problems with Repetition. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Introduction to C Programming
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Computer Science 1620 Loops.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
1 11/8/06CS150 Introduction to Computer Science 1 Arrays Chapter 8 page 477 November 13, 2006.
1.9 Methods academy.zariba.com 1. Lecture Content 1.What is a method? Why use methods? 2.Void Methods and methods with parameters 3.Methods which return.
Introduction to C Programming
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Chapter 6: Functions.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Reading and Writing to the Console Svetlin Nakov Telerik Corporation
Data Types, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods Svetlin Nakov Telerik Corporation
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
Advanced Programming LOOP.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 9: MuPAD Programming II Procedures MATLAB for Scientist and Engineers Using Symbolic Toolbox.
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Processing Sequences of Elements Svetlin Nakov Telerik Corporation
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Fundamental Programming: Fundamental Programming Introduction to C++
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Processing Sequences of Elements Technical Trainer Telerik Corporation Doncho Minkov.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
C# Programming Methods.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Programming Fundamentals Enumerations and Functions.
Solving Problems with Repetition Version 1.0. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C#
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
CIS199 Test Review 2 REACH.
User-Written Functions
Java Language Basics.
Repeating Code Multiple Times
COMP 170 – Introduction to Object Oriented Programming
Computing with C# and the .NET Framework
Subroutines in Computer Programming
Chapter 4 – Control Structures Part 1
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 JavaProgramming
Presentation transcript:

Subroutines in Computer Programming Svetlin Nakov Telerik Corporation

1. Using Methods  What is a Method? Why to Use Methods?  Declaring and Creating Methods  Calling Methods 2. Methods with Parameters  Passing Parameters  Returning Values 3. Best Practices 2

 A method is a kind of building block that solves a small problem  A piece of code that has a name and can be called from the other code  Can take parameters and return a value  Methods allow programmers to construct large programs from simple pieces  Methods are also known as functions, procedures, and subroutines 3

 More manageable programming  Split large problems into small pieces  Better organization of the program  Improve code readability  Improve code understandability  Avoiding repeating code  Improve code maintainability  Code reusability  Using existing methods several times 4

 Each method has a name  It is used to call the method  Describes its purpose 6 static void PrintLogo() { Console.WriteLine("Telerik Corp."); Console.WriteLine("Telerik Corp."); Console.WriteLine(" Console.WriteLine(" Method name

 Methods declared static can be called by any other method (static or not)  This will be discussed later in details  The keyword void means that the method does not return any result 7 static void PrintLogo() { Console.WriteLine("Telerik Corp."); Console.WriteLine("Telerik Corp."); Console.WriteLine(" Console.WriteLine("

static void PrintLogo() { Console.WriteLine("Telerik Corp."); Console.WriteLine("Telerik Corp."); Console.WriteLine(" Console.WriteLine(" 8  Each method has a body  It contains the programming code  Surrounded by { and } Method body

using System; class MethodExample { static void PrintLogo() static void PrintLogo() { Console.WriteLine("Telerik Corp."); Console.WriteLine("Telerik Corp."); Console.WriteLine(" Console.WriteLine(" } static void Main() static void Main() { //... //... }} 9  Methods are always declared inside a class  Main() is also a method like all others

 To call a method, simply use: 1.The method’s name 2.Parentheses (don’t forget them!) 3.A semicolon ( ; )  This will execute the code in the method’s body and will result in printing the following: 11 PrintLogo(); Telerik Corp.

 A method can be called from:  The Main() method  Any other method  Itself (process known as recursion) 12 static void Main() { //... //... PrintLogo(); PrintLogo(); //... //...}

Live Demo

Passing Parameters and Returning Values

 To pass information to a method, you can use parameters (also known as arguments)  You can pass zero or several input values  You can pass values of different types  Each parameter has name and type  Parameters are assigned to particular values when the method is called  Parameters can change the method behavior depending on the passed values 15

 Method’s behavior depends on its parameters  Parameters can be of any type  int, double, string, etc.  arrays ( int[], double[], etc.) 16 static void PrintSign(int number) { if (number > 0) if (number > 0) Console.WriteLine("Positive"); Console.WriteLine("Positive"); else if (number < 0) else if (number < 0) Console.WriteLine("Negative"); Console.WriteLine("Negative"); else else Console.WriteLine("Zero"); Console.WriteLine("Zero");}

 Methods can have as many parameters as needed:  The following syntax is not valid: 17 static void PrintMax(float number1, float number2) { float max = number1; float max = number1; if (number2 > number1) if (number2 > number1) max = number2; max = number2; Console.WriteLine("Maximal number: {0}", max); Console.WriteLine("Maximal number: {0}", max);} static void PrintMax(float number1, number2)

 To call a method and pass values to its parameters:  Use the method’s name, followed by a list of expressions for each parameter  Examples: 18 PrintSign(-5);PrintSign(balance);PrintSign(2+3); PrintMax(100, 200); PrintMax(oldQuantity * 1.5, quantity * 2);

 Expressions must be of the same type as method’s parameters (or compatible)  If the method requires a float expression, you can pass int instead  Use the same order like in method declaration  For methods with no parameters do not forget the parentheses 19

Examples

21 static void PrintSign(int number) { if (number > 0) if (number > 0) Console.WriteLine("The number {0} is positive.", number); Console.WriteLine("The number {0} is positive.", number); else if (number < 0) else if (number < 0) Console.WriteLine("The number {0} is negative.", number); Console.WriteLine("The number {0} is negative.", number); else else Console.WriteLine("The number {0} is zero.", number); Console.WriteLine("The number {0} is zero.", number);} static void PrintMax(float number1, float number2) { float max = number1; float max = number1; if (number2 > number1) if (number2 > number1) { max = number2; max = number2; } Console.WriteLine("Maximal number: {0}", max); Console.WriteLine("Maximal number: {0}", max);}

Live Demo

 Display the period between two months in a user-friendly way 23 using System; class MonthsExample { static void SayMonth(int month) static void SayMonth(int month) { string[] monthNames = new string[] { string[] monthNames = new string[] { "January", "February", "March", "January", "February", "March", "April", "May", "June", "July", "April", "May", "June", "July", "August", "September", "October", "August", "September", "October", "November", "December"}; "November", "December"}; Console.Write(monthNames[month-1]); Console.Write(monthNames[month-1]); } (the example continues)

24 static void SayPeriod(int startMonth, int endMonth) static void SayPeriod(int startMonth, int endMonth) { int period = endMonth - startMonth; int period = endMonth - startMonth; if (period < 0) if (period < 0) { period = period + 12; period = period + 12; // From December to January the // From December to January the // period is 1 month, not -11! // period is 1 month, not -11! } Console.Write("There are {0} + months from ", period); Console.Write("There are {0} + months from ", period); SayMonth(startMonth); SayMonth(startMonth); Console.Write(" to "); Console.Write(" to "); SayMonth(endMonth); SayMonth(endMonth); }}

Live Demo

 Creating a program for printing triangles as shown below: n=5  n=6 

27 static void Main() { int n = int.Parse(Console.ReadLine()); int n = int.Parse(Console.ReadLine()); for (int line = 1; line <= n; line++) for (int line = 1; line <= n; line++) PrintLine(1, line); PrintLine(1, line); for (int line = n-1; line >= 1; line--) for (int line = n-1; line >= 1; line--) PrintLine(1, line); PrintLine(1, line);} static void PrintLine(int start, int end) { for (int i = start; i <= end; i++) for (int i = start; i <= end; i++) { Console.Write(" {0}", i); Console.Write(" {0}", i); } Console.WriteLine(); Console.WriteLine();}

Live Demo

 C# 4.0 supports optional parameters with default values assigned at their declaration:  The above method can be called in several ways: 29 static void PrintNumbers(int start = 0; int end = 100) { for (int i = start; i <= end; i++) for (int i = start; i <= end; i++) { Console.Write("{0} ", i); Console.Write("{0} ", i); }} PrintNumbers(5, 10); PrintNumbers(15);PrintNumbers(); PrintNumbers(end: 40, start: 35);

Live Demo

 A method can return a value to its caller  Returned value:  Can be assigned to a variable:  Can be used in expressions:  Can be passed to another method: 32 string message = Console.ReadLine(); // Console.ReadLine() returns a string float price = GetPrice() * quantity * 1.20; int age = int.Parse(Console.ReadLine());

 Instead of void, specify the type of data to return  Methods can return any type of data ( int, string, array, etc.)  void methods do not return anything  The combination of method's name, parameters and return value is called method signature  Use return keyword to return a result 33 static int Multiply(int firstNum, int secondNum) { return firstNum * secondNum; return firstNum * secondNum;}

 The return statement:  Immediately terminates method’s execution  Returns specified expression to the caller  Example:  To terminate void method, use just:  Return can be used several times in a method body 34 return -1; return;

Examples

Examples

 Convert temperature from Fahrenheit to Celsius: 37 static double FahrenheitToCelsius(double degrees) { double celsius = (degrees - 32) * 5 / 9; double celsius = (degrees - 32) * 5 / 9; return celsius; return celsius;} static void Main() { Console.Write("Temperature in Fahrenheit: "); Console.Write("Temperature in Fahrenheit: "); double t = Double.Parse(Console.ReadLine()); double t = Double.Parse(Console.ReadLine()); t = FahrenheitToCelsius(t); t = FahrenheitToCelsius(t); Console.Write("Temperature in Celsius: {0}", t); Console.Write("Temperature in Celsius: {0}", t);}

Live Demo

 Check if all numbers in a sequence are positive: 39 static bool ArePositive(int[] sequence) { foreach (int number in sequence) foreach (int number in sequence) { if (number <= 0) if (number <= 0) { return false; return false; } } return true; return true;}

Live Demo

 Validating input data: 41 using System; class ValidatingDemo { static void Main() static void Main() { Console.WriteLine("What time is it?"); Console.WriteLine("What time is it?"); Console.Write("Hours: "); Console.Write("Hours: "); int hours = int.Parse(Console.ReadLine()); int hours = int.Parse(Console.ReadLine()); Console.Write("Minutes: "); Console.Write("Minutes: "); int minutes = int.Parse(Console.ReadLine()); int minutes = int.Parse(Console.ReadLine()); // (The example continues on the next slide)

42 bool isValidTime = bool isValidTime = ValidateHours(hours) && ValidateHours(hours) && ValidateMinutes(minutes); ValidateMinutes(minutes); if (isValidTime) if (isValidTime) Console.WriteLine("It is {0}:{1}", Console.WriteLine("It is {0}:{1}", hours, minutes); hours, minutes); else else Console.WriteLine("Incorrect time!"); Console.WriteLine("Incorrect time!"); } static bool ValidateMinutes(int minutes) static bool ValidateMinutes(int minutes) { bool result = (minutes>=0) && (minutes =0) && (minutes<=59); return result; return result; } static bool ValidateHours(int hours) {... } static bool ValidateHours(int hours) {... }}

Live Demo

Multiple Methods with the Same Name

 What means "to overload a method name"?  Use the same method name for multiple methods with different parameters 45 static void Print(string text) { Console.WriteLine(text); Console.WriteLine(text);} static void Print(int number) { Console.WriteLine(number); Console.WriteLine(number);} static void Print(string text, int number) { Console.WriteLine(text + ' ' + number); Console.WriteLine(text + ' ' + number);}

 A method in C# can take variable number of parameters by specifying the params keyword 47 static long CalcSum(params int[] elements) { long sum = 0; long sum = 0; foreach (int element in elements) foreach (int element in elements) sum += element; sum += element; return sum; return sum;} static void Main() { Console.WriteLine(CalcSum(2, 5)); Console.WriteLine(CalcSum(2, 5)); Console.WriteLine(CalcSum(4, 0, -2, 12)); Console.WriteLine(CalcSum(4, 0, -2, 12)); Console.WriteLine(CalcSum()); Console.WriteLine(CalcSum());}

 Each method should perform a single, well-defined task  Method’s name should describe that task in a clear and non-ambiguous way  Good examples: CalculatePrice, ReadName  Bad examples: f, g1, Process  In C# methods should start with capital letter  Avoid methods longer than one screen  Split them to several shorter methods 48

 Break large programs into simple methods that solve small sub-problems  Methods consist of declaration and body  Methods are invoked by their name  Methods can accept parameters  Parameters take actual values when calling a method  Methods can return a value or nothing 49

Questions?Questions?

1. Write a method that asks the user for his name and prints “Hello, ” (for example, “Hello, Peter!”). Write a program to test this method. 2. Write a method GetMax() with two parameters that returns the bigger of two integers. Write a program that reads 3 integers from the console and prints the biggest of them using the method GetMax(). 3. Write a method that returns the last digit of given integer as an English word. Examples: 512  "two", 1024  "four",  "nine". 51

4. Write a method that counts how many times given number appears in given array. Write a test program to check if the method is working correctly. 5. Write a method that checks if the element at given position in given array of integers is bigger than its two neighbors (when such exist). 6. Write a method that returns the index of the first element in array that is bigger than its neighbors, or -1, if there’s no such element.  Use the method from the previous exercise. 52

7. Write a method that reverses the digits of given decimal number. Example: 256  Write a method that adds two positive integer numbers represented as arrays of digits (each array element arr[i] contains a digit; the last digit is kept in arr[0] ). Each of the numbers that will be added could have up to digits. 9. Write a method that return the maximal element in a portion of array of integers starting at given index. Using it write another method that sorts an array in ascending / descending order. 53

10. Write a program to calculate n! for each n in the range [1..100]. Hint: Implement first a method that multiplies a number represented as array of digits by given integer number. 11. Write a method that adds two polynomials. Represent them as arrays of their coefficients as in the example below: x = 1x 2 + 0x + 5  12. Extend the program to support also subtraction and multiplication of polynomials

13. Write a program that can solve these tasks:  Reverses the digits of a number  Calculates the average of a sequence of integers  Solves a linear equation a * x + b = 0 Create appropriate methods. Provide a simple text-based menu for the user to choose which task to solve. Validate the input data:  The decimal number should be non-negative  The sequence should not be empty  a should not be equal to 0 55

14. Write methods to calculate minimum, maximum, average, sum and product of given set of integer numbers. Use variable number of arguments. 15. * Modify your last program and try to make it work for any number type, not just integer (e.g. decimal, float, byte, etc.). Use generic method (read in Internet about generic methods in C#). 56