You are on page 1of 20

Al Imam Mohammad Ibn Saud Islamic University

College of Computer and Information Sciences


Computer Science Department

Homework

CS140 – Computer Programming 1

(last updated: January 2019)

Page 1 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Table of Contents
Note to students............................................................................................................. 4
Homework 01: Fundamentals of Java Programs, Input/Output, Variables, and
Arithmetic ...................................................................................................................... 5
Exercise 1 .............................................................................................................................. 5
Exercise 2 .............................................................................................................................. 5
Exercise 3 .............................................................................................................................. 6
Exercise 4 .............................................................................................................................. 6
Exercise 5 .............................................................................................................................. 6
Homework 02: Introduction to Problem Solving, Selection Control Statements &
Logical Operators .......................................................................................................... 7
Exercise 1 .............................................................................................................................. 7
Exercise 2 .............................................................................................................................. 7
Exercise 3 .............................................................................................................................. 7
Homework 03: Introduction to Problem Solving, Selection Control Statements &
Logical Operators .......................................................................................................... 8
Part 1: .................................................................................................................................... 8
Part 2: .................................................................................................................................... 8
Part 3: .................................................................................................................................... 8
Homework 04: Formulating Algorithms, Repetition Control Statements ................ 9
Exercise 1 .............................................................................................................................. 9
Exercise 2 .............................................................................................................................. 9
Problem (class ConsecutiveNumbers) ................................................................................ 9
Homework 05: Formulating Algorithms, Repetition Control Statements .............. 11
Exercise 1 ............................................................................................................................ 11
Exercise 2 ............................................................................................................................ 11
Exercise 3 ............................................................................................................................ 11
Exercise 4 ............................................................................................................................ 11
Problem (class SumNonDuplicates) .................................................................................. 11
Homework 06: Methods, Introduction to Recursion ................................................ 13
Exercise 1 ............................................................................................................................ 13
Exercise 2 ............................................................................................................................ 13
Exercise 3 ............................................................................................................................ 13
Exercise 4 ............................................................................................................................ 13
Exercise 5 ............................................................................................................................ 14
Homework 07: Methods, Introduction to Recursion ................................................ 15
Exercise 1 ............................................................................................................................ 15
Exercise 2 ............................................................................................................................ 15
Exercise 3 ............................................................................................................................ 15
Exercise 4 ............................................................................................................................ 16
Homework 08: Arrays ................................................................................................. 17
Problem (class MergeSalary) ............................................................................................. 17

Page 2 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 09: Arrays ................................................................................................. 18
Problem (class CheckSequence) ........................................................................................ 18
Homework 10: Strings ................................................................................................ 19
Exercise 1 (class NameSplitter) ......................................................................................... 19
Exercise 2 (class Hex2Dec)................................................................................................. 19
Exercise 3 (class CheckProtection).................................................................................... 20

Page 3 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Note to students
This homework exercises are prepared for students of the course CS140 – Computer
Programming 1.

To take benefit from these exercises, students must resolve them after the lecture and before
the tutorial session. This will help him to review the course practically and be prepared for the
tutorial and lab sessions.

No solution to the homework exercises is provided, so student may ask course or lab instructor
to explain the questions or even to resolve some of them if the time allow during the lecture or
during the office hours.

We are happy to have you among our students and we wish you a successful course with an
excellent level of learning and practicing.

Page 4 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 01: Fundamentals of Java Programs,
Input/Output, Variables, and Arithmetic

Exercise 1
Write an application that displays the numbers 1 to 4 on the same line, with each pair of
adjacent numbers separated by one space. Use the following techniques:
a) Use one System.out.println statement.
b) Use four System.out.print statements.
c) Use one System.out.printf statement.
What does the following code print?

d) System.out.printf( "%s\n%s\n%s\n", "*", "***", "*****" );

Exercise 2
Write a Java program that calculates and prints the subtraction of two integers: write
declarations, statements or comments that accomplish each of the following tasks:

a) Create a class named Subtraction.


