BCSE103E: Computer Programming: Java
Basic programs with Java (involving loops)
Dr. P Sasanka Bhushan
General:
1. Write a program that finds the product of N numbers that are input one-by-one by the
user. N is given by the user.
Algorithm
Java Program
Prepare iteration table for the loop used in the above program (N=4):
count product Check num product count=count+1
count<=N =product*num
1 1 True 6 1*6=6 2
2 6 True 4 6*4=24 3
3 24 True 4 24*4=96 4
4 96 True 5 96*5=480 5
5 480 False Not
continue
Print 480
2. A person is tracking the consumption of cooking oil in her kitchen in each month. Write a
program that takes input for the amount of consumption in litres for N months. Then the
program calculates average consumption, minimum consumption and maximum
consumption and prints the same.
Algorithm
Java Program
Prepare iteration table for the loop used in the above program (N=4):
count tot_cons min max Check cons sum min max count=count+1
count<=N =sum+cons
3. A product has an initial price of P. Every week, the price will be cut by 10% of the
previous price until the price reaches a given lowest price. Write a program that takes P
and the lowest price and prints price for the next five weeks. If the lowest is reached, it
will print the same for the remaining weeks.
Ex: Input:
Initial price: 500
Lowest: 300
Output:
Week0: 500
Week1: 450
Week2: 405
Week3: 364
Week4:328
Week5: 300
Algorithm
Java Program
Prepare iteration table for the loop used in the above program (N=4):
4. Write a program that takes a decimal number as input and prints binary number as
output.
Algorithm
Java Program
Prepare iteration table for the loop used in the above program (dec=34):
5. Encoding is used to pass information secretly. A simple encoding method is: Take a
number and replace each digit with the subsequent fourth digit on the digit scale. For
example, 34 becomes 78; 47 becomes 81. Write a program that gets a number from the
user and prints the encoded number. For simplicity, assume that the number has 3
digits.
After completing this program, try to make the program work for any number of digits.
Algorithm
Java Program
Prepare iteration table for the loop used in the above program (num=568):