Buzz Code
Published in

Buzz Code

Java 8 | For Practice

Hey y’all! I brought you some practice questions that need to be solved with the for statement. Today it’s gonna be all basics, so as usual try to solve the questions by yourself and then check the answers! To do that you need to be aware of how to use the For statement, so please learn it first before you scroll down!

Question 1. Print 1 3 5 7 9.

Try to solve it only with the For statement. If you know the meaning of ++ well, it’s not hard at all. The answer is right on below.

I initialized the variable i as 1 which satisfies the condition that i<10 . So i will be printed into 1 first. And then move to the increment/decrement section, you see that I put i=i+2 on there. some of you might think only i++ or i-- can be there, but i++ is just a shorten version of the i=i+1 ! So it’s fine as long as it increase or decrease the value.
Here the variable i is 1, so i=i+2 will be meaning of i=1+2 . Like this you can keep add more numbers onto the variable i .

Question 2. Print 10 9 8 7 6 5 4 3 2 1.

If you guessed you will need the decrement, you’re right. The answer is on below.

I set the initial value of i as 10, and the condition as i>0 . And I put the i-- So the number can get lower every time when the statement is repeated.

Question 3. Print the sum of the numbers 1 to 99.

The hint is that you would need two different variables. The answer is on below.

On the outside of the For statement, I made another variable and I named it into sum, So I can print it out after the loop ends.
On the first loop it will be sum=0(sum’s initial value)+1(i's initial value). So sum’s value will become 1.
On the next loop it will be sum=1+2 …And so on.
And the double quotes in the println method, means String. So basically you can write the sequence of characters that you want to print out on the console with the double quotes.

Question 4. Print the outcome of the following equation( 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 = ? )

This is a very similar question with the one above.

* is the multiplication sign.

Question 5. How many numbers are there from 1 to 10?

Spoiler alert! The answer is 10. I know this question sounds bit silly but we need to know how to make it into a program for the future sessions!

I created the variable and named it into cnt shorten for count. And made it increased during the loop repeated.

Could you solve all the questions above by yourself? Then that’s great! If you couldn’t, it’s also fine, but try to fully understand how the For statements work. On the next session I’ll bring you some more of the practice questions that you can work on both If and For statements. Thank you for reading today as well. See ya!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store