Programming in C

(Barry) #1

118 Chapter 7 Working with Arrays


the number of responses in the list, set up the program so that the value 999 can
be keyed in by the user to indicate that the last response has been entered. (Hint:
You can use the breakstatement here if you want to exit your loop.)


  1. Write a program that calculates the average of an array of 10 floating-point values.

  2. What output do you expect from the following program?
    #include <stdio.h>


int main (void)
{
int numbers[10] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int i, j;

for ( j = 0; j < 10; ++j )
for ( i = 0; i < j; ++i )
numbers[j] += numbers[i];

for ( j = 0; j < 10; ++j )
printf ("%i ", numbers[j]);

printf ("\n");

return 0;
}


  1. You don’t need to use an array to generate Fibonacci numbers.You can simply use
    three variables: two to store the previous two Fibonacci numbers and one to store
    the current one. Rewrite Program 7.3 so that arrays are not used. Because you’re
    no longer using an array, you need to display each Fibonacci number as you gen-
    erate it.

  2. Prime numbers can also be generated by an algorithm known as the Sieve of
    Erastosthenes.The algorithm for this procedure is presented here.Write a program
    that implements this algorithm. Have the program find all prime numbers up to n
    = 150.What can you say about this algorithm as compared to the ones used in the
    text for calculating prime numbers?
    Sieve of Erastosthenes Algorithm
    To Display All Prime Numbers Between 1 and n
    Step 1: Define an array of integers P. Set all elements Pito 0, 2 <= i<= n.
    Step 2: Set ito 2.
    Step 3: If i> n,the algorithm terminates.
    Step 4: If Piis 0, then iis prime.
    Step 5: For all positive integer values of j, such that ix j≤n, set Pixjto 1.
    Step 6: Add 1 to iand go to step 3.

Free download pdf