{"id":3837,"date":"2019-12-12T16:32:09","date_gmt":"2019-12-12T21:32:09","guid":{"rendered":"https:\/\/www.circuitcrush.com\/?p=3837"},"modified":"2021-06-30T14:31:38","modified_gmt":"2021-06-30T18:31:38","slug":"c-programming-tutorial-7-arrays-2","status":"publish","type":"post","link":"https:\/\/www.circuitcrush.com\/c-programming-tutorial-7-arrays-2\/","title":{"rendered":"C Programming Tutorial 7: More on Arrays in C"},"content":{"rendered":"<p>Welcome to C Programming Tutorial 7, Arrays in C Part 2!<\/p>\n<p><a href=\"https:\/\/www.circuitcrush.com\/c-programming-tutorial-6-arrays-intro\/\" target=\"_blank\" rel=\"noopener noreferrer\">C Tutorial 6 was an introduction to arrays<\/a> in C.<\/p>\n<p>This time, we\u2019re going to go into a little bit more detail about arrays after a quick review.<\/p>\n<p>Let\u2019s do this!<\/p>\n<p><!--more--><\/p>\n<h1><strong>Arrays in C Programming Part 2<br \/>\n<\/strong><\/h1>\n<h2><strong>Review of Array Basics<br \/>\n<\/strong><\/h2>\n<p>An array in C programming is a group of sequential locations in memory that hold one data type such as integers, floats, or chars. An array in C can only hold one data type, so don\u2019t try to create an array that mixes integers with floats, for example.<\/p>\n<p>There are a few different ways to declare an array in C.<\/p>\n<p>We can initialize an array with values if we already know what the array should contain. For example, letters[] is an array of four characters:<\/p>\n<pre>char letters[4] = {A,B,C,D}; \/*declares and initializes an array of 4 characters.*\/<\/pre>\n<p>Often though, we don\u2019t know ahead of time what the array is going to contain, so we can\u2019t initialize it. For example, who_knows is an array of fifty integers, but we don\u2019t know what their exact value is yet.<\/p>\n<pre>int who_knows[50]; \/*declares an array of 50 integers, which will take on values \r\n later as the program runs *\/<\/pre>\n<p>Array indexing starts at 0, not 1. This is a VERY important thing to remember because forgetting it can cause hard-to-find errors. People — even those with C programming experience, make this mistake all the time. Figure 1 is from the first C tutorial on arrays, but here it is again just to drive the point home.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"alignnone wp-image-3203 \" src=\"http:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Programming-1024x576.jpg\" alt=\"Arrays in C\" width=\"702\" height=\"395\" srcset=\"https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Programming-1024x576.jpg 1024w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Programming-600x338.jpg 600w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Programming-150x84.jpg 150w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Programming-300x169.jpg 300w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Programming-768x432.jpg 768w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Programming.jpg 1280w\" sizes=\"(max-width: 702px) 100vw, 702px\" \/><\/p>\n<p><strong><em>Figure 1: Like a character from a bad horror flick, it\u2019s back! Here is a graphical representation of array indexing in C. The first element in the array Num[] is indexed at position 0.<\/em><\/strong><\/p>\n<p>Arrays and for loops are best friends that go way, way back. You\u2019ll use arrays with for loops all the time.<\/p>\n<p>In an effort to not regurgitate everything from the last C tutorial, I\u2019ll stop the review here. If you want a more in depth review on the basics of arrays in C programming see <a href=\"https:\/\/www.circuitcrush.com\/c-programming-tutorial-6-arrays-intro\/\" target=\"_blank\" rel=\"noopener noreferrer\">C Programming Tutorial 6: Intro to Arrays in C<\/a>.<\/p>\n<h2><strong>Designated Initializers \u2013 Another Way to Initialize Arrays in C<br \/>\n<\/strong><\/h2>\n<p>With C99 came a new capability called designated initializers.<\/p>\n<p>This feature allows the programmer to pick and choose which elements to initialize. For example, suppose that you just want to initialize the last element in an array. Using traditional C initialization syntax, you also have to initialize every element preceding the last one:<\/p>\n<pre>int repetitive_and_boring[7] = {0,0,0,0,0,0,339};<\/pre>\n<p>With this method, you can use an index in brackets in the initialization list to specify a particular element of the array:<\/p>\n<pre>int better_way[7] = {[6] = 339}; \/* initializes last element of better_way[] to 339 *\/<\/pre>\n<p>The rest of the elements in our example above are simply set to 0.<\/p>\n<p>And here\u2019s another cool thing about designated initializers \u2013 you can initialize more than one element if you wish, as in the example below.<\/p>\n<pre>int pretty_slick[10] = {[0]=1, [4]=2, [8]=3}; \/* initializes elements 0, 4, and 8 to 1, 2, and 3 *\/<\/pre>\n<p>We can also write something like the following code fragment:<\/p>\n<pre>int days[12] = {31,28,[4]=31,30,31,[1]=28};<\/pre>\n<p>for clarity, the complete C program prints the number of days in each month (well, some of them) and may look something like this:<\/p>\n<pre>#include <stdio.h>\r\nint main(void)\r\n{\r\nint days[12] = {31,28,[4]=31,30,31,[1]=29};\r\nfor (int i = 0; i < 12; i++)\r\nprintf(\"%2d %d\\n\", i + 1, days[i]);\r\nreturn 0;\r\n}<\/pre>\n<p>The output of the above code looks something like this:<\/p>\n<pre>1 31\r\n\r\n2 29\r\n\r\n3 0\r\n\r\n4 0\r\n\r\n5 31\r\n\r\n6 30\r\n\r\n7 31\r\n\r\n8 0\r\n\r\n9 0\r\n\r\n10 0\r\n\r\n11 0\r\n\r\n12 0<\/pre>\n<p>There are a few interesting things to note about the output.<\/p>\n<p>First, if the code follows a designated initializer with more values, like the sequence [4] = 31, 30, 31, these values are used to initialize the subsequent elements. In other words, after initializing days[4] to 31, the code initializes days[5] and days[6] to 30 and 31, respectively.<\/p>\n<p>Second, if the code initializes a certain element to a value more than once, the last initialization is the one that wins. For example, the start of the initialization list initializes days[1] to 28, but the last initialization [1] = 29 overrides it later, so the output is 29, not 28.<\/p>\n<p>Finally, the rest of the elements are automatically set to 0.<\/p>\n<p>Before we move on, I have a word of warning for all Arduino and C++ enthusiasts.<\/p>\n<p><strong><em>Neither C++ nor the Arduino IDE support this as of the time of this writing<\/em><\/strong>.<\/p>\n<p>However, C PIC programmers should be safe.<\/p>\n<h3 style=\"text-align: center;\">Become the Maker you were born to be. Try <a href=\"https:\/\/learnarduinonow.com\">Arduino Academy<\/a> for FREE!<\/h3>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-4238\" src=\"https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2.png\" alt=\"\" width=\"339\" height=\"129\" srcset=\"https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2.png 828w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2-300x114.png 300w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2-150x57.png 150w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2-768x292.png 768w\" sizes=\"(max-width: 339px) 100vw, 339px\" \/><\/p>\n<h2><strong>Multidimensional Arrays in C<br \/>\n<\/strong><\/h2>\n<p>Pretend for a moment that you want to make a home-brew weather station. You\u2019re an ambitious person and in this for the long haul, so you decide to track monthly rainfall over a period of five years.<\/p>\n<p>First, you think about using an array with 60 elements, but perhaps it\u2019s more elegant (and smart) if you keep each year’s data separate. Another alternative is to use five arrays, each with 12 elements, but that is clumsy and could get really nutso if you decide to track 20 years’ worth of rainfall (remember, you\u2019re in this for the long haul).<\/p>\n<p>The smarter, slicker approach is to use an array of arrays. The master array would have five elements, one for each year. Each of those elements, in turn, would be a 12-element array — one for each month. Here is how to declare such an array:<\/p>\n<pre>float rain[5][12]; \/* array of 5 arrays of 12 floats *\/<\/pre>\n<p>So how do we interpret this?<\/p>\n<p>One way to do so is to first look at the inner portion (the [5] part). It tells us that rain[] is an array with five elements. But what the heck are those elements?<\/p>\n<p>Now have a peek at the remaining part of the declaration (the [12] part). This tells us that each element is of type float[12], that is, each of the five elements of rain[] is, in itself, an array of 12 floats.<\/p>\n<p>Toward that end, rain[0], being the first element of rain[], is an array of 12 values. So are rain[1], rain[2], etc. So, if rain[0] is an array, its first element is rain[0][0], its second element is rain[0][1] and so on. In short, rain[] is a five-element array of 12-element arrays of floats, rain[0] is an array of 12 floats, and rain[0][0] is a float.<\/p>\n<p>To access, say, the value in row 3, column 4, use rain[3][4] (Remember, array indexing starts at 0, so row 3 is the fourth row, with row 0 being the first row).<\/p>\n<p>If this is confusing (which is was to me when I first learned about multidimensional arrays) take a look at figure 2.<\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-3838 size-full\" src=\"http:\/\/www.circuitcrush.com\/wp-content\/uploads\/Multidimensional-Arrays-in-C.jpg\" alt=\"Multidimensional-Arrays-in-C\" width=\"553\" height=\"264\" srcset=\"https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Multidimensional-Arrays-in-C.jpg 553w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Multidimensional-Arrays-in-C-300x143.jpg 300w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Multidimensional-Arrays-in-C-150x72.jpg 150w\" sizes=\"(max-width: 553px) 100vw, 553px\" \/><\/p>\n<p> <\/p>\n<p><strong><em>Figure 2: You can visualize this array as a two-dimensional array consisting of five rows, each of 12 columns. By changing the second subscript, you move along a row, month by month. By changing the first subscript, you move vertically along a column, year by year.<\/em><\/strong><\/p>\n<p>Remember, internally, this array is stored sequentially in memory, beginning with the first 12-element array, followed by the second 12-element array, and so on.<\/p>\n<p>Everything we know about two-dimensional arrays applies to three-dimensional arrays and above, though I don\u2019t recommend going more than three dimensions as it becomes unwieldy after that.<\/p>\n<p>You can declare a three-dimensional array this way:<\/p>\n<pre>int three_dee[10][15][20];<\/pre>\n<p>To aid in visualization, think of a one-dimensional array as a row of data, a two-dimensional array as a table of data, and a three-dimensional array as a stack of data tables. For example, you can visualize the three-dee[] array as 10 two-dimensional arrays (each 15×20) stacked atop each other.<\/p>\n<p>The other way to think of three-dee[] is as an array of arrays of arrays. So, it is a 10-element array, each element of which is a 15-element array. Each 15-element array then has elements that are 20-element arrays. Or, you can simply think of arrays in terms of the number of indices needed.<\/p>\n<h2><strong>How to Initialize a Multidimensional Array<br \/>\n<\/strong><\/h2>\n<p>Initializing a two-dimensional array builds on the technique for initializing a one-dimensional array.<\/p>\n<p>We\u2019ll stick with two dimensions for the purposes of demonstration and clarity. Going back to our rain tracking example, suppose we already have five years\u2019 worth of rainfall data we want to load into the program. In this case, we need to initialize our two-dimensional array rain[] with the data we have. To do so, we need to do something like this:<\/p>\n<pre>const float rain[12][5] =\r\n\r\n{\r\n {4.3, 5.3, 6.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6}, \/*rainfall data year 1*\/\r\n \u00a0\u00a0\u00a0 {6.5, 8.5, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3},\u00a0 \/*rainfall data year 2*\/\r\n \u00a0\u00a0\u00a0 {9.1, 7.5, 6.7, 4.3, 3.1, 0.8, 0.2, 1.2, 1.1, 2.5, 6.1, 8.4},\u00a0 \/*rainfall data year 3*\/\r\n \u00a0\u00a0\u00a0 {5.2, 9.9, 6.4, 3.3, 1.2, 2.8, 0.4, 0.0, 0.6, 1.6, 5.3 ,6.2},\u00a0 \/*you get it now*\/\r\n \u00a0\u00a0\u00a0 {1.6, 5.7, 6.8, 3.4, 3.5, 1.2, 0.9, 0.4, 1.6, 1.6, 3.6, 7.2}\r\n};<\/pre>\n<p>A few notes on initializing multidimensional arrays are in order.<\/p>\n<p>First, since the array holds data that should not be modified, we\u2019re using the const modifier when declaring the array. After all, these values represent rain fall from the past and we\u2019re not going to travel back in time and change the weather.<\/p>\n<p>Second, the initialization uses five lists of numbers, each of which are enclosed by braces. All five lists are enclosed by one outer set of braces. You could omit the interior braces and just retain the two outermost braces. As long as you have the right number of entries, the effect is the same. However, this tends to be confusing, especially if you come back later to modify the program, so I don\u2019t recommend doing this.<\/p>\n<p>The data in the first interior set of braces is assigned to the first row of the array, the data in the second interior set goes to the second row, and so on.<\/p>\n<p>Finally, the rules about mismatches between data and array sizes apply to each row (see <a href=\"https:\/\/www.circuitcrush.com\/c-programming-tutorial-6-arrays-intro\/\" target=\"_blank\" rel=\"noopener noreferrer\">C Programming Tutorial 6<\/a> for a review on this). That is, if the first inner set of braces encloses 10 numbers, only the first 10 elements of the first row are affected. The last two elements in that row are then initialized by default to zero. If there are too many numbers, it is an error; the numbers do not move to the next row.<\/p>\n<h2><strong>An Array of Information<br \/>\n<\/strong><\/h2>\n<p>This wraps up our treatment of arrays in C programming for now.<\/p>\n<p>You\u2019ll see and use arrays a lot if you do any C programming, program microcontrollers, or are an Arduino enthusiast. Don\u2019t be afraid of them and don\u2019t forget to pair them with your <em>for<\/em> loops! The two are a perfect match for each other.<\/p>\n<p>Drop me a comment and let me know what you thought of this tutorial. Or, tell me about your latest C programming or microcontroller-driven project. I love to hear about that stuff.<\/p>\n<p>Until next time, keep making!<\/p>\n<h2 style=\"text-align: center;\">Become the Maker you were born to be. Try <a href=\"https:\/\/learnarduinonow.com\">Arduino Academy<\/a> for FREE!<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4238\" src=\"https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2.png\" alt=\"\" width=\"533\" height=\"203\" srcset=\"https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2.png 828w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2-300x114.png 300w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2-150x57.png 150w, https:\/\/www.circuitcrush.com\/wp-content\/uploads\/FB_Cover2-768x292.png 768w\" sizes=\"(max-width: 533px) 100vw, 533px\" \/><\/p>\n<a target=\"_blank\" href=\"https:\/\/www.drpeterscode.com\/index.php\"><img src=\"https:\/\/www.circuitcrush.com\/wp-content\/plugins\/dpabottomofpostpage\/apixel1x1.jpg\" ><\/a><table><\/table>","protected":false},"excerpt":{"rendered":"<p>Welcome to C Programming Tutorial 7, Arrays in C Part 2! C Tutorial 6 was an introduction to arrays in C. This time, we\u2019re going to go into a little bit more detail about arrays after a quick review. Let\u2019s do this!<\/p>\n","protected":false},"author":1,"featured_media":3845,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[118],"tags":[116],"class_list":{"0":"post-3837","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-c-programming","8":"tag-c-programming","9":"entry"},"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/www.circuitcrush.com\/wp-content\/uploads\/Arrays-in-C-Part-2.jpg","_links":{"self":[{"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/posts\/3837","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/comments?post=3837"}],"version-history":[{"count":10,"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/posts\/3837\/revisions"}],"predecessor-version":[{"id":4257,"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/posts\/3837\/revisions\/4257"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/media\/3845"}],"wp:attachment":[{"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/media?parent=3837"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/categories?post=3837"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.circuitcrush.com\/wp-json\/wp\/v2\/tags?post=3837"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}