Solution for Exercise 12-7

ex1207

#include <stdio.h>
#include <math.h>

int main()
{
    int first[] = { 10, 12, 14, 15, 16, 18, 20 };
    float second[7];
    int x;

    for(x=0;x<7;x++)
        second[x] = sqrt(first[x]);

    for(x=0;x<7;x++)
        printf("The square root of %d is %.2f\n",first[x],second[x]);
    return(0);
}

Notes

* Line 6 is in response to the first task of this exercise: Create an array with the 7 named values.

* Line 7 is in response to the second task: Create an empty array of 7 values. Because of the third task, that array is created as a float. That's something you either figure out the first time you ran the code with the sqrt() function and saw what would not probably be the actual square roots of the values (as they're all integers).

* By the way, eating the return value from sqrt() as an int (instead of a float) doesn't generate a compiler error or warning. It may in higher-level languages, but not in C. Of course, the values stored aren't accurate, which is probably your biggest clue.

* Lines 10 and 11 are in response to the third task: Fill the second array with the square root of each value in the first array. I used a for loop in line 10. Line 11 uses the sqrt() function, which requires the math.h header file be included, Line 2.

* Lines 13 and 14 displays the results, again using a for loop at Line 13. Line 14 is my method of displaying the results; if you just spit out the values, that would be okay. It wouldn't be the best way to display the results, but it's okay.

* Yes it's possible to solve this Exercise without using two loops. I'm not sure what I was trying to do with separate for loops, but as I look at the code now it does seem kind of redundant.