Data Types, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
JavaScript, Third Edition
Integer, Floating-Point, Text Data, Variables, Literals Svetlin Nakov Telerik Corporation
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
A First Book of ANSI C Fourth Edition
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Reading and Writing to the Console Svetlin Nakov Telerik Corporation
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
Primitive Data Types and Variables Integer, Floating-Point, Text Data, Variables, Literals Angel Georgiev Part-time Trainer angeru.softuni-friends.org.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
C# Language Overview (Part I)
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Data Types, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods Svetlin Nakov Telerik Corporation
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Chapter 2: Using Data.
CPS120: Introduction to Computer Science
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.
Primitive Data Types and Variables Integer, Floating-Point, Text Data, Variables, Literals SoftUni Team Technical Trainers Software University
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
Reading and Writing to the Console Svetlin Nakov Telerik Corporation
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Perform Calculations and Control Flow Telerik Software Academy Learning & Development Team.
Telerik Software Academy Telerik School Academy Integer, Floating-Point, Text Data, Variables,
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
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.
Chapter 2 Variables.
Performing Simple Calculations with C# Telerik Corporation
Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Integer, Floating-Point, Text Data, Variables, Literals Telerik Corporation
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
Operators and Expressions
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Data Types and Methods Data Types, Type Conversions, Switch-Case, Methods, Debugging SoftUni Team Technical Trainers Software University
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Data Types and Variables Data Types, Variables, Type Conversions SoftUni Team Technical Trainers Software University
Repeating Code Multiple Times
COMP 170 – Introduction to Object Oriented Programming
Numeral Types and Type Conversion
Lecture 2 Data Types Richard Gesick.
Data Types, Type Conversions, Switch-Case, Methods
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3: Understanding C# Language Fundamentals
elementary programming
Problem 1 Given n, calculate 2n
Presentation transcript:

Data Types, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods Svetlin Nakov Telerik Corporation

