Algorithms / C Programming

Practice

Exercises in this Practice include Algorithms Design practice (Ex.A1 - A6) and C Programming practice (Ex.C1 - C8), and appear as they are listed in the Course A Schedule.

1. List seven steps in a program development.
2. Formulate the Structure Theorem.
3. Define the three basic control structures.
4. Define the following terms:
• Top-down development.
• Refinement of the algorithm.
• Sentinel value.
• Compound statement.
• Change the pseudocode in Example 2 in such a way that the numbers are added from zero up to the MAX.
• Make the corresponding changes to the flowchart.
• Write an algorithm (in pseudocode and using a flowchart) that will receive two integers from a keyboard, and calculate and print their sum, difference, product and quotient.
• Modify the previous algorithm to terminate the program if division by zero occurs.
• Modify the previous algorithm in such a way that a message "The first number is larger than the second number" is printed if the difference is positive, and a message "The second number is larger than the first number" is printed otherwise.
• Formulate a problem, the algorithm for which is shown here.
• Write a pseudocode for this algorithm.

1. Create flowcharts for each of the following:

1. Obtain two numbers from the keyboard, and determine and display which (if either) is the larger of the two numbers.
2. Obtain three non-zero integers from the keyboard, and determine and print if they could be the sides of a right triangle.
3. Read an integer value from the keyboard and display a message indicating if this number is odd or even.
4. read 10 integers from the keyboard in the range 0 - 100, and count how many of them are larger than 50, and display this result

2. In the following problems you will need to:

1. Define the problem by specifying input, output and processing involved;
2. Design a solution algorithm using pseudocode;
3. Draw a flowcharts of the solution;
4. Desk check the solution algorithm using two valid test cases.

2.1 Write an algorithm that will repeatedly

• ask a user to enter a non-zero integer,
• read the number from the keyboard,
• double it,
• subtract 7 from it
• display the final number to the screen,
• terminate the program if a sentinel value is entered.

What is the best choice of the sentinel value in this case? Explain.

2.2 Write an algorithm to read and display a customer account balance at the end of a month.

• Read in from the keyboard the following data:
• The account balance at the beginning of the month;
• A total of all withdrawals for the month;
• A total of all deposits made during this month;

A federal tax charge of 1% is applied to all transactions made during the month.

• Calculate the account balance at the end of the month:
• subtract the total withdrawals from the account balance at the beginning of the month.
• Add the total deposits to the new balance.
• Calculate the federal tax(1% of total transactions, that is total withdrawals plus total deposits.)
• Subtract the tax form the new balance.
• Print the end-of-month balance.

Each time you modify the program, you should compile it, run it and record the output.

1. Compile and run Program 1.
2. Omit the return 0; statement at the end and compile again. Record the compiler message.
3. Put back the return statement and delete the int in front of main. Did the compiler complain?
4. Add \n after the word "first" in the sentence "This is my first C program".
5. Add \n after each word.
6. Remove all \n and add \t after each word.
7. Add another sentence within the same printf function: "C programming is fun!". Change the program in such a way that these two sentences are printed (a) in one line; (b) in two lines; (c) in two columns:
```
This is my first    C programming
C program.          is fun!
```
8. Write compile and run a program that rings a bell after displaying the message on the screen: "Now I will ring the bell!"
9. Write, compile and run a program that prints an English alphabet as 5 x 5 table + 1 character. Use double tab between columns and double space between rows.

1. Give the proper names and write definitions using the #define directive of the following constants:
24 hours a day, 366 days in a leap year, 25 students in a group.
2. Which of the following are valid function names? Explain.
• 2int_multiply
• multiply_2int
• Room_Size
• *Loop
• _Loop
3. Evaluate the following expressions if i = 7, n = 12, m = 3:
• n / m + i * 5 % 3
• (n + m) % i - 1
• n + m % i
• i % 5 + (n - m)
• i % (5 + n) - m
4. Find and correct errors in the following function definition:
```	int 3_int_add(int n1, int n2 int n3)
{
int sum;
sum = n1 + n2 + n3;
return sum
}
```
5. Write, compile and run a program that calculates and prints the sum of 3 integers. Use the corrected function from the previous question. Look at Program 2 to find out how to print an integer variable.
6. Modify the program in question E to include the multiply_int() function. Declare and initialise 3 integers in the main() function. Calculate and print their sum and results of all possible multiplications in a tabular form. Use \t and \n escape characters. The output of the program should look like this:
```    The numbers are: 3, 7, 11.
3 + 7 + 11 = 21.

Multiplication results:

|   3   7   11
--------------------
3   |   9   21  33
7   |   21  49  77
11  |   33  77  121

```
1. Let int n = 125; int m = 100;
Name the type of the result for each of the following arithmetic operations.
• n + m
• n + m + 25.5
• n/m
2. If x is float, and n and m are from question A, what are the results of the following arithmetic operations?
• x = n / m;
• x =(float) n / m;
• x = (float)(n / m);

