Solution for Exercise 12-7

ex1207

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

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

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

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

Output

The square root of 10 is 3.16
The square root of 12 is 3.46
The square root of 14 is 3.74
The square root of 15 is 3.87
The square root of 16 is 4.00
The square root of 18 is 4.24
The square root of 20 is 4.47

Notes

*Collect some For Dummies bonus points if you used a constant to set the size of the array and looping values, as shown at Line 6.

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

* Line 8 is in response to the second task: Create an empty array of 7 values. Because of the third task, this 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 warning. It may do so in higher-level languages, but not in C.

* Lines 11 and 12 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 14 and 15 output the results, again using a for loop. If your code just spits out the values, that'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.