C# - Arrays - Tutorialspoint

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?