20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

118 Chapter 7 Work<strong>in</strong>g with Arrays<br />

the number of responses <strong>in</strong> the list, set up the program so that the value 999 can<br />

be keyed <strong>in</strong> by the user to <strong>in</strong>dicate that the last response has been entered. (H<strong>in</strong>t:<br />

You can use the break statement here if you want to exit your loop.)<br />

4. Write a program that calculates the average of an array of 10 float<strong>in</strong>g-po<strong>in</strong>t values.<br />

5. What output do you expect from the follow<strong>in</strong>g program?<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t numbers[10] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };<br />

<strong>in</strong>t i, j;<br />

for ( j = 0; j < 10; ++j )<br />

for ( i = 0; i < j; ++i )<br />

numbers[j] += numbers[i];<br />

for ( j = 0; j < 10; ++j )<br />

pr<strong>in</strong>tf ("%i ", numbers[j]);<br />

pr<strong>in</strong>tf ("\n");<br />

}<br />

return 0;<br />

6. You don’t need to use an array to generate Fibonacci numbers.You can simply use<br />

three variables: two to store the previous two Fibonacci numbers and one to store<br />

the current one. Rewrite Program 7.3 so that arrays are not used. Because you’re<br />

no longer us<strong>in</strong>g an array, you need to display each Fibonacci number as you generate<br />

it.<br />

7. Prime numbers can also be generated by an algorithm known as the Sieve of<br />

Erastosthenes.The algorithm for this procedure is presented here.Write a program<br />

that implements this algorithm. Have the program f<strong>in</strong>d all prime numbers up to n<br />

= 150.What can you say about this algorithm as compared to the ones used <strong>in</strong> the<br />

text for calculat<strong>in</strong>g prime numbers?<br />

Sieve of Erastosthenes Algorithm<br />

To Display All Prime Numbers Between 1 and n<br />

Step 1: Def<strong>in</strong>e an array of <strong>in</strong>tegers P. Set all elements P i<br />

to 0, 2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!