You are here

Example 4.7

9 October, 2015 - 14:47

Using a while loop, calculate y =\textrm{ cos} (x) for -\pi \leq x\leq \pi using an increment of  \frac{\pi }{4} .

This time we need to initialize the x value outside the loop and then state the test condition in the first line of the while loop. We also need to create an increment statement within the while loop:

x=-pi;
    while x<=pi
        y=cos(x);
        fprintf('%8.3f %8.2f nn',x,y);
        x = x + (pi/4);
end

The result is the same as that of the previous example:

-3.142      -1.00
-2.356      -0.71
-1.571       0.00
-0.785       0.71
0.000        1.00
0.785        0.71
1.571        0.00
2.356       -0.71
3.142       -1.00

Now we can improve the code by adding extra formatting lines and comments:

clear; clc;
fprintf(' x cos(x)nn') % title row
fprintf(' ----------------nn') % title row
x=-pi; % initiating the x value
while x<=pi % stating the test condition
    y=cos(x); % calculating the value of y
    fprintf('%8.3f %8.2f nn',x,y); % printing a and y
    x = x + (pi/4); % iterating to the next step
end

The result should look the same as before.

x           cos(x)
----------------
-3.142      -1.00
-2.356      -0.71
-1.571       0.00
-0.785       0.71
0.000        1.00
0.785        0.71
1.571        0.00
2.356       -0.71
3.142       -1.00