1. Data Types 2. Operators 3. Expressions 4. Console I/O 5. Conditional Statements 6. Loops 7. Methods 2

 Integer types are:  sbyte (-128 to 127): signed 8-bit  byte (0 to 255): unsigned 8-bit  short (-32,768 to 32,767): signed 16-bit  ushort (0 to 65,535): unsigned 16-bit  int (-2,147,483,648 to 2,147,483,647): signed 32-bit  uint (0 to 4,294,967,295): unsigned 32-bit

 More integer types:  long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807): signed 64-bit  ulong (0 to 18,446,744,073,709,551,615): unsigned 64-bit

 Measuring time  Depending on the unit of measure we may use different data types: byte centuries = 20; // Usually a small number ushort years = 2000; uint days = ; ulong hours = ; // May be a very big number Console.WriteLine("{0} centuries is {1} years, or {2} days, or {3} hours.", centuries, years, days, hours);

 Floating-point types are:  float (±1.5 × 10 −45 to ±3.4 × ): 32-bits, precision of 7 digits  double (±5.0 × 10 −324 to ±1.7 × ): 64-bits, precision of digits  The default value of floating-point types:  Is 0.0F for the float type  Is 0.0D for the double type

 There is a special fixed-point real number type:  decimal (±1,0 × to ±7,9 × ): 128-bits, precision of digits  Used for financial calculations with low loss of precision  No round-off errors  The default value of decimal type is:  0.0M ( M is the suffix for decimal numbers)

 See below the difference in precision when using float and double :  NOTE: The “ f ” suffix in the first statement!  Real numbers are by default interpreted as double !  One should explicitly convert them to float float floatPI = f; double doublePI = ; Console.WriteLine("Float PI is: {0}", floatPI); Console.WriteLine("Double PI is: {0}", doublePI);

 Sometimes abnormalities can be observed when using floating-point numbers  Comparing floating-point numbers can not be done directly with the == operator  Example: float a = 1.0f; float b = 0.33f; float sum = 1.33f; bool equal = (a+b == sum); // False!!! Console.WriteLine("a+b={0} sum={1} equal={2}", a+b, sum, equal); a+b, sum, equal);

 The Boolean Data Type:  Is declared by the bool keyword  Has two possible values: true and false  Is useful in logical expressions  The default value is false

 Here we can see how boolean variables take values of true or false : int a = 1; int b = 2; bool greaterAB = (a > b); Console.WriteLine(greaterAB); // False bool equalA1 = (a == 1); Console.WriteLine(equalA1); // True

 The Character Data Type:  Represents symbolic information  Is declared by the char keyword  Gives each symbol a corresponding integer code  Has a '\0' default value  Takes 16 bits of memory (from U+0000 to U+FFFF )

 The example below shows that every symbol has an its unique code: char symbol = 'a'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol, (int) symbol); symbol = 'b'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol, (int) symbol); symbol = 'A'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol, (int) symbol);

 The String Data Type:  Represents a sequence of characters  Is declared by the string keyword  Has a default value null (no value)  Strings are enclosed in quotes:  Strings can be concatenated string s = "Microsoft.NET Framework";

 Concatenating the two names of a person to obtain his full name:  NOTE: a space is missing between the two names! We have to add it manually string firstName = "Ivan"; string lastName = "Ivanov"; Console.WriteLine("Hello, {0}!", firstName); string fullName = firstName + " " + lastName; Console.WriteLine("Your full name is {0}.", fullName);

 The object type:  Is declared by the object keyword  Is the “parent” of all other types  Can take any types of values according to the needs

 Example of an object variable taking different types of data: object dataContainer = 5; Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer); dataContainer = "Five"; Console.Write ("The value of dataContainer is: "); Console.WriteLine(dataContainer);

 When declaring a variable we:  Specify its type  Specify its name (called identifier)  May give it an initial value  The syntax is the following:  Example: [= ]; [= ]; int height = 200;

 Identifiers may consist of:  Letters (Unicode)  Digits [0-9]  Underscore "_"  Identifiers  Can begin only with a letter or an underscore  Cannot be a C# keyword

 Identifiers  Should have a descriptive name  It is recommended to use only Latin letters  Should be neither too long nor too short  Note:  In C# small letters are considered different than the capital letters (case sensitivity)

 Examples of correct identifiers:  Examples of incorrect identifiers: int new;// new is a keyword int 2Pac;// Cannot begin with a digit int New = 2; // Here N is capital int _2Pac; // This identifiers begins with _ string поздрав = "Hello"; // Unicode symbols used // The following is more appropriate: string greeting = "Hello"; int n = 100; // Undescriptive int numberOfClients = 100; // Descriptive // Overdescriptive identifier: int numberOfPrivateClientOfTheFirm = 100;

 Examples of integer literals  The ' 0x ' and ' 0X ' prefixes mean a hexadecimal value, e.g. 0xA8F1  The ' u ' and ' U ' suffixes mean a ulong or uint type, e.g U  The ' l ' and ' L ' suffixes mean a long or ulong type, e.g L

 Note: the letter ‘ l ’ is easily confused with the digit ‘ 1 ’ so it’s better to use ‘ L ’!!! // The following variables are // initialized with the same value: int numberInHex = -0x10; int numberInDec = -16; // The following causes an error, because 234u is of type uint int unsignedInt = 234u; // The following causes an error, because 234L is of type long int longInt = 234L;

 The real literals:  Are used for values of type float and double  May consist of digits, a sign and “. ”  May be in exponential formatting  The “ f ” and “ F ” suffixes mean float  The “ d ” and “ D ” suffixes mean double  The default interpretation is double

 Example of incorrect float literal:  A correct way to assign floating-point value (using also the exponential format): 28 // The following causes an error // because 12.5 is double by default float realNumber = 12.5; // The following is the correct // way of assigning the value: float realNumber = 12.5f; // This is the same value in exponential format: realNumber = 1.25e+1f;

 The character literals:  Are used for values of the char type  Consist of two single quotes surrounding the value: ' '  The value may be:  Symbol  The code of the symbol  Escaping sequence

 Escaping sequences are:  Means of presenting a symbol that is usually interpreted otherwise (like ' )  Means of presenting system symbols (like the new line symbol)  Common escaping sequences are:  \' for single quote  \" for double quote  \\ for backslash  \n for new line

 Examples of different character literals: char symbol = 'a'; // An ordinary symbol symbol = '\u0061'; // Unicode symbol code in // a hexadecimal format symbol = '\''; // Assigning the single quote symbol symbol = '\\'; // Assigning the backslash symbol symbol = "a"; // Incorrect: use single quotes

 String literals:  Are used for values of the string type  Consist of two double quotes surrounding the value: " "  May have prefix which ignores the used escaping sequences  The value is a sequence of character literals

 Benefits of quoted strings prefix):  In quoted strings \" is used instead of "" ! // Here is a string literal using escape sequences string quotation = "\"Hello, Jude\", he said."; string path = "C:\\WINNT\\Darts\\Darts.exe"; // Here is an example of the usage quotation Jimmy!"", she answered."; path

