Introduction to Computers and Programming: Section1

Midterm 2

November 14, 2001

Instructor: Avi Rosenfeld

1. (25 points) Write a program to a sequence of letters until the period is hit.  Have the program display how many upper case letters, lower case letters, and numbers were in the sequence.  You may use the following functions from ctype.h (but you don’t have to):

int isupper(char);

int islower(char);

int isalnum(char);

int isdigit(char);

For extra credit, create the functions you used.


 

2. (25 points) Assume the following function has been made:

int RollDice();

which returns a random number between 1 – 6.

Write a function IsSnakeEyes that returns true if two 1’s were rolled consecutively, and false otherwise.

Write a program that rolls 100 pair of “dice” and says how many SnakeEyes were found.  The function prototype for the IsSnakeEyes is:

bool IsSnakeEyes();


 

3. (20 points) What will the following code display?  Why?

int sum = 0;

          for (int i = 2; i < 7; i++)

          {

                    for (int j = 2; j < i; j++)

                    {

                             if (i % j == 0)

                             {

                                       printf("%d %d\n", i, j);

                                       sum+=j;

                             }

                    }

 

          }

          printf("%d",sum);


 

4. (15 points) There are at least 5 errors in the code below.  Comments, formatting or lack thereof are not any of the errors. Identify the line numbers and the errors.  (For extra credit, find a 6th problem.)

 

1.     #include <stdio.h>

2.     /*This program uses the non-built in Power function which works for any whole power 1 or  greater*/

3.     int Power(int, int)

 

4.     int main()

5.     {

6.     int base, exp, answer;

7.     scanf("%d%d",base,exp);

8.     answer(Power(base,exp));

9.     printf("%d to the power of %d is %d", base, exp, answer);

10. }

 

11. int Power(int x, int y)

12. {

13. int sum = 1;

14. for (int i = 1; i <y; i++)

15.        sum*=x;

16. return sum,x,y;

17. }


5. (15 points) Write a function PrintTriangle which prints an inverted Right Triangle on the screen.  The function should take two parameters, the size, and the letter to make the triangle out of.  The function prototype is:

void PrintTriangle(int, char);

If you called the function with the parameters (6, ‘Q’), the function should print:

QQQQQQ

QQQQQ

QQQQ

QQQ

QQ

Q