Note: Yound
There is a JAR full of Candies for sale at a mall
counter. JAR has the capacity N, that is JAR can
contain maximum N Candies when JAR is full
At any point of time, JAR can have M number of
Candies where M<-N. Candies are served to the
customers. JAR is never remaining empty as when
last k candies are left. JAR is refilled with new Candies
in such a way that JAR gets full.
Write the code to implement above scenario. Display
JAR at Counter with available number of candies.
Input should be number of candies one customer
orders at point of time. Update the JAR after every
purchase and display JAR at Counter.
Output should give number of Candies sold and
updated number of Candies in JAR
If input is more than number of Candies in JAR,
return: "INVALID INPUT"
Given,
N= 10.where N is NUMBER OF CANDIES AVAILABLE
k=<5, where kis number of minimum Candies that
must be inside JAR ever.
Example 1: (N=10, k=<5)
Input Value
3
Output Values
NUMBER OF CANDIES SOLD: 3
NUMBER OF CANDIES AVAILABLE: 7
Answers
Answer:
Solution in Java
import java.util.Scanner;
class Main{
public static void main(String[] args) {
int n = 10, k = 5;
int num;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
if(num >= 1 && num <= 5) {
System.out.println("NUMBER OF CANDIES SOLD : " + num);
System.out.print("NUMBER OF CANDIES LEFT : " + (n - num));
} else {
System.out.println("INVALID INPUT");
System.out.print("NUMBER OF CANDIES LEFT : " + n);
}
}
}
Answer:
Solution program code if written in python:
n = 10 #Total capacity of Jar
m = n #Candies available in jar
k = 5 #Minimum Candies that should be present
a = "y" #Loop Variable
while a == "y":
c = int( input( "Enter the number of candies you want to buy:"))
if c > m: #if the input is greater than the candies available
print( "Required number of candies not available!!" )
else:
print( "Number of Candies Sold:", c)
m = m - c #Updating the number of available candies
print( "Number of Candies available:", m)
#Adding candies to fill the jar if it's less than minimum value
if m <= k:
m = 10
a = input( "Do you want to buy candies? (y/n):")
Explanation:
We are given a jar with 'n=10' candies and the number of candies available in it at any point of time is 'm'. We need to have at least of 'k=5' candies in the jar. If 'm' goes less than 'k', we have to completely fill the jar. Thus, firstly, the variables will be defined for 'n', 'm', 'k', and another variable 'a' for traversing the while loop.
Then we have a while loop which will keep on taking input and selling the candies until the user says no. First, it will take input about how many candies the customer requires and after checking if it has the asked number of candies, it updates all the values and gives the output. The loop then checks if the number of candies is more than the minimum number required. If yes, it continues, otherwise it updates the value of 'm' to be 10 as the jar can contain a total of 10 candies.
#SPJ3