Programming in C

(Barry) #1
Exercises 163

represents a quadratic equation where a= 4,b= –17, and c= –15.The values of x
that satisfy a particular quadratic equation, known as the rootsof the equation, can
be calculated by substituting the values of a,b,and cinto the following two
formulas:
If the value of b^2 –4ac, called the discriminant, is less than zero, the roots of the
equation,x 1 and x 2 ,are imaginary numbers.
Write a program to solve a quadratic equation.The program should allow
the user to enter the values for a,b,and c. If the discriminant is less than
zero, a message should be displayed that the roots are imaginary; otherwise,
the program should then proceed to calculate and display the two roots of
the equation. (Note:Be certain to make use of the squareRootfunction that
you developed in this chapter.)


  1. The least common multiple (lcm) of two positive integers uand vis the smallest
    positive integer that is evenly divisible by both uand v.Thus, the lcmof 15 and 10,
    written lcm(15, 10), is 30 because 30 is the smallest integer divisible by both 15
    and 10.Write a function lcmthat takes two integer arguments and returns their
    lcm.The lcmfunction should calculate the least common multiple by calling the
    gcdfunction from Program 8.6 in accordance with the following identity:
    lcm (u, v) = uv / gcd (u, v) u, v >= 0

  2. Write a function primethat returns 1 if its argument is a prime number and
    returns 0 otherwise.

  3. Write a function called arraySumthat takes two arguments: an integer array and
    the number of elements in the array. Have the function return as its result the sum
    of the elements in the array.

  4. A matrix Mwith irows,jcolumns can be transposedinto a matrix Nhaving jrows
    and icolumns by simply setting the value of Na,bequal to the value of Mb, afor all
    relevant values of aand b.
    a. Write a function transposeMatrixthat takes as an argument a 4 x 5 matrix
    and a 5 x 4 matrix. Have the function transpose the 4 x 5 matrix and store
    the results in the 5 x 4 matrix. Also write a mainroutine to test the function.
    b. Using variable-length arrays, rewrite the transposeMatrixfunction devel-
    oped in exercise 12a to take the number of rows and columns as arguments,
    and to transpose the matrix of the specified dimensions.

  5. Modify the sortfunction from Program 8.12 to take a third argument indicating
    whether the array is to be sorted in ascending or descending order.Then modify
    the sortalgorithm to correctly sort the array into the indicated order.

  6. Rewrite the functions developed in the last four exercises to use global variables
    instead of arguments. For example, the preceding exercise should now sort a glob-
    ally defined array.

Free download pdf