Java Loops II

  • + 0 comments

    See, you have already been provided with the explanation.The question wants you to print a series in the given format. But many people fail at understanding that their program should take input and give output as demonstrated below:- Input: 2 0 2 10 Output: 2 6 14 30 62 126 254 510 1022 2046 Input: 5 3 5 Output: 8 14 26 50 98

    Now, to print the series you need to find what is common between the initial formula and the following formulae.So,

    Initial Formula: (a+2^0*b)

    Second Formula: (a+2^0*b+2^1*b)

    If you notice these two formulae carefully you will see that a+2^0+b is common in both the formulae but in the second one the last part has been replicated and the power of 2 has been changed.In all the formulae given the power of 2 is increasing and so our program should add a definitely and then the rest of the formula is dependent on b and the power of 2. So we can use the shorthand operator += so that 2 is added at the end.

    To handle the power of 2 we just need to use a for loop since it is given that this power of two starts at 0 and goes all the way up to n-1.Thus, we make a for loop which runs from 0 to n-1 having the loop variable as 0 and the condition as loopvar

    Thus we will only need to print the term using printf and then add a println statement at the end of the main loop which is the loop that will be used to take the 3 inputs only.The value of q will be used in the condition as it is entered only once.

    Our Formula will look like:

    result+=Math.pow(2,j)*b; // j is the loop variable // result should be equal to a