35CategoryOperatorsArithmetic + - * / % Logical && || ^ ! Binary & | ^ ~ > Comparison == != = Assignment = += -= *= /= %= &= |= ^= >= String concatenation + Type conversion is as typeof Other. [] () ?: new

36PrecedenceOperatorsHighest (postfix) new typeof (prefix) + - (unary) ! ~ * / % + - > > = is as = is as == != & Lower^

37PrecedenceOperatorsHigher| && || ?: Lowest = *= /= %= += -= >= &= ^= |=  Parenthesis operator always has highest precedence  Note: prefer using parentheses, even when it seems stupid to do so

 Arithmetic operators +, -, * are the same as in math  Division operator / if used on integers returns integer (without rounding)  Remainder operator % returns the remainder from division of integers  The special addition operator ++ increments a variable

int squarePerimeter = 17; double squareSide = squarePerimeter/4.0; double squareArea = squareSide*squareSide; Console.WriteLine(squareSide); // 4.25 Console.WriteLine(squareArea); // int a = 5; int b = 4; Console.WriteLine( a + b ); // 9 Console.WriteLine( a + b++ ); // 9 Console.WriteLine( a + b ); // 10 Console.WriteLine( a + (++b) ); // 11 Console.WriteLine( a + b ); // 11 Console.WriteLine(11 / 3); // 3 Console.WriteLine(11 % 3); // 2 Console.WriteLine(12 / 3); // 4

 Logical operators take boolean operands and return boolean result  Operator ! turns true to false and false to true  Behavior of the operators &&, || and ^ ( 1 == true, 0 == false ) : Operation||||||||&&&&&&&&^^^^Operand Operand Result

 Using the logical operators: bool a = true; bool b = false; Console.WriteLine(a && b); // False Console.WriteLine(a || b); // True Console.WriteLine(a ^ b); // True Console.WriteLine(!b); // True Console.WriteLine(b || true); // True Console.WriteLine(b && true); // False Console.WriteLine(a || true); // True Console.WriteLine(a && true); // True Console.WriteLine(!a); // False Console.WriteLine((5>7) ^ (a==b)); // False

 Bitwise operator ~ turns all 0 to 1 and all 1 to 0  Like ! for boolean expressions but bit by bit  The operators |, & and ^ behave like ||, && and ^ for boolean expressions but bit by bit  The > move the bits (left or right)  Behavior of the operators |, & and ^ : Operation||||&&&&^^^^Operand Operand Result

 Bitwise operators are used on integer numbers ( byte, sbyte, int, uint, long, ulong )  Bitwise operators are applied bit by bit  Examples: ushort a = 3; // ushort b = 5; // Console.WriteLine( a | b); // Console.WriteLine( a & b); // Console.WriteLine( a ^ b); // Console.WriteLine(~a & b); // Console.WriteLine( a<<1 ); // Console.WriteLine( a>>1 ); //

 Comparison operators are used to compare variables  ==,, >=,, >=, <=, !=  Comparison operators example: int a = 5; int b = 4; Console.WriteLine(a >= b); // True Console.WriteLine(a != b); // True Console.WriteLine(a > b); // False Console.WriteLine(a == b); // False Console.WriteLine(a == a); // True Console.WriteLine(a != ++b); // False

 Assignment operators are used to assign a value to a variable,  =, +=, -=, |=,...  Assignment operators example: int x = 6; int y = 4; Console.WriteLine(y *= 2); // 8 int z = y = 3; // y=3 and z=3 Console.WriteLine(z); // 3 Console.WriteLine(x |= 1); // 7 Console.WriteLine(x += 3); // 10 Console.WriteLine(x /= 2); // 5

 String concatenation operator + is used to concatenate strings  If the second operand is not a string, it is converted to string automatically string first = "First"; string second = "Second"; Console.WriteLine(first + second); // FirstSecond string output = "The number is : "; int number = 5; Console.WriteLine(output + number); // The number is : 5

 Member access operator. is used to access object members  Square brackets [] are used with arrays indexers and attributes  Parentheses ( ) are used to override the default operator precedence  Class cast operator (type) is used to cast one compatible type to another

 Conditional operator ?: has the form (if b is true then the result is x else the result is y )  The new operator is used to create new objects  The typeof operator returns System.Type object (the reflection of a type)  The is operator checks if an object is compatible with given type b ? x : y

 Using some other operators: int a = 6; int b = 4; Console.WriteLine(a > b ? "a>b" : "b>=a"); // a>b Console.WriteLine((long) a); // 6 int c = b = 3; // b=3; followed by c=3; Console.WriteLine(c); // 3 Console.WriteLine(a is int); // True Console.WriteLine((a+b)/2); // 4 Console.WriteLine(typeof(int)); // System.Int32 int d = new int(); Console.WriteLine(d); // 0

 Example of implicit and explicit conversions:  Note: explicit conversion may be used even if not required by the compiler float heightInMeters = 1.74f; // Explicit conversion double maxHeight = heightInMeters; // Implicit double minHeight = (double) heightInMeters; // Explicit float actualHeight = (float) maxHeight; // Explicit float maxHeightFloat = maxHeight; // Compilation error!

