{"id":5752,"date":"2023-02-18T00:01:35","date_gmt":"2023-02-18T08:01:35","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=5752"},"modified":"2023-02-11T18:12:42","modified_gmt":"2023-02-12T02:12:42","slug":"adding-values-from-two-arrays","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=5752","title":{"rendered":"Adding Values from Two Arrays"},"content":{"rendered":"<p>In <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5739\">last week&#8217;s Lesson<\/a>, I covered a function present in other programming languages but absent in C: concatenating arrays. This time, the topic is similar: adding two arrays. Yes, such functions exist in other languages, but in C you must write one yourself.<br \/>\n<!--more--><br \/>\nI&#8217;m unsure when it would be necessary to add values from two arrays &mdash; or to perform any other math on these values. I&#8217;ve never had the need, though I find such exercises challenging.<\/p>\n<p>The function&#8217;s goal is to swallow two arrays, adding sequential element values from each, then setting the results in a third array, which the function returns.<\/p>\n<p>For example, you start with these two arrays:<\/p>\n<p><code>int a[] = { 11, 22, 33, 44, 55 };<br \/>\nint b[] = { 89, 78, 67, 56, 45 };<\/code><\/p>\n<p>The function, call it <em>intarrayadd()<\/em>, swallows these two arrays &mdash; and their element count &mdash; then returns a new array with the totals:<\/p>\n<p><code>100 100 100 100 100<\/code><\/p>\n<p>As I ruminated on this topic, one thought immediately came to me: What if the arrays are of different sizes? Obviously, I didn&#8217;t want to truncate the result and lose data. So I figured I would do what happens in real life: If extra items are left over, they&#8217;re included in the result as-is. This rule implies that the array generated must be equal in its element count to the larger of the two arrays passed.<\/p>\n<p>Here is my array adding function, which works specifically with integer arrays:<\/p>\n<pre class=\"screen\">\r\n<span class=\"comments\">\/* concatenate two integer arrays *\/<\/span>\r\nint *intarrayadd(int *a, int asize, int *b, int bsize)\r\n{\r\n    int *c,larger,smaller,x;\r\n\r\n    <span class=\"comments\">\/* allocate for the larger array *\/<\/span>\r\n    larger = asize &gt; bsize ? asize : bsize;\r\n    <span class=\"comments\">\/* and get the smaller size as well *\/<\/span>\r\n    smaller = larger &gt; asize ? asize : bsize;\r\n\r\n    <span class=\"comments\">\/* allocate storage for new array *\/<\/span>\r\n    c = malloc( sizeof(int) * (larger) );\r\n\r\n    <span class=\"comments\">\/* add if the allocate in successfull *\/<\/span>\r\n    if( c!=NULL )\r\n    {\r\n        <span class=\"comments\">\/* copy up to the size of the\r\n           smaller array *\/<\/span>\r\n        for( x=0; x&lt;smaller; x++ )\r\n            *(c+x) = *(a+x) + *(b+x);\r\n\r\n        <span class=\"comments\">\/* just copy over the remaining values\r\n           from the larger array *\/<\/span>\r\n        if( asize==larger )\r\n        {\r\n            <span class=\"comments\">\/* use existing value of x *\/<\/span>\r\n            <span class=\"comments\">\/* array 'a' is larger *\/<\/span>\r\n            for( ; x&lt;larger; x++ )\r\n                *(c+x) = *(a+x);\r\n        }\r\n        else\r\n        {\r\n            <span class=\"comments\">\/* array 'b' is larger *\/<\/span>\r\n            for( ; x&lt;larger; x++ )\r\n                *(c+x) = *(b+x);\r\n        }\r\n    }\r\n\r\n    return(c);\r\n}<\/pre>\n<p>As with array concatenation, the <em>intarrayadd()<\/em> function is specific to the integer data type. Both arrays are passed, along with their sizes.<\/p>\n<p>Immediately, tests made to determine which array is larger and and which is smaller, assuming they&#8217;re of different sizes:<\/p>\n<p><code><span class=\"comments\">\/* allocate for the larger array *\/<\/span><br \/>\nlarger = asize &gt; bsize ? asize : bsize;<br \/>\n<span class=\"comments\">\/* and get the smaller size as well *\/<\/span><br \/>\nsmaller = larger &gt; asize ? asize : bsize;<\/code><\/p>\n<p>Storage is then allocated based on the size of the larger array:<\/p>\n<p><code>c = malloc( sizeof(int) * (larger) );<\/code><\/p>\n<p>Upon success, the values of the two arrays are added, stored in newly created array (buffer, actually) <code>c<\/code>:<\/p>\n<p><code>for( x=0; x&lt;smaller; x++ )<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;*(c+x) = *(a+x) + *(b+x);<\/code><\/p>\n<p>Depending on which array is larger, a second set of <em>for<\/em> loops copy over the remaining elements from the larger array into new array (buffer) <code>c<\/code>. If the arrays are identical in size, the value of variable <code>larger<\/code> is equal to variable <code>x<\/code>, so nothing is copied.<\/p>\n<p>The newly-created array is returned or, should memory allocation fail, <code>NULL<\/code> is returned.<\/p>\n<p>The <em>main()<\/em> function outputs both original arrays, then the newly-created array, returned from the <em>intarrayadd()<\/em> function. The larger array size must be calculated again in the <em>main()<\/em> function to ensure that all elements in the new array are output. Here is a test run:<\/p>\n<p><code>Array 'a': 11 22 33 44 55<br \/>\nArray 'b': 89 78 67 56 45 1 2 3<br \/>\nResult:  100 100 100 100 100 1 2 3<\/code><\/p>\n<p><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2023_02_18-Lesson.c\" rel=\"noopener\" target=\"_blank\">Click here<\/a> to view the full code on GitHub. Again, I don&#8217;t know when I would ever use such a function. My point is that although other programming languages have such functions in their libraries, in C you must code your own. I find such challenges engaging and fun.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Another array function absent in C is one that adds elements from two arrays, creating a third array. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5752\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-5752","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5752","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5752"}],"version-history":[{"count":3,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5752\/revisions"}],"predecessor-version":[{"id":5755,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5752\/revisions\/5755"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5752"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5752"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5752"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}