Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Slides:



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

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
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.
Programming Logic and Design Sixth Edition
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
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.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Lab Session-VI CSIT-120 Spring 2001 Let us look at C++ syntax rules in brief Exercise VI-A (Demo Required) Lab Assignment#4 Due May 1st, 2001 (No Lab.
Unit 171 Algorithms and Problem Solving  Introduction  Algorithm Design  Algorithm Properties  Algorithm Control Flow  Examples  Comparing Algorithms.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
1 11/8/06CS150 Introduction to Computer Science 1 Arrays Chapter 8 page 477 November 13, 2006.
Arrays Chapter 8 page /24/07CS150 Introduction to Computer Science 1 Arrays (8.1)  One variable that can store a group of values of the same.
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.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
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.
Lesson15. JavaScript Objects Objects encapsulate data (properties) and behavior(methods); the properties and the methods of an object are tied together.
Chapter 6: Functions.
School Year Calendar You can print this template to use it as a wall calendar, or you can copy the page for any month to add it to your own presentation.
School Year Calendar You can print this template to use it as a wall calendar, or you can copy the page for any month to add it to your own presentation.
2007 Monthly Calendar You can print this template to use it as a wall calendar, or you can copy the page for any month to add it to your own presentation.
You can print this template to use it as a wall calendar, or you can copy the page for any month to add it to your own presentation. If you’d like to change.
A First Book of ANSI C Fourth Edition
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
Subroutines in Computer Programming 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
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 Session 3: Flow Control & Functions iNET Academy Open Source Web Programming.
Chapter 9: MuPAD Programming II Procedures MATLAB for Scientist and Engineers Using Symbolic Toolbox.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
1 Functions Lecfture Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly.
Fundamental Programming: Fundamental Programming Introduction to C++
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
CPS120: Introduction to Computer Science Lecture 14 Functions.
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
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)
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
If Statements and Boolean Expressions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits:
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
2011 Calendar Important Dates/Events/Homework. SunSatFriThursWedTuesMon January
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
Chapter 8 Functions in Depth. Chapter 8 A programmer-defined function is a block of statements, or a subprogram, that is written to perform a specific.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
July 2007 SundayMondayTuesdayWednesdayThursdayFridaySaturday
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Java Language Basics.
Chapter 6 JavaScript: Introduction to Scripting
JavaScript Syntax and Semantics
Subroutines in Computer Programming
JavaScript: Functions.
WEB PROGRAMMING JavaScript.
Chapter 6: User-Defined Functions I
Methods.
The structure of programming
CHAPTER 4: Lists, Tuples and Dictionaries
2015 January February March April May June July August September
Presentation transcript:

Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

 Functions Overview  Declaring and Creating Functions  Calling Functions  Functions with Parameters  Examples: Functions With Parameters  Print the Sign of Number  Period Between Months  Printing a Triangle of Numbers 2

 Returning Values From Functions  Examples: Returning Values From Functions  Temperature Conversion  Positive Numbers  Data Validation 3