Printing / Reading Strings and Numbers 51

 Provides methods for input and output  Input  Read(…) – reads a single character  ReadLine(…) – reads a single line of characters  Output  Write(…) – prints the specified argument on the console  WriteLine(…) – prints specified data to the console and moves to the next line 52

 Printing more than one variable using a formatting string int a = 15;... Console.Write(a); // 15  Printing an integer variable double a = 15.5; int b = 14;... Console.Write("{0} + {1} = {2}", a, b, a + b); // = 29.5  Next print operation will start from the same line 53

 Printing more than one variable using a formatting string string str = "Hello C#!";...Console.WriteLine(str);  Printing a string variable string name = "Marry"; int year = 1987;... Console.Write("{0} was born in {1}.", name, year); // Marry was born in  Next printing will start from the next line 54

static void Main() { string name = "Peter"; string name = "Peter"; int age = 18; int age = 18; string town = "Sofia"; string town = "Sofia"; Console.Write("{0} is {1} years old from {2}.", Console.Write("{0} is {1} years old from {2}.", name, age, town); name, age, town); // Result: Peter is 18 years old from Sofia. // Result: Peter is 18 years old from Sofia. Console.Write("This is on the same line!"); Console.Write("This is on the same line!"); Console.WriteLine("Next sentence will be" + Console.WriteLine("Next sentence will be" + " on a new line."); " on a new line."); Console.WriteLine("Bye, bye, {0} from {1}.", Console.WriteLine("Bye, bye, {0} from {1}.", name, town); name, town);} 55

 We use the console to read information from the command line  We can read:  Characters  Strings  Numeral types (after conversion)  To read from the console we use the methods Console.Read() and Console.ReadLine() 56

 Gets a line of characters  Returns a string value  Returns null if the end of the input is reached Console.Write("Please enter your first name: "); string firstName = Console.ReadLine(); Console.Write("Please enter your last name: "); string lastName = Console.ReadLine(); Console.WriteLine("Hello, {0} {1}!", firstName, lastName); firstName, lastName); 57

 Numeral types can not be read directly from the console  To read a numeral type do following: 1.R ead a string value 2.Convert (parse) it to the required numeral type  int.Parse(string) – parses a string to int string str = Console.ReadLine() int number = int.Parse(str); Console.WriteLine("You entered: {0}", number); 58

 Numeral types have a method Parse(…) for extracting the numeral value from a string  int.Parse(string) – string  int  long.Parse(string) – string  long  float.Parse(string) – string  float  Causes FormatException in case of error string s = "123"; int i = int.Parse(s); // i = 123 long l = long.Parse(s); // l = 123L string invalid = "xxx1845"; int value = int.Parse(invalid); // FormatException 59

Implementing Conditional Logic

 The most simple conditional statement  Enables you to test for a condition  Branch to different parts of the code depending on the result  The simplest form of an if statement: if (condition) { statements; statements;} 61

