I am currently in the process of learning Java and I have an assignment that asks me to write a for loop. I need to create a small program that allows user input then uses the for loop to put a message telling the user their info. I need the for loop to allow, to sum up the number of days the user put and for each day they grain and I also need to get double the amount of grain for each day.
EXAMPLE:
Day 1 you get 1 grain of rice for a total of 1 grain
Day 2 you get 2 grains of rice for a total of 3 grains
Day 3 you get 4 grains of rice for a total of 7 grains
Day 4 you get 8 grains of rice for a total of 15 grains
Day X you get X grains of rice for a total of Y grains
I am not totally sure how to set up my for loop to do this. Here is what I have so far.
public static void GrainCounter()
{
Scanner s = new Scanner(System.in);
System.out.println("How many days worth of grain do you have?");
int days = s.nextInt();
int sum = 0;
for (int i = 0; i <= days; i++)
{
sum = sum + i;
}
System.out.print("Day " + days + " you got " + sum + " grains of rice");
}
The formula is actually,
Day X you get 2**X grains of rice for a total of Y grains
Your sum
should start at 1
, and you should put your print
in the loop (also you want to print i
for the day). Something like,
System.out.println("Day 1 you get 1 grain of rice for a total of 1 grain");
int sum = 1;
for (int i = 1; i <= days; i++)
{
sum += Math.pow(2, i);
System.out.println("Day " + (i + 1) + " you got " + (int)Math.pow(2,i) +
" grains of rice for a total of " + sum + " grains");
}
You could also write the println
as
System.out.printf("Day %d you got %d grains of rice for a total of %d grains%n",
i + 1, (int) Math.pow(2, i), sum);