b) State that a program will calculate the subtraction of an integer from another. (this is a
comment)
c) Create a Scanner called input that reads values from the standard input.
d) Declare the variables x, y and result to be of type int.
e) Prompt the user to enter the first integer.
f) Read the first integer from the user and store it in the variable x.
g) Prompt the user to enter the second integer.
h) Read the second integer from the user and store it in the variable y.
i) Compute the subtraction of y from x, and assign the result to the variable result.
j) Display the message "Difference is" followed by the value of the variable result.

Page 5 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Exercise 3
Write a Java program that computes the value of z where z=x2+2y+1 where x and y are given
by the user.

Exercise 4
State the order of evaluation of the operators in each of the following Java statements, and
show the value of x after each statement is performed:
a) x = b * ( c / b ) + c % b;
b) x = a - b / c * 10;

Exercise 5
Write a Java program that computes the sum of two rational numbers given by the user.
𝑎 𝑏
[Note: If two numbers are rational, then we can write them in the form 𝑥 and 𝑦, for some
integer values of a, b, x and y, and x and y cannot be zero.
𝑎 𝑏
Then their sum is: 𝑥
+𝑦

𝑎𝑦 𝑏𝑥
= 𝑥𝑦 + 𝑦𝑥

(𝑎𝑦+𝑏𝑥)
=
𝑥𝑦

Page 6 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 02: Introduction to Problem Solving,
Selection Control Statements & Logical Operators

Exercise 1
Write Java program that asks the user to enter an integer number than accomplish each of the
following tasks:
a) If the number is equal to 7, display "The variable number is equal to 7".
b) If the number is not equal to 7, display "The variable number is not equal to 7".
You have to resolve the exercise using if statement only.

Exercise 2
Write a Java program that determines whether a number n given by the user is a multiple of 5
or not.