62 static void Main() { Console.WriteLine("Enter two numbers."); Console.WriteLine("Enter two numbers."); int biggerNumber = int.Parse(Console.ReadLine()); int biggerNumber = int.Parse(Console.ReadLine()); int smallerNumber = int.Parse(Console.ReadLine()); int smallerNumber = int.Parse(Console.ReadLine()); if (smallerNumber > biggerNumber) if (smallerNumber > biggerNumber) { biggerNumber = smallerNumber; biggerNumber = smallerNumber; } Console.WriteLine("The greater number is: {0}", Console.WriteLine("The greater number is: {0}", biggerNumber); biggerNumber);}

 More complex and useful conditional statement  Executes one branch if the condition is true, and another if it is false  The simplest form of an if-else statement: if (expression) { statement1; statement1;}else{ statement2; statement2;} 63

 Checking a number if it is odd or even string s = Console.ReadLine(); int number = int.Parse(s); if (number % 2 == 0) { Console.WriteLine("This number is even."); Console.WriteLine("This number is even.");}else{ Console.WriteLine("This number is odd."); Console.WriteLine("This number is odd.");} 64

 if and if-else statements can be nested, i.e. used inside another if or else statement  Every else corresponds to its closest preceding if if (expression) { if (expression) if (expression) { statement; statement; } else else { statement; statement; }}else 65

if (first == second) { Console.WriteLine( Console.WriteLine( "These two numbers are equal."); "These two numbers are equal.");}else{ if (first > second) if (first > second) { Console.WriteLine( Console.WriteLine( "The first number is bigger."); "The first number is bigger."); } else else { Console.WriteLine("The second is bigger."); Console.WriteLine("The second is bigger."); }} 66

 Selects for execution a statement from a list depending on the value of the switch expression switch (day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; default: Console.WriteLine("Error!"); break; } 67

Repeating Statements Multiple Times

 The simplest and most frequently used loop  The repeat condition  Returns a boolean result of true or false  Also called loop condition while (condition) { statements; statements;}

int counter = 0; while (counter < 10) { Console.WriteLine("Number : {0}", counter); Console.WriteLine("Number : {0}", counter); counter++; counter++;}

 Another loop structure is:  The block of statements is repeated  While the boolean loop condition holds  The loop is executed at least once do{ statements; statements;} while (condition);

 Calculating N factorial static void Main() { int n = Convert.ToInt32(Console.ReadLine()); int n = Convert.ToInt32(Console.ReadLine()); int factorial = 1; int factorial = 1; do do { factorial *= n; factorial *= n; n--; n--; } while (n > 0); while (n > 0); Console.WriteLine("n! = " + factorial); Console.WriteLine("n! = " + factorial);}

 The typical for loop syntax is:  Consists of  Initialization statement  Boolean test expression  Update statement  Loop body block for (initialization; test; update) { statements; }

 Calculating n to power m (denoted as n^m ): static void Main() { int n = int.Parse(Console.ReadLine()); int n = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); decimal result = 1; decimal result = 1; for (int i=0; i<m; i++) for (int i=0; i<m; i++) { result *= n; result *= n; } Console.WriteLine("n^m = " + result); Console.WriteLine("n^m = " + result);}

 The typical foreach loop syntax is:  Iterates over all elements of a collection  The element is the loop variable that takes sequentially all collection values  The collection can be list, array or other group of elements of the same type foreach (Type element in collection) { statements; }

 Example of foreach loop: string[] days = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; "Friday", "Saturday", "Sunday" }; foreach (String day in days) { Console.WriteLine(day); Console.WriteLine(day);}  The above loop iterates of the array of days  The variable day takes all its values

Declaring and Using Methods

 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 78

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() { //... //... }}  Methods are always declared inside a class  Main() is also a method like all others 79

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

 Method’s behavior depends on its parameters  Parameters can be of any type  int, double, string, etc.  arrays ( int[], double[], etc.) 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");} 81

 Methods can have as many parameters as needed:  The following syntax is not valid: 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) 82

 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: PrintSign(-5);PrintSign(balance);PrintSign(2+3); PrintMax(100, 200); PrintMax(oldQuantity * 1.5, quantity * 2); 83

 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: string message = Console.ReadLine(); // Console.ReadLine() returns a string float price = GetPrice() * quantity * 1.20; int age = int.Parse(Console.ReadLine()); 84

 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 static int Multiply(int firstNum, int secondNum) { return firstNum * secondNum; return firstNum * secondNum;} 85

 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 return -1; return; 86

 Convert temperature from Fahrenheit to Celsius: 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);} 87

Questions?