3. Write the following numbers in scientific notation:
• 4600
• 0.00037
• - 0.00037
• 25.00
4. Write, compile and run the following programs:
1. A program that prints ASCII codes for all uppercase and lowercase letters.
Print the results in a tabulated form. Use the following while statement for the uppercase:
```	c = 'A';
while (c <='Z')
{
...	/* print characters and corresponding
numeric values in tabular format */
c = c + 1;
}
```

Replace 'A' and 'Z' with 'a' and 'z' for the lowercase letters.

2. A program that prints the numeric values of the escape characters '\n' and '\t'.
3. A program that prints the characters with ASCII codes from 48 to 57.

• What is the difference between getc() and getchar() functions?
• What does the scanf() function return?
• What format specifier is used in the printf() function to output (a) a floating-point number, (b) a character, (c) an integer?
• What does the address of a variable mean?
• Within %8.4f, which part is the minimum field width specifier, and which one is the precision specifier?
• What header file has to be included in the program that uses mathematical functions?
• What is the advantage of using the time(NULL) function as an argument of the srand()?
2. For the next 2 questions use the ASCII codes table from Exercise C3(D).

3. Write printf() statements which result in the following outputs
of the variables int n1=87 and int n2=115:
4. ```	1.	87, 115
2.	0087, 0115.00
3.	87.000
115
4.	W, s
5.	s
W
```

5. Write a program that reads your first name in lowercase letters from the screen using getc() or getchar() function, for example sam, and prints into the screen in the uppercase letters with a space between letters.: "S A M ".Hint: think about locations of the uppercase and lowercase letters in the ASCII table.
6. Write a program that reads 3 integers from the keyboard and then calculates their sum and all possible products using two functions you defined in Exercise C2(F)
7. Modify the program above in such a way that it generates 3 random integers instead of reading them from the keyboard..
8. Modify Program 4.3 to use the given code fragment to generate the coordinates of two points as random floating-point numbers in the range
[-100.0, 99.9]
9. Write a program that generates three random integer numbers in the range [0 90] that represent angles in degrees. Calculate the corresponding angles in radians and print the results of all trigonometrical functions of these angles in a tabular format. The output may look like this (note the left alignment and five decimal places)
 ==================================================== degrees radians sin() cos() tan() ==================================================== 15 0.26179 0.25881 0.96592 0.26794 30 0.52359 0.50000 0.86602 0.57735 88 1.53588 0.99939 0.03490 28.63564 ====================================================
• What is the difference between unary and binary operators?
• What type of variable do the relational operators return?
• List all the arithmetic assignment operators and the equivalent expressions
• Write 4 different statements that result in incrementing the value of x by 1.
• Explain the difference between prefix and postfix increment and decrement operators.
2. If int a = 3, int b = 11 and int c = 0, evaluate the expression given in the tutorial.
3. For the same values of a, b, and c evaluate the following expressions:
• a + c < b
• a % 5 == c
• (a - b) <= c
• (a - b) > 0 && a > c
• (a - b) > 0 || a > c
• (a = 1) && (b = 1)
• a && c
4. Copy, compile and run Program 5.3. Then modify this program to check your answers to the questions B and C.
5. For each of the logical operators state clearly in which cases it returns 1, and in which cases 0.
6. If a, b, and c represent the sides of a triangle, write a boolean expression which is evaluated to 1 if this is a right-angle triangle, and to 0 otherwise.
7. If a, b, and c are the coefficients of a quadratic equation, write a boolean expression that returns 1 if the discriminant of this equation, (b^2 - 4ac), is positive, and 0 if it is negative.

1. For the EXAMPLE 4

1. Draw a flowchart for the "swap" module.
2. Draw a flowchart for the complete algorithm.

Construct a solution algorithm for the following programming problems.
Your solution should contain: a defining diagram, a pseudocode algorithm, and a desk check of the algorithm.

2.  Design an algorithm that simulates a simple calculator.