What is a function? 4

 A function 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  Functions allow programmers to construct large programs from simple pieces  Functions are also known as methods, procedures, and subroutines 5

 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 functions several times 6

 Each function has a name  It is used to call the Function  Describes its purpose 8 fucntion printLogo(){ console.log("Telerik Corp."); console.log("Telerik Corp."); console.log(" console.log(" Function name

function printLogo(){ console.log("Telerik Corp."); console.log("Telerik Corp."); console.log(" console.log(" 9  Each function has a body  It contains the programming code  Surrounded by { and } Function body

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

 A function can be called from:  Any other Function  Itself (process known as recursion) 12 function print(){ console.log("printed"); console.log("printed");} function anotherPrint(){ print(); print(); anotherPrint(); anotherPrint();} Don't do this at home

Live Demo

Passing Parameters and Returning Values

 To pass information to a function, 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  Parameters are assigned to particular values when the function is called  Parameters can change the function behavior depending on the passed values 15

 Function’s behavior depends on its parameters  Parameters can be of any type  integer, floating-point, string, etc.  Arrays 16 function printSign(number) { if (number > 0) if (number > 0) console.log("Positive"); console.log("Positive"); else if (number < 0) else if (number < 0) console.log("Negative"); console.log("Negative"); else else console.log("Zero"); console.log("Zero");}

 Functions can have as many parameters as needed: 17 function printMax(number1, number2){ var max = number1; var max = number1; if (number2 > number1) if (number2 > number1) max = number2; max = number2; console.log("Maximal number: " + max); console.log("Maximal number: " + max);}

 To call a function and pass values to its parameters:  Use the function’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);

Examples

20 function printSign(number){ if (number > 0) if (number > 0) console.log("The number " + number + " is positive."); console.log("The number " + number + " is positive."); else if (number < 0) else if (number < 0) console.log("The number " + number + " is negative."); console.log("The number " + number + " is negative."); else else console.log("The number " + number + " is zero."); console.log("The number " + number + " is zero.");} function printMax(number1, number2){ var max = number1; var max = number1; if (number2 > number1){ if (number2 > number1){ max = number2; max = number2; } console.log("Maximal number: " + max); console.log("Maximal number: " + max);}

Live Demo

 Display the period between two months in a user-friendly way 22 function sayMonth(month) { var monthNames = [ "January", "February", "March", var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "April", "May", "June", "July", "August", "September", "October", "August", "September", "October", "November", "December"]; "November", "December"]; return monthNames[month-1]; return monthNames[month-1];} (the example continues)

23 function sayPeriod(startMonth, endMonth){ var period = endMonth - startMonth; var 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! } var resultString = "There are "; var resultString = "There are "; resultString += period + " + months from "; resultString += period + " + months from "; resultString += sayMonth(startMonth); resultString += sayMonth(startMonth); resultString += " to "; resultString += " to "; resultString += sayMonth(endMonth); resultString += sayMonth(endMonth); }

Live Demo

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

26 int n = read("input-tb"); var line; for (line = 1; line <= n; line++) printLine(1, line); printLine(1, line); for (line = n-1; line >= 1; line--) printLine(1, line); printLine(1, line); function printLine(start, end){ var line=""; var line=""; for (var i = start; i <= end; i++){ for (var i = start; i <= end; i++){ line += " " + i; line += " " + i; } console.log(line); console.log(line);}

Live Demo

 In JavaScript functions can return a value  The returned values can be of any type  Even of type void (no type)  Returned value  Can be assigned to a variable:  Can be used in expressions:  Can be passed to another Function: var head = arr.shift(); var price = getPrice() * quantity * 1.20; var age = parseInt("5");

 Functions can return any type of data ( int, string, array, etc.)  The combination of function's name and parameters is called function signature  Use return keyword to return a result 30 function multiply(int firstNum, int secondNum){ return firstNum * secondNum; return firstNum * secondNum;}

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

Examples

 Convert temperature from Fahrenheit to Celsius: 33 function fahrenheitToCelsius(degrees){ var celsius = (degrees - 32) * 5 / 9; var celsius = (degrees - 32) * 5 / 9; return celsius; return celsius;} var tStr = read("input-tb"); var t = parseInt(tStr); t = fahrenheitToCelsius(t); console.log("Temperature in Celsius: " + t);

Live Demo

 Check if all numbers in a sequence are positive: 35 function arePositive(sequence){ for (var i in sequence) { for (var i in sequence) { var number = sequence[i]; var number = sequence[i]; if (number <= 0) { if (number <= 0) { return false; return false; } } return true; return true;}

Live Demo

 Validating input data: 37 function validate(username, password, ) { return validateUsername(username) && return validateUsername(username) && validatePass(password) && validate ( ); validatePass(password) && validate ( );} function validateUsername(username) { return username != "" && username.length > 3 && username.length 3 && username.length < 20;} function validatePass(pass) { return pass != "" && pass.length > 6 && pass.length 6 && pass.length < 20;} function validate ( ) { var containsAt = var containsAt = return containsAt > 3 && .length - containsAt > 3; return containsAt > 3 && .length - containsAt > 3;}

Live Demo

 Each function should perform a single, well-defined task  Function’s name should describe that task in a clear and non-ambiguous way  Good examples: calculatePrice, readName  Bad examples: f, g1, Process  In JS functions should start with lower letter  Avoid functions longer than one screen  Split them to several shorter functions 39

Questions?Questions?

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

4. Write a function that counts how many times given number appears in given array. Write a test script to check if the function is working correctly. 5. Write a function 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 Function 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 function from the previous exercise. 42

7. Write a function that reverses the digits of given decimal number. Example: 256  Write a function 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. 43