Skip to main content
Engineering LibreTexts

13.6: Initializing Arrays

  • Page ID
    54349
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    An array can be initialized when it is declared. Each element in the array can be initialized to a single value or each element to a different value. The following declaration,

    real, dimension(10) :: numbers = 1.0
    

    will initialize each of the 10 elements in the array numbers to 1.0.

    To initialize each element to a different value, each value needs to be specified.

    For example, the following declaration,

    real, dimension(5) :: numbers = (/ 1.0, 2.0, 3.0, 4.0, 5.0 /)
    

    will initialize each of the 5 elements in the array numbers to 1.0, 2.0, 3.0, 4.0, and 5.0 respectively.

    The implied do-loop may also be used. For example, in the following declaration,

    integer, dimension(5) :: numbers = (/ (i, i=1,5) /)
    

    will initialize each of the 5 elements in the array numbers to 1, 2, 3, 4, and 5 respectively.


    This page titled 13.6: Initializing Arrays is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Ed Jorgensen via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.

    • Was this article helpful?