• Read two numbers from the keyboard
• Display the menu options as follows:
• 1 - computes the sum of two numbers.
• 2 - computes the difference (first minus second).
• 3 - computes the product of the two numbers.
• 4 - if the second number is not zero, computes the quotient (first divided by second).
• 5 - terminates the program
• If the code is not equal to 1,2,3,4 or 5 - displays an error message.

The program is then to display the two numbers, the integer code and the computed result to the screen. Use CASE structure in this algorithm.

3.  Design an algorithm that prompts an operator for a student's number and the student's exam mark out of 100. Your program is then to match the exam mark to a letter grade and print the grade to the screen. Calculate the letter grade as follows:

80 - 100 H
70 - 80 D
60 - 70 C
50 - 60 P
below 50 N

4.  Design an algorithm that receives a date in the format dd/mm/yyyy (for instance, 20/02/2001) and validates it as follows:

• The month must be in the range 1 - 12.
• The day must be in the range 1 - 31 and acceptable for the corresponding month. (Don't forget a leap year check for February).

1. Write a C program that implements an algorithm designed in the exercise A3.3. Validate a user's input. If the mark entered is negative or larger then 100, give an error message and exit the program.
2. Design a program that generates 3 floating-point numbers in the range [-10.00 10.00] and solves the quadratic equation with coefficients given by these numbers. See the detailed solution in Quadratic.pdf. Format the results to 3 decimal places.
3. Design a program that reads three floating-point numbers from the standard input, and checks if these numbers can represent the sides of a triangle. If the answer is 'yes', the program then decides if this is a right-angle triangle. Finally, the program prints the report. The output may look like the following.

```
3.0 4.0 5.0
You entered the numbers: 3.00, 4.00, 5.00.
These numbers can form a triangle.
This is a right-angle triangle.
```
4. Write a C program that simulates a simple calculator. Implement an algorithm designed in the Exercise A3.2. Use a switch - case statement to perform calculations or to exit the program.

1. Formulate the difference between WHILE and DO-WHILE control structures. Give examples when the use of a particular repetition structure is desirable.
2. Draw a flowchart of the algorithm designed in Example 5 (see Repetition Control Structures) and perform a desk check.
3. In Example 5 set counter = 1 before the first WHILE statement instead of inside the WHILE statement. Explain how this change affects the logic of the program.
4. Perform a desk check of the program modified in (3) above if the user enters three numbers for times-tables, 5, 6, and 7. What is the program's output?

Construct a solution algorithm for the following programming problems.
Your solution should contain: a defining diagram, a pseudocode algorithm, and a desk check of the algorithm.

5. Write a fragment of a program that adds all odd numbers from 1 to 100 and displays the result.

6. Write a program that continuously prints multiplication tables from 1 to 10 with a double-space interval after each table.

7. Modify the program in Exercise A3, question 3, in such a way that it reads students' names and exam marks from the keyboard until a sentinel value is entered, and calculates the number of students who have passed their exam (has grades H, D, C or P), the number of students who have failed (grade N), and prints and displays the report.

8. Modify the previous program to calculate a class average mark and display it together with the other information.

1. Design a program that continuously generates the random integer number n in the range [1, 10] and calculates and prints the n-factorial (n!). The factorial of a positive number n is equal to the product of the positive integers from 1 to n. The program terminates if the user presses 'Q' or 'q' (for 'quit') on the keyboard.
2. Write a C program that continuously generates a random number and checks and reports if this number is prime or not. Use the remainder operator %. NOTE: N is prime if N%M = 0 only if M=N. Include an option to continue or to terminate the program.
3. Design and implement a program that plays the HIGH-LOW guessing game with numbers between 1 and 100. The program should pick a random number and then repeatedly prompt the user to guess the number. After each guess, it should give an appropriate response (e.g. High or Low) to the user. Continue accepting guesses until the game is over or the user enters an appropriate sentinel value to quit. Report the number of guesses the user made.
4. Write a program that neatly prints a table of powers using a repetition structure. The first few lines of the table might look like this:

::::  A  TABLE  OF  POWERS  ::::

IntegerSquare3rd power4th power5th power
11111
2481632
392781243

Etc.

Write your own function to calculate an integer power of a number (x^n). Do not use the math library function pow().

1.a Discuss various ways to load data into an array. State under what conditions a particular way is preferable. Give examples, other than in the Tutorial.

1.b You have been given an array of integer values: {34, 58, 4, 23, 12, 6, 0}. Implement a Bubble sort algorithm. Write the array elements after each completed internal loop. How many swaps are performed?

2. In the following programming problems assume that you have been given an array of floating point values which is called Numbers[]. It has MAX_NUMBER elements. The array has already been loaded with values.

Write a pseudocode and draw flowcharts for each of the following:

1. Find the sum of the elements of the array.
2. Find the mean (average) of the elements of the array.
3. Find the largest of the elements of the array.
4. Find the range of the elements of the array.

3. Combine the fragments of pseudocode from question 2 into one program that generates random integer values in the range [10, 100], load them into the array and process as above. Perform a desk check for the solution.

4. Construct a solution algorithm for the following programming problems. Your solution should contain:

• a defining diagram(inputs, processes, outputs),
• a list of control structures required,
• a pseudocode algorithm, and
• a desk check of the algorithm.
1. Design an algorithm that will prompt for and receive 10 integers from the keyboard, and count the number of integers whose value is less than the average value of the integers. Your program is to display the average integer value and the count of integers less than the average.
2. Design an algorithm that will prompt for and receive an employee number from an operator at a terminal. Your program is to search an array of the valid employee numbers to check that the employee number is valid, look up a parallel array to retrieve the employee's salary, and display the number and the salary on the screen. If the employee number is not valid, an error message must be displayed.

• Explain the difference between the "passing parameter by value" and "passing by reference"
• Write a function void change_value(int value) that takes an integer as a parameter and assigns to it a value which is its original value multiplied by 5.
• Write a program that declares an integer variable n, prints its value, calls the function change_value(n) and prints the value n after that. Did the value change? Discuss the results.
1. Write functions which have the following prototypes and then write small programs to test each of the functions.

1. void print_table(int array[], int size, int columns)
this function prints all elements of the given array as a table with given numbers of columns.
2. double mean_value(int array[], int size)
this function calculates and returns the mean (average) value of all elements in the given array.
3. int search_array(int array[], int size, int target)
this function searches the given array for the target (parameter passed to it) and returns an index at which the number found in the array or -1 if the number is not found. For example, if int array = {2, 5, 7, 3, 8}, the function call search_array(array, 7) returns 2, the function call search_array(array, 4)returns -1, etc.
4. int max_value (int array[], int size)
this function finds the largest integer in a given array of integers and returns it.
5. Modify the function in (d) to return the smallest value in the array int min_value (int array[], int size)
6. void squares_array(int array[], int new_array[], int size)
this function reads the elements of the given array, calculates squares of each element and assigns the values to the elements of a new_array.

2. Write a program to perform the following tasks:

• Generate 20 random numbers, each of which is between 10 and 100 inclusive.
• Stores the number in an array only if it is not a duplicate of any number already generated.
• Displays the array of 20 integer numbers that has no duplicates as a table 4X5.

1. List six steps in the top-down modular design of a solution algorithm.
2. Give the definition of a programming module.
3. What is a hierarchy chart?. Give examples. Does a hierarchy chart indicate the program control flow?
4. What is the difference between global and local variables?.
5. Identify all global and local variables in Example 11
6. In which cases would you pass parameters to a module?
7. What does the keyword return mean in the content of module definition?
1. Construct a solution algorithm for the following programming problems. Use top-down modular design. State clearly tasks that are to be performed by each module. Write a pseudocode of the mainline and all modules.

1. Design a program that prompts and receives a nonnegative integer n and then calculates and displays on the screen the following:
• The factorial of this number n!, where n-factoriaL is the product of all numbers from the given number to 1:
n! = n*(n-1)*(n-2)*(n-3)*...*3*2*1.
• Sum of all numbers from 1 to the given number.
• Sum of all odd numbers from 1 to the given number.
Each task must be defined in a module, that takes the number as a parameter and returns the result.
2. Design a program that performs the following tasks:
• Prompts and receives three numbers,
• Checks if these numbers can form a triangle,
• Checks if this is a right angle triangle,
• Calculates the perimeter of the triangle,
• Calculates the area of the triangle,
• Displays the results of all calculations,
• Displays an error message and exits the program if the numbers are not valid sides of a triangle.
• Each task must be defined in a module, that takes the number as a parameter and returns the result.
3. Write two C programs to implement all the algorithms designed in A6.2(A, B). Each programming module should be implemented in a C function. Write each program as a project using DEV - C++ compiler. See instruction in How to use Dev-C++.