Exercise 3
Write a Java program that determines whether a number n given by the user is outside the
range ]a, b[ or not where a and b are also given by the user in good order (a <= b).

Page 7 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 03: Introduction to Problem Solving,
Selection Control Statements & Logical Operators

Part 1:
• Write a Java program that presents to the users a choice of your 4 favorite beverages
(Water, Milk, Juice, and Coffee).
• Then allow the user to choose a beverage by entering a number from 1 to 4.
• Output the name of which beverage they chose. Use switch to display the choice.
• Modify the program so that if the user enters a choice other than 1,2,3, and 4 then it will
output "Invalid choice."

Part 2:
• Modify your program to make the user enter a quantity of the chosen drink. If the user
enters quantity outside of the range [1,5] then the program will output "Invalid
quantity."
• Knowing that drink prices are respectively: 1 SAR, 1.5 SAR, 2 SAR, and 1.75 SAR,
print the total amount that the user should pay.

Part 3:
• Modify your program to ask the user to enter the amount of money first.
• Then he makes his choice and quantity.
• If the money entered is less than the total amount, print “You cannot buy this quantity
of the chosen drink” otherwise, print the total amount and the remaining money.

Page 8 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 04: Formulating Algorithms, Repetition
Control Statements

Exercise 1
Write a Java program that computes the sum of even numbers less than or equal to n where n
is given by the user (without nesting the control statements).

Exercise 2
Write a Java application that computes the sum of even numbers and the product of odd
numbers that are in the range [a, b] where a and b are given by the user (without nesting the
control statements, to do so you have to use 2 separate loops).

Problem (class ConsecutiveNumbers)


Write a Java program that checks if a series of 10 numbers entered by the user in the ascending
order are consecutive (in this case, print congrats message) or not (in this case, print the number
of conflicts).
Example 1:
Number 1 = 10
Number 2 = 12
Conflict: 10 & 12 are not consecutive.
Number 3 = 14
Conflict: 12 & 14 are not consecutive.
Number 4 = 15
Number 5 = 16
Number 6 = 17
Number 7 = 18
Number 8 = 19
Number 9 = 20
Number 10 = 30
Conflict: 20 & 30 are not consecutive.

Unfortunately, you have 3 conflicts.

Example 2:
Number 1 = 1
Number 2 = 2
Number 3 = 3
Number 4 = 4

Page 9 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Number 5 = 5
Number 6 = 6
Number 7 = 7
Number 8 = 8
Number 9 = 9
Number 10 = 10

Congrats. All numbers are consecutive.

Page 10 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 05: Formulating Algorithms, Repetition
Control Statements

Exercise 1
Write a Java program that computes the maximum of n numbers given by the user (use counter
and sentinel approaches).

Exercise 2
Write a Java program that counts the number of divisors of a number n given by the user.

Exercise 3
Write a Java program that determines whether a number n given by the user is prime or not.
(use: do/while)

Exercise 4
Write a Java program that prints the list of characters between two characters a and b given
by the user and supposed ordered.

Problem (class SumNonDuplicates)


Write a Java program that sums a series of 10 numbers without duplicates. These numbers are
supposed entered ordered by the user. The program will print at the end the computed sum and
whether there are duplicates (in this case, print the number of duplicates) or not.
Example 1:
Number 1 = 1
Number 2 = 1
Number 3 = 2
Number 4 = 2
Number 5 = 2
Number 6 = 3
Number 7 = 4
Number 8 = 4
Number 9 = 4

Page 11 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Number 10 = 4

Sum = 10
The number of duplicates is: 6
Example 2:
Number 1 = 10
Number 2 = 20
Number 3 = 30
Number 4 = 40
Number 5 = 50
Number 6 = 60
Number 7 = 70
Number 8 = 80
Number 9 = 90
Number 10 = 100

Sum = 550
No duplicate numbers were entered.

Page 12 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 06: Methods, Introduction to Recursion

Exercise 1
Create a method that takes a value and indicate whether it is positive or negative by a return a
Boolean value.
Declared as: boolean isPositive (float a)

Exercise 2
Create a method that takes a value and tell whether it is null or not.
Declared as: boolean isZero (float a)

Exercise 3
Create a method delta() that takes three values, a, b and c, which are the coefficients of a
quadratic equation and returns the value of the delta, which is given by b ² - 4ac

Exercise 4
Using the 3 methods above, create an application that calculates the roots of an equation of
second degree:
ax ² + bx + c = 0
For it exists, the coefficient a must be nonzero.
If delta is positive, then there are two distinct roots:

If delta is zero, then there is exactly one real root:

If delta is negative, there is no real solution.

Page 13 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Exercise 5
Write a method to convert an upper-case letter to a lower-case letter. (Hint: Check first to be
sure that it is not lower case already.)

Page 14 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 07: Methods, Introduction to Recursion

Exercise 1
Create a method that randomly select a letter in the alphabet.

Exercise 2
Complete this code fragment which is supposed to count the number of alphanumeric
characters in a string s (you may use Character.isDigit and Character.isLetter methods to
check if a character is a digit or a letter respectively).
for(int i = 0; i < s.length(); i++) {
if (........................................................){
count++;
}
}

Exercise 3
The following two methods are supposed to compute the absolute value of 1 number and the
absolute value of the sum of 2 numbers respectively. Find and fix 2 errors to make these
methods work properly.
public static int abs(int n) { ............................

return n <= 0 ? n : -1 * n; ............................


}

public static int abs(int a, int b) {............................

int c = a + b; ............................

return abs(a,b); ............................


}

Page 15 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Exercise 4
avg is supposed to: receive any (undetermined) number of parameters of type double, compute,
and return their average. Find and fix 3 errors to make this method works properly.
public static double avg(double numbers) { ...........................

double s; ............................

for (double v: numbers) ............................

s += v; ............................

return s/numbers.size(); ............................


}

Page 16 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 08: Arrays

Problem (class MergeSalary)

First, write a Java method merge that takes as parameter a non-empty double array representing
employees’ salaries. The method merges the values of every 2 adjacent elements. put the
merged values at the beginning of the array, and put 0 in the remaining positions. Suppose that
the original array will contain an even number of elements.

Second, write two java methods readArray(int[]a) and printArray(int[]a) that


reads/writes the elements of an array passed in parameter from/to the standard input/output.

Finally, Use the following main method to test your different methods:
public class MergeSalary
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double[] salaries = new double[10];
System.out.print("Enter 10 salaries: ");
readArray(salaries);
merge(salaries);

System.out.print("Salaries after merge: ");


printArray(salaries);

}
}
Hint: For the method merge, you can work on the same array or use a temporary array.

