Classes provide templates for objects by defining attributes and behaviors. An object is an instance of a class that holds specific state through its attribute values. Classes in C# can contain fields to store data, properties for encapsulated access to fields, methods to implement behaviors, and constructors to initialize objects. Constructors are special methods that are called when an object is instantiated and assign initial field values.
Report
Share
Report
Share
1 of 69
More Related Content
Using class and object java
1. Using Classes and ObjectsUsing Classes and Objects
Using the Standard .NET Framework ClassesUsing the Standard .NET Framework Classes
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
2. Table of ContentsTable of Contents
1.1. Classes and ObjectsClasses and Objects
What are Objects?What are Objects?
What are Classes?What are Classes?
1.1. Classes in C#Classes in C#
Declaring ClassDeclaring Class
Fields and Properties: Instance and StaticFields and Properties: Instance and Static
Instance and Static MethodsInstance and Static Methods
ConstructorsConstructors
1.1. StructuresStructures
3. Table of Contents (2)Table of Contents (2)
4.4. NamespacesNamespaces
5.5. RandomRandom classclass
6.6. Introduction to .NETIntroduction to .NET
Common Type SystemCommon Type System
4. Classes and ObjectsClasses and Objects
Modeling Real-world Entities with ObjectsModeling Real-world Entities with Objects
5. What are Objects?What are Objects?
Software objects model real-world objects orSoftware objects model real-world objects or
abstract conceptsabstract concepts
Examples:Examples:
bank, account, customer, dog, bicycle, queuebank, account, customer, dog, bicycle, queue
Real-world objects haveReal-world objects have statesstates andand behaviorsbehaviors
Account' states:Account' states:
holder, balance, typeholder, balance, type
Account' behaviors:Account' behaviors:
withdraw, deposit, suspendwithdraw, deposit, suspend
6. What are Objects? (2)What are Objects? (2)
How do software objects implement real-How do software objects implement real-
world objects?world objects?
Use variables/data to implement statesUse variables/data to implement states
Use methods/functions to implement behaviorsUse methods/functions to implement behaviors
An object is a software bundle of variables andAn object is a software bundle of variables and
related methodsrelated methods
8. What is Class?What is Class?
The formal definition ofThe formal definition of classclass::
Definition by GoogleDefinition by Google
ClassesClasses act as templates from which anact as templates from which an
instance of an object is created at runinstance of an object is created at run
time. Classes define the properties of thetime. Classes define the properties of the
object and the methods used to controlobject and the methods used to control
the object's behavior.the object's behavior.
9. ClassesClasses
Classes provide the structure for objectsClasses provide the structure for objects
Define their prototype, act as templateDefine their prototype, act as template
Classes define:Classes define:
Set ofSet of attributesattributes
Represented by variables and propertiesRepresented by variables and properties
Hold theirHold their statestate
Set of actions (Set of actions (behaviorbehavior))
Represented by methodsRepresented by methods
A class defines the methods and types of dataA class defines the methods and types of data
associated with an objectassociated with an object
10. Classes – ExampleClasses – Example
AccountAccount
+Owner: Person+Owner: Person
+Ammount: double+Ammount: double
+Suspend()+Suspend()
+Deposit(sum:double)+Deposit(sum:double)
+Withdraw(sum:double)+Withdraw(sum:double)
ClassClass
NameName
AttributesAttributes
(Properties(Properties
and Fields)and Fields)
OperationsOperations
(Methods)(Methods)
11. ObjectsObjects
AnAn objectobject is a concreteis a concrete instanceinstance of a particularof a particular
classclass
Creating an object from a class is calledCreating an object from a class is called
instantiationinstantiation
Objects have stateObjects have state
Set of values associated to their attributesSet of values associated to their attributes
Example:Example:
Class:Class: AccountAccount
Objects: Ivan's account, Peter's accountObjects: Ivan's account, Peter's account
13. Classes in C#Classes in C#
Using Classes and their Class MembersUsing Classes and their Class Members
14. Classes in C#Classes in C#
Basic units that compose programsBasic units that compose programs
Implementation isImplementation is encapsulatedencapsulated (hidden)(hidden)
Classes in C# can contain:Classes in C# can contain:
Fields (member variables)Fields (member variables)
PropertiesProperties
MethodsMethods
ConstructorsConstructors
Inner typesInner types
Etc. (events, indexers, operators, …)Etc. (events, indexers, operators, …)
15. Classes in C# – ExamplesClasses in C# – Examples
Example of classes:Example of classes:
System.ConsoleSystem.Console
System.StringSystem.String ((stringstring in C#)in C#)
System.Int32System.Int32 ((intint in C#)in C#)
System.ArraySystem.Array
System.MathSystem.Math
System.RandomSystem.Random
16. Declaring ObjectsDeclaring Objects
An instance of a class or structure can beAn instance of a class or structure can be
defined like any other variable:defined like any other variable:
Instances cannot be used if they areInstances cannot be used if they are
not initializednot initialized
using System;using System;
......
// Define two variables of type DateTime// Define two variables of type DateTime
DateTime today;DateTime today;
DateTime halloween;DateTime halloween;
// Declare and initialize a structure instance// Declare and initialize a structure instance
DateTime today = DateTime.Now;DateTime today = DateTime.Now;
18. FieldsFields
Fields are data members of a classFields are data members of a class
Can be variables and constantsCan be variables and constants
Accessing a field doesn’t invoke any actions ofAccessing a field doesn’t invoke any actions of
the objectthe object
Example:Example:
String.EmptyString.Empty (the(the """" string)string)
19. Accessing FieldsAccessing Fields
Constant fields can be only readConstant fields can be only read
Variable fields can be read and modifiedVariable fields can be read and modified
Usually properties are used instead of directlyUsually properties are used instead of directly
accessing variable fieldsaccessing variable fields
Examples:Examples:
// Accessing read-only field// Accessing read-only field
String empty = String.Empty;String empty = String.Empty;
// Accessing constant field// Accessing constant field
int maxInt = Int32.MaxValue;int maxInt = Int32.MaxValue;
20. PropertiesProperties
Properties look like fields (have name andProperties look like fields (have name and
type), but they can contain code, executedtype), but they can contain code, executed
when they are accessedwhen they are accessed
Usually used to control access to dataUsually used to control access to data
fields (wrappers), but can contain morefields (wrappers), but can contain more
complex logiccomplex logic
Can have two components (and at least oneCan have two components (and at least one
of them) calledof them) called accessorsaccessors
getget for reading their valuefor reading their value
setset for changing their valuefor changing their value
21. Properties (2)Properties (2)
According to the implemented accessorsAccording to the implemented accessors
properties can be:properties can be:
Read-only (Read-only (getget accessor only)accessor only)
Read and write (bothRead and write (both getget andand setset accessors)accessors)
Write-only (Write-only (setset accessor only)accessor only)
Example of read-only property:Example of read-only property:
String.LengthString.Length
22. Accessing PropertiesAccessing Properties
and Fields – Exampleand Fields – Example
using System;using System;
......
DateTime christmas = new DateTime(2009, 12, 25);DateTime christmas = new DateTime(2009, 12, 25);
int day = christmas.Day;int day = christmas.Day;
int month = christmas.Month;int month = christmas.Month;
int year = christmas.Year;int year = christmas.Year;
Console.WriteLine(Console.WriteLine(
"Christmas day: {0}, month: {1}, year: {2}","Christmas day: {0}, month: {1}, year: {2}",
day, month, year);day, month, year);
Console.WriteLine(Console.WriteLine(
"Day of year: {0}", christmas.DayOfYear);"Day of year: {0}", christmas.DayOfYear);
Console.WriteLine("Is {0} leap year: {1}",Console.WriteLine("Is {0} leap year: {1}",
year, DateTime.IsLeapYear(year));year, DateTime.IsLeapYear(year));
24. Instance and Static MembersInstance and Static Members
Accessing Object and Class MembersAccessing Object and Class Members
25. Instance and Static MembersInstance and Static Members
Fields, properties and methods can be:Fields, properties and methods can be:
Instance (or object members)Instance (or object members)
Static (or class members)Static (or class members)
Instance members are specific for each objectInstance members are specific for each object
Example: different dogs have different nameExample: different dogs have different name
Static members are common for all instancesStatic members are common for all instances
of a classof a class
Example:Example: DateTime.MinValueDateTime.MinValue is sharedis shared
between all instances ofbetween all instances of DateTimeDateTime
26. Accessing Members – SyntaxAccessing Members – Syntax
Accessing instance membersAccessing instance members
The name of theThe name of the instanceinstance, followed by the, followed by the
name of the member (field or property),name of the member (field or property),
separated by dot ("separated by dot ("..")")
Accessing static membersAccessing static members
The name of theThe name of the classclass, followed by the name of, followed by the name of
the memberthe member
<instance_name>.<member_name><instance_name>.<member_name>
<class_name>.<member_name><class_name>.<member_name>
27. Instance and StaticInstance and Static
Members – ExamplesMembers – Examples
Example of instance memberExample of instance member
String.LengthString.Length
Each string object has different lengthEach string object has different length
Example of static memberExample of static member
Console.ReadLine()Console.ReadLine()
The console is only one (global for the program)The console is only one (global for the program)
Reading from the console does not require toReading from the console does not require to
create an instance of itcreate an instance of it
29. MethodsMethods
Methods manipulate the data of the object toMethods manipulate the data of the object to
which they belong or perform other taskswhich they belong or perform other tasks
Examples:Examples:
Console.WriteLine(…)Console.WriteLine(…)
Console.ReadLine()Console.ReadLine()
String.Substring(index, length)String.Substring(index, length)
Array.GetLength(index)Array.GetLength(index)
30. Instance MethodsInstance Methods
Instance methods manipulate the data of aInstance methods manipulate the data of a
specified object or perform any other tasksspecified object or perform any other tasks
If a value is returned, it depends on theIf a value is returned, it depends on the
particular class instanceparticular class instance
Syntax:Syntax:
The name of the instance, followed by theThe name of the instance, followed by the
name of the method, separated by dotname of the method, separated by dot
<object_name>.<method_name>(<parameters>)<object_name>.<method_name>(<parameters>)
33. Static MethodsStatic Methods
Static methods are common for all instances ofStatic methods are common for all instances of
a class (shared between all instances)a class (shared between all instances)
Returned value depends only on the passedReturned value depends only on the passed
parametersparameters
No particular class instance is availableNo particular class instance is available
Syntax:Syntax:
The name of the class, followed by the name ofThe name of the class, followed by the name of
the method, separated by dotthe method, separated by dot
<class_name>.<method_name>(<parameters>)<class_name>.<method_name>(<parameters>)
36. ConstructorsConstructors
Constructors are special methods used toConstructors are special methods used to
assign initial values of the fields in an objectassign initial values of the fields in an object
Executed when an object of a given type isExecuted when an object of a given type is
being createdbeing created
Have the same name as the class that holdsHave the same name as the class that holds
themthem
Do not return a valueDo not return a value
A class may have several constructors withA class may have several constructors with
different set of parametersdifferent set of parameters
37. Constructors (2)Constructors (2)
Constructor is invoked by theConstructor is invoked by the newnew operatoroperator
Examples:Examples:
String s = new String("Hello!"); // s = "Hello!"String s = new String("Hello!"); // s = "Hello!"
<instance_name> = new <class_name>(<parameters>)<instance_name> = new <class_name>(<parameters>)
String s = new String('*', 5); // s = "*****"String s = new String('*', 5); // s = "*****"
DateTime dt = new DateTime(2009, 12, 30);DateTime dt = new DateTime(2009, 12, 30);
DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59);DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59);
Int32 value = new Int32(1024);Int32 value = new Int32(1024);
38. Parameterless ConstructorsParameterless Constructors
The constructor without parameters is calledThe constructor without parameters is called
defaultdefault constructorconstructor
Example:Example:
Creating an object for generating randomCreating an object for generating random
numbers with a default seednumbers with a default seed
using System;using System;
......
Random randomGenerator = new Random();Random randomGenerator = new Random();
The classThe class System.RandomSystem.Random providesprovides
generation of pseudo-randomgeneration of pseudo-random
numbersnumbers
ParameterlessParameterless
constructorconstructor
callcall
39. Constructor With ParametersConstructor With Parameters
ExampleExample
Creating objects for generating random valuesCreating objects for generating random values
with specified initial seedswith specified initial seeds
using System;using System;
......
Random randomGenerator1 = new Random(123);Random randomGenerator1 = new Random(123);
Console.WriteLine(randomGenerator1.Next());Console.WriteLine(randomGenerator1.Next());
// 2114319875// 2114319875
Random randomGenerator2 = new Random(456);Random randomGenerator2 = new Random(456);
Console.WriteLine(randomGenerator2.Next(50));Console.WriteLine(randomGenerator2.Next(50));
// 47// 47
41. More Constructor ExamplesMore Constructor Examples
Creating aCreating a DateTimeDateTime object for a specifiedobject for a specified
date and timedate and time
Different constructors are called depending onDifferent constructors are called depending on
the different sets of parametersthe different sets of parameters
using System;using System;
DateTime halloween = new DateTime(2009, 10, 31);DateTime halloween = new DateTime(2009, 10, 31);
Console.WriteLine(halloween);Console.WriteLine(halloween);
DateTime julyMorning;DateTime julyMorning;
julyMorning = new DateTime(2009,7,1, 5,52,0);julyMorning = new DateTime(2009,7,1, 5,52,0);
Console.WriteLine(julyMorning);Console.WriteLine(julyMorning);
44. EnumerationsEnumerations
EnumerationsEnumerations in C# are types whose values arein C# are types whose values are
limited to a predefined set of valueslimited to a predefined set of values
E.g. the days of weekE.g. the days of week
Declared by the keywordDeclared by the keyword enumenum in C#in C#
Hold values from a predefined setHold values from a predefined set
44
public enum Color { Red, Green, Blue, Black }public enum Color { Red, Green, Blue, Black }
……
Color color = Color.Red;Color color = Color.Red;
Console.WriteLine(color); // RedConsole.WriteLine(color); // Red
color = 5; // Compilation error!color = 5; // Compilation error!
46. StructuresStructures
Structures are similar to classesStructures are similar to classes
Structures are usually used for storing dataStructures are usually used for storing data
structures, without any other functionalitystructures, without any other functionality
Structures can have fields, properties, etc.Structures can have fields, properties, etc.
Using methods is not recommendedUsing methods is not recommended
Structures areStructures are value typesvalue types, and classes are, and classes are
reference typesreference types (this will be discussed later)(this will be discussed later)
Example of structureExample of structure
System.DateTimeSystem.DateTime – represents a date and time– represents a date and time
48. What is a Namespace?What is a Namespace?
Namespaces are used to organize the sourceNamespaces are used to organize the source
code into more logical and manageable waycode into more logical and manageable way
Namespaces can containNamespaces can contain
Definitions of classes, structures, interfaces andDefinitions of classes, structures, interfaces and
other types and other namespacesother types and other namespaces
Namespaces can contain other namespacesNamespaces can contain other namespaces
For example:For example:
SystemSystem namespace containsnamespace contains DataData namespacenamespace
The name of the nested namespace isThe name of the nested namespace is
System.DataSystem.Data
49. Full Class NamesFull Class Names
A full name of a class is the name of the classA full name of a class is the name of the class
preceded by the name of its namespacepreceded by the name of its namespace
Example:Example:
ArrayArray class, defined in theclass, defined in the SystemSystem namespacenamespace
The full name of the class isThe full name of the class is System.ArraySystem.Array
<namespace_name>.<class_name><namespace_name>.<class_name>
50. Including NamespacesIncluding Namespaces
TheThe usingusing directive in C#:directive in C#:
Allows using types in a namespace, withoutAllows using types in a namespace, without
specifying their full namespecifying their full name
Example:Example:
instead ofinstead of
using <namespace_name>using <namespace_name>
using System;using System;
DateTime date;DateTime date;
System.DateTime date;System.DateTime date;
52. TheThe RandomRandom ClassClass
TheThe RandomRandom classclass
Generates random integer numbersGenerates random integer numbers
bytebyte oror intint
Random rand = new Random();Random rand = new Random();
for (int number = 1; number <= 6; number++)for (int number = 1; number <= 6; number++)
{{
iint randomNumber = rand.Next(49) + 1;nt randomNumber = rand.Next(49) + 1;
Console.Write("{0} ", randomNumber);Console.Write("{0} ", randomNumber);
}}
This generates six random numbers from 1 toThis generates six random numbers from 1 to
4949
TheThe Next()Next() method returns a randommethod returns a random
numbernumber
53. Password GeneratorPassword Generator
Generates a random password between 8 and 15Generates a random password between 8 and 15
characterscharacters
The password contains of at least two capitalThe password contains of at least two capital
letters, two small letters, one digit and threeletters, two small letters, one digit and three
special charactersspecial characters
Constructing the Password Generator class:Constructing the Password Generator class:
Start from empty passwordStart from empty password
Place two random capital letters at randomPlace two random capital letters at random
positionspositions
Place two random small letters at random positionsPlace two random small letters at random positions
Place one random digit at random positionsPlace one random digit at random positions
Place three special characters at random positionsPlace three special characters at random positions
53
54. Password Generator (2)Password Generator (2)
Now we have exactly 8 charactersNow we have exactly 8 characters
To make the length between 8 and 15 weTo make the length between 8 and 15 we
generate a number N between 0 and 7generate a number N between 0 and 7
And then inserts N random characters ( capitalAnd then inserts N random characters ( capital
letter or small letter or digit or specialletter or small letter or digit or special
character) at random positionscharacter) at random positions
54
55. class RandomPasswordGeneratorclass RandomPasswordGenerator
{{
private const stringprivate const string CapitalLettersCapitalLetters==
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const stringprivate const string SmallLettersSmallLetters ==
"abcdefghijklmnopqrstuvwxyz";"abcdefghijklmnopqrstuvwxyz";
private const stringprivate const string DigitsDigits = "0123456789";= "0123456789";
pprivate const stringrivate const string SpecialCharsSpecialChars ==
"~!@#$%^&*()_+=`{}[]|':;.,/?<>";"~!@#$%^&*()_+=`{}[]|':;.,/?<>";
private const stringprivate const string AllCharsAllChars ==
CapitalLettersCapitalLetters ++ SmallLettersSmallLetters ++ DigitsDigits ++ SpecialCharsSpecialChars;;
private static Random rnd = new Random();private static Random rnd = new Random();
// the example continues…// the example continues…
Password Generator ClassPassword Generator Class
56. Password Generator ClassPassword Generator Class
56
static void Main()static void Main()
{{
StringBuilder password = new StringBuilder();StringBuilder password = new StringBuilder();
ffor (int i = 1; i <= 2; i++)or (int i = 1; i <= 2; i++)
{{
char capitalLetter = GenerateChar(char capitalLetter = GenerateChar(CapitalLettersCapitalLetters););
InsertAtRandomPosition(password, capitalLetter);InsertAtRandomPosition(password, capitalLetter);
}}
for (int i = 1; i <= 2; i++)for (int i = 1; i <= 2; i++)
{{
char smallLetter = GenerateChar(char smallLetter = GenerateChar(SmallLettersSmallLetters););
InsertAtRandomPosition(password, smallLetter);InsertAtRandomPosition(password, smallLetter);
}}
char digit = GenerateChar(char digit = GenerateChar(DigitsDigits););
InsertAtRandomPosition(password, digit);InsertAtRandomPosition(password, digit);
for (int i = 1; i <= 3; i++)for (int i = 1; i <= 3; i++)
{{
char specialChar = GenerateChar(char specialChar = GenerateChar(SpecialCharsSpecialChars););
InsertAtRandomPosition(password, specialChar);InsertAtRandomPosition(password, specialChar);
}}
// the example continues…// the example continues…
59. Common Type System (CTS)Common Type System (CTS)
CTS defines all dataCTS defines all data typestypes supported in .NETsupported in .NET
FrameworkFramework
Primitive types (e.g.Primitive types (e.g. intint,, floatfloat,, objectobject))
Classes (e.g.Classes (e.g. StringString,, ConsoleConsole,, ArrayArray))
Structures (e.g.Structures (e.g. DateTimeDateTime))
Arrays (e.g.Arrays (e.g. intint[][],, string[,]string[,]))
Etc.Etc.
Object-oriented by designObject-oriented by design
60. CTS and Different LanguagesCTS and Different Languages
CTS is common for all .NET languagesCTS is common for all .NET languages
C#, VB.NET, J#,C#, VB.NET, J#, JScript.NETJScript.NET, ..., ...
CTS type mappings:CTS type mappings:
CTS TypeCTS Type C# TypeC# Type VB.NET TypeVB.NET Type
System.Int32System.Int32 intint IntegerInteger
System.SingleSystem.Single floatfloat SingleSingle
System.BooleanSystem.Boolean boolbool BooleanBoolean
System.StringSystem.String stringstring StringString
System.ObjectSystem.Object objectobject ObjectObject
61. Value and Reference TypesValue and Reference Types
In CTS there are two categories of typesIn CTS there are two categories of types
ValueValue typestypes
Reference typesReference types
Placed in different areas of memoryPlaced in different areas of memory
Value types live in theValue types live in the execution stackexecution stack
Freed when become out of scopeFreed when become out of scope
Reference types live in theReference types live in the managed heapmanaged heap
(dynamic memory)(dynamic memory)
Freed by theFreed by the garbage collectorgarbage collector
62. Value and Reference Types –Value and Reference Types –
ExamplesExamples
Value typesValue types
Most of the primitive typesMost of the primitive types
StructuresStructures
Examples:Examples: intint,, floatfloat,, boolbool,, DateTimeDateTime
Reference typesReference types
Classes and interfacesClasses and interfaces
StringsStrings
ArraysArrays
Examples:Examples: stringstring,, RandomRandom,, objectobject,, int[]int[]
63. System.Object: CTS Base TypeSystem.Object: CTS Base Type
System.ObjectSystem.Object ((objectobject in C#) is a basein C#) is a base typetype
for all other typesfor all other types in CTSin CTS
Can hold values of any other type:Can hold values of any other type:
All .NET types derive common methods fromAll .NET types derive common methods from
System.ObjectSystem.Object, e.g., e.g. ToString()ToString()
string s = "test";string s = "test";
object obj = s;object obj = s;
DateTime now = DateTime.Now;DateTime now = DateTime.Now;
string nowInWords = now.ToString();string nowInWords = now.ToString();
Console.WriteLine(nowInWords);Console.WriteLine(nowInWords);
64. SummarySummary
Classes provide the structure for objectsClasses provide the structure for objects
Objects are particular instances of classesObjects are particular instances of classes
Classes have different membersClasses have different members
Methods, fields, properties, etc.Methods, fields, properties, etc.
Instance and static membersInstance and static members
Members can be accessedMembers can be accessed
Methods can be calledMethods can be called
Structures are used for storing dataStructures are used for storing data
65. Summary (2)Summary (2)
Namespaces help organizing the classesNamespaces help organizing the classes
Common Type System (CTS) defines the typesCommon Type System (CTS) defines the types
for all .NET languagesfor all .NET languages
Values typesValues types
Reference typesReference types
67. ExercisesExercises
1.1. Write a program that reads a year from the consoleWrite a program that reads a year from the console
and checks whether it is a leap. Useand checks whether it is a leap. Use DateTimeDateTime..
2.2. Write a program that generates and prints to theWrite a program that generates and prints to the
console 10 random values in the range [100, 200].console 10 random values in the range [100, 200].
3.3. Write a program that prints to the console which dayWrite a program that prints to the console which day
of the week is today. Useof the week is today. Use System.DateTimeSystem.DateTime..
4.4. Write methods that calculate the surface of a triangleWrite methods that calculate the surface of a triangle
by given:by given:
Side and an altitude to it; Three sides; Two sidesSide and an altitude to it; Three sides; Two sides
and an angle between them. Useand an angle between them. Use System.MathSystem.Math..
68. Exercises (2)Exercises (2)
5.5. Write a method that calculates the number ofWrite a method that calculates the number of
workdays between today and given date, passed asworkdays between today and given date, passed as
parameter. Consider that workdays are all days fromparameter. Consider that workdays are all days from
Monday to Friday except a fixed array of publicMonday to Friday except a fixed array of public
holidays specified preliminary as array.holidays specified preliminary as array.
6.6. You are given a sequence of positive integer valuesYou are given a sequence of positive integer values
written into a string, separated by spaces. Write awritten into a string, separated by spaces. Write a
function that reads these values from given stringfunction that reads these values from given string
and calculates their sum. Example:and calculates their sum. Example:
string = "string = "43 68 9 23 31843 68 9 23 318"" result =result = 461461
69. Exercises (3)Exercises (3)
7.7. * Write a program that calculates the value of given* Write a program that calculates the value of given
arithmetical expression. The expression can containarithmetical expression. The expression can contain
the following elements only:the following elements only:
Real numbers, e.g.Real numbers, e.g. 55,, 18.3318.33,, 3.141593.14159,, 12.612.6
Arithmetic operators:Arithmetic operators: ++,, --,, **,, // (standard priorities)(standard priorities)
Mathematical functions:Mathematical functions: ln(x)ln(x),, sqrt(x)sqrt(x),, pow(x,y)pow(x,y)
Brackets (for changing the default priorities)Brackets (for changing the default priorities)
Examples:Examples:
(3+5.3)(3+5.3) ** 2.72.7 -- ln(22)ln(22) // pow(2.2,pow(2.2, -1.7)-1.7) ~~ 10.610.6
pow(2,pow(2, 3.14)3.14) ** (3(3 -- (3(3 ** sqrt(2)sqrt(2) -- 3.2)3.2) ++ 1.5*0.3)1.5*0.3) ~ 21.22~ 21.22
Hint: Use the classicalHint: Use the classical "shunting yard" algorithm"shunting yard" algorithm andand
"reverse Polish notation""reverse Polish notation"..