C# - Arrays - Tutorialspoint
文章推薦指數: 80 %
int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;. When you create an array, C# compiler implicitly initializes each array element to a ... Home CodingGround Jobs Whiteboard Tools Business Teachwithus C#BasicTutorial C#-Home C#-Overview C#-Environment C#-ProgramStructure C#-BasicSyntax C#-DataTypes C#-TypeConversion C#-Variables C#-Constants C#-Operators C#-DecisionMaking C#-Loops C#-Encapsulation C#-Methods C#-Nullables C#-Arrays C#-Strings C#-Structure C#-Enums C#-Classes C#-Inheritance C#-Polymorphism C#-OperatorOverloading C#-Interfaces C#-Namespaces C#-PreprocessorDirectives C#-RegularExpressions C#-ExceptionHandling C#-FileI/O C#AdvancedTutorial C#-Attributes C#-Reflection C#-Properties C#-Indexers C#-Delegates C#-Events C#-Collections C#-Generics C#-AnonymousMethods C#-UnsafeCodes C#-Multithreading C#UsefulResources C#-QuestionsandAnswers C#-QuickGuide C#-UsefulResources C#-Discussion SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho C#-Arrays Advertisements PreviousPage NextPage Anarraystoresafixed-sizesequentialcollectionofelementsofthesametype.Anarrayisusedtostoreacollectionofdata,butitisoftenmoreusefultothinkofanarrayasacollectionofvariablesofthesametypestoredatcontiguousmemorylocations. Insteadofdeclaringindividualvariables,suchasnumber0,number1,...,andnumber99,youdeclareonearrayvariablesuchasnumbersandusenumbers[0],numbers[1],and...,numbers[99]torepresentindividualvariables.Aspecificelementinanarrayisaccessedbyanindex. Allarraysconsistofcontiguousmemorylocations.Thelowestaddresscorrespondstothefirstelementandthehighestaddresstothelastelement. DeclaringArrays TodeclareanarrayinC#,youcanusethefollowingsyntax− datatype[]arrayName; where, datatypeisusedtospecifythetypeofelementsinthearray. []specifiestherankofthearray.Therankspecifiesthesizeofthearray. arrayNamespecifiesthenameofthearray. Forexample, double[]balance; InitializinganArray Declaringanarraydoesnotinitializethearrayinthememory.Whenthearrayvariableisinitialized,youcanassignvaluestothearray. Arrayisareferencetype,soyouneedtousethenewkeywordtocreateaninstanceofthearray.Forexample, double[]balance=newdouble[10]; AssigningValuestoanArray Youcanassignvaluestoindividualarrayelements,byusingtheindexnumber,like− double[]balance=newdouble[10]; balance[0]=4500.0; Youcanassignvaluestothearrayatthetimeofdeclaration,asshown− double[]balance={2340.0,4523.69,3421.0}; Youcanalsocreateandinitializeanarray,asshown− int[]marks=newint[5]{99,98,92,97,95}; Youmayalsoomitthesizeofthearray,asshown− int[]marks=newint[]{99,98,92,97,95}; Youcancopyanarrayvariableintoanothertargetarrayvariable.Insuchcase,boththetargetandsourcepointtothesamememorylocation− int[]marks=newint[]{99,98,92,97,95}; int[]score=marks; Whenyoucreateanarray,C#compilerimplicitlyinitializeseacharrayelementtoadefaultvaluedependingonthearraytype.Forexample,foranintarrayallelementsareinitializedto0. AccessingArrayElements Anelementisaccessedbyindexingthearrayname.Thisisdonebyplacingtheindexoftheelementwithinsquarebracketsafterthenameofthearray.Forexample, doublesalary=balance[9]; Thefollowingexample,demonstratestheabove-mentionedconceptsdeclaration,assignment,andaccessingarrays− LiveDemo usingSystem; namespaceArrayApplication{ classMyArray{ staticvoidMain(string[]args){ int[]n=newint[10];/*nisanarrayof10integers*/ inti,j; /*initializeelementsofarrayn*/ for(i=0;i<10;i++){ n[i]=i+100; } /*outputeacharrayelement'svalue*/ for(j=0;j<10;j++){ Console.WriteLine("Element[{0}]={1}",j,n[j]); } Console.ReadKey(); } } } Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult− Element[0]=100 Element[1]=101 Element[2]=102 Element[3]=103 Element[4]=104 Element[5]=105 Element[6]=106 Element[7]=107 Element[8]=108 Element[9]=109 UsingtheforeachLoop Inthepreviousexample,weusedaforloopforaccessingeacharrayelement.Youcanalsouseaforeachstatementtoiteratethroughanarray. LiveDemo usingSystem; namespaceArrayApplication{ classMyArray{ staticvoidMain(string[]args){ int[]n=newint[10];/*nisanarrayof10integers*/ /*initializeelementsofarrayn*/ for(inti=0;i<10;i++){ n[i]=i+100; } /*outputeacharrayelement'svalue*/ foreach(intjinn){ inti=j-100; Console.WriteLine("Element[{0}]={1}",i,j); } Console.ReadKey(); } } } Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult− Element[0]=100 Element[1]=101 Element[2]=102 Element[3]=103 Element[4]=104 Element[5]=105 Element[6]=106 Element[7]=107 Element[8]=108 Element[9]=109 C#Arrays TherearefollowingfewimportantconceptsrelatedtoarraywhichshouldbecleartoaC#programmer− Sr.No. Concept&Description 1 Multi-dimensionalarrays C#supportsmultidimensionalarrays.Thesimplestformofthemultidimensionalarrayisthetwo-dimensionalarray. 2 Jaggedarrays C#supportsmultidimensionalarrays,whicharearraysofarrays. 3 Passingarraystofunctions Youcanpasstothefunctionapointertoanarraybyspecifyingthearray'snamewithoutanindex. 4 Paramarrays Thisisusedforpassingunknownnumberofparameterstoafunction. 5 TheArrayClass DefinedinSystemnamespace,itisthebaseclasstoallarrays,andprovidesvariouspropertiesandmethodsforworkingwitharrays. PreviousPage PrintPage NextPage Advertisements
延伸文章資訊
- 1Day17-C#陣列Array、不規則陣列。神啊 - iT 邦幫忙
C#陣列簡介. 1.陣列Array是多個相同資料型別的變數,在記憶體中連續串在一起的物件,需用new進行建立物件及宣告 2.宣告時由於是要跟電腦要一串連續的記憶體空間,陣列 ...
- 2C# Array Examples, String Arrays - Dot Net Perls
Create and loop over a string array. Access array Length and get elements at indexes.
- 3C# | Arrays of Strings - GeeksforGeeks
C# | Arrays of Strings ... declares & initializes string array String[] s1 = new String[2]; // as...
- 4C# Arrays - W3Schools
Create an Array ... Arrays are used to store multiple values in a single variable, instead of dec...
- 5C# - Arrays - Tutorialspoint
int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;. When you create an array, C...