Run:
Enter 10 salaries:
1000 1000 2000 2000 3000 3000 4000 4000 5000 5000

Salaries after merge:


2000.00 4000.00 6000.00 8000.00 10000.00 0.00 0.00 0.00 0.00 0.00

Page 17 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 09: Arrays

Problem (class CheckSequence)


First, write a Java method isSequence that takes as parameters a non-empty 2-dimensional
array of integers. The method checks whether the elements of the array are consecutive or not.

Second, write a java methods printArray(int[][]a) that writes the elements of an array
passed in parameter to the standard output.

Finally, use the following main method to test your different methods:
public class CheckSequence
{
public static void main(String[] args)
{
int[][] array1 = {{5,6,7,8},{9,10,11,12},{13,14,15,16}, {17,18,19,20}};
int[][] array2 = {{1, 3 , 2,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};

if (isSequence(array1))
{
System.out.println("The following array elements are successive:");
printArray(array1);
}

if (isSequence(array2))
{
System.out.println("The following array elements are successive:");
printArray(array2);
}
}
}

Run Example:
The following array elements are successive:
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

Page 18 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Homework 10: Strings

Exercise 1 (class NameSplitter)

Write a Java method splitName() that takes a string (that contains 1 word or more (space-
separated)), split it into words, count the number of words, makes the first letter of each word
capital, and display each modified word in a line.
Write main() method that reads a full name (use nextLine() of the Scanner), removes
eventual extra spaces, and makes all characters of the full name in lower case. Then, sends the
name to splitName() method and displays the returned value.
Hints: use only String methods studied so far (don’t use split() which require array
manipulations that we didn’t study it yet)

Run:
Enter your full name: MohammAD BIN saud
Splitted name:
Mohammad
Bin
Saud

You entered 3 word(s)

Exercise 2 (class Hex2Dec)


Write a Java method toDecimalString() that receives a string with hexadecimal symbols and
returns another string where every hexadecimal symbol is converted individually to its decimal
representation. If the received string contains a wrong hexadecimal value, it should return an error
message.
To test your method, write a main() method that enables the user to input a string in hexadecimal
format, removes eventual extra spaces from it, and makes all characters of the string in upper case.
Then, sends this string to toDecimalString() and displays the returned string (decimal format or
error message).
Hints:
1. To declare an empty string use: String newString = "";
2. The hexadecimal system is composed of 16 symbols: 0 to 9 and A to F.
a. To check if a character c is a digit you can use: Character.isDigit(c);
b. The decimal representation of A is 10, B is 11, C is12, D is 13, E is 14, and F is 15.

Page 19 of 20

Imam University | CCIS | Doc. No. 006-02-20170316


Run Example 1:
Enter a hexadecimal string: 2gk
Decimal value is: Wrong hexadecimal value (g)

Run Example 2:
Enter a hexadecimal string: 1f2bc9a
Decimal value is: 1 15 2 11 12 9 10

Exercise 3 (class CheckProtection)


Write a Java method named check() that checks the validity of a password received as string
parameter. To be valid, a password should contain at least: 3 letters, 2 digits, and 1 character from {‘-’,
‘_’}. If the password is valid the method returns true, otherwise it returns false.
To test your method, write a main() method that enables the user to input a password as a string,
removes eventual extra spaces from it, sends it to check(), and displays the returned decision (the
password is valid or not).

Hints: To check if a character c is a digit you can use Character.isDigit(c), and to check if it is
a letter you can use Character.isLetter(c).

Run Example 1:
Enter a password to check (at least 2 digits, 3 letters, and one char (- or _)): p5t4_i
The password is valid.

Run Example 2:
Enter a password to check (at least 2 digits, 3 letters, and one char (- or _)): i0z#-9k
The password is not valid.

Page 20 of 20

Imam University | CCIS | Doc. No. 006-02-20170316

You might also like