For (A Lesson; On C#; Loops)

Hello readers,

Michael here, and today’s post will be all about loops in C#. We’ll go over the for-loop, foreach-loop and while-loop!

If you learned about loops through some of my previous programming tools, great! However, for those who may not know, loops in programming are simple sets of directions for the program to repeat X amount of times until a certain condition is met.

For (A Piece; On C#; Loops)

The first type of loop we’ll cover is a simple C# for loop. Here’s an example of a C# for loop:

for (int m = 5; m <= 30; m+=5)
{
    Console.WriteLine(m);
}

5
10
15
20
25
30

In this loop, I have the for (statement 1; statement 2; statement 3) with the respective statements being int m = 5 (setting initial loop value to 5), m <= 30 (setting the loop-ending condition to the point where m is less than or equal to 30), and m+=5 (indicating that m should be incremented by 5 during each loop iteration). After the for statement, I have the body of the loop, which prints out each successive value from 5 to 30 in increments of 5.

  • Just so you remember, the three statements in a C# for loop are (in order) the initial value-setter, the loop-ending condition, and the action that should be performed during each loop iteration. Also, the statements in the for loop need to be separated by semicolons.

Foreach (Lesson in Loops)

The next type of C# loop we’ll iterate through (coder joke) is the foreach loop. Here’s an example of a foreach loop below:

string[] states = ["Tennessee", "Florida", "California", "New Mexico", "Arizona", "Ohio", "Indiana"];

foreach (string s in states)
{
    Console.WriteLine(s);
}

Tennessee
Florida
California
New Mexico
Arizona
Ohio
Indiana

In this example, I’m iterating through the states array using the foreach loop. Unlike the for loop, the foreach loop only requires one statement-(array type element in array). In this statement, you’ll need to include the array type, indicator value for each element in the array (s in this case) and the name of the array. In this case, I used foreach (string s in states).

While (C# Loop Runs)

Last but not least, let’s explore C# while loops. You may recognize while loops from other programming tools you know about (like Python) and in C#, while loops do the same thing-run the loop over and over WHILE a certain condition is True.

Here’s an example of a simple C# while loop:

int o = 2;

while (o <= 100)
{
    Console.WriteLine(o);
    o *= 2;
}

2
4
8
16
32
64

In this example, we have a simple C# while loop that sets the initial value-o-to 2. The loop will then multiply o by 2 for each iteration until o hits the highest possible value allowed by the loop condition. In other words, o will keep multiplying itself by 2 until it gets to 64, as 64*2 (128) will end the loop as 128 is greater than 100.

Now, how would you structure a C# while loop? The syntax is quite simple-while (condition to keep loop running) { code block to execute }.

Do (Loop Code) While Loop = Running

So we just explored the C# while loop. However, did you know there’s a variation of the C# while loop called the do-while loop. It works just like a while loop with one major difference-do-while loops will always be executed at least once as they always check whether the condition is still true before performing the next loop iteration. Here’s our while loop example from above converted into a do-while loop

int f = 2;

do  
{
    Console.WriteLine(f);
    f *= 2;
} 
while (f <= 100);

2
4
8
16
32
64

How would you structure a do-while loop. Easy-do { code block to execute } while (condition to test loop)! As you can see from the output, our do-while loop returned the same six values as our while loop above.

For (Infinite; Loop; Encounters)

Yes, just as with other languages we’ve covered (Python and R for two), it is possible to have the infinite loop encounter in C# as well. Here’s an example of that:

while (true)
{
    Console.WriteLine("Michael's Programming Bytes");
}

The loop above is a simple example of an infinite C# loop. Since the while (true) statement will never stop the loop, it will just keep going, and going, and going…unless of course you write a break statement in the loop to stop it after X iterations or something like that.

For (Nested; Loops) For (In; C#)

Yes, it is possible to have nested loops in C#, just as it’s possible to have nested loops in other programming languages. Here’s a simple example of a C# nested loop:

for (int t = 2; t <= 20; t*=2)
{
    for (int n = 5; n <= 30; n+=5)
    {
        Console.WriteLine(t * n);
    }
}

10
20
30
40
50
60
20
40
60
80
100
120
40
80
120
160
200
240
80
160
240
320
400
480

This loop will print out all possible products of t and n through each iteration of the nested loop pair. The outermost loop-the one with t-runs first while the innermost loop-the one with n-runs second. The reason you see 24 outputs on this page is because the amount of iterations a nested loop has is the product of the amount of iterations for each individual loop. In this case, since the t loop runs four times and the n loop runs six times, we get 24 total iterations of the nested loop (4*6=24).

Here’s the link to the script for today’s post on my GitHub-https://github.com/mfletcher2021/blogcode/blob/main/Loops.cs. Note that I did include the infinite loop example here but if you want to effectively test the other loops, you can “turn off” the infinite loop simply by commenting it out of the code.

Thanks for reading,

Michael

Python Lesson 6: Loops

Hello everybody,

It’s Michael, and today’s Python lesson will be on loops. Like Java, Python also has loops, but while Java has three main types of loops, Python only has two-while and for. There is no do-while loop in Python.

Let’s start by discussing the while loop. The Python while loop works the same as its Java counterpart since both loops will keep running WHILE a certain condition is true. Here’s a demonstration of a Python while loop:

x = 10
y = 1
while (y <= 6):
print(x**y)
y += 1

And here’s the output:

10
100
1000
10000
100000
1000000

In this while loop, successive powers of 10 are printed as long as y is less than or equal to 6; y is also incremented by 1 with each iteration of the loop. In other words, the first 6 powers of 10 (from 10^1 to 10^6) will be printed.

One thing to keep in mind is that, even though Python while loops work the same as their Java counterparts, the syntax between the two while loops differs. However, the difference is fairly minor, as Python would use a colon to denote the loop, while Java would use a pair of curly brackets.

Now, let’s make things a little more complex by adding the break statement. Here’s a sample program:

x = 1936
while (x <= 2020):
print(x)
x += 4
if (x % 7 == 0):
break

And here’s the output:

1936
1940
1944
1948
1952
1956

One thing to remember with the break statement is that it gives the loop another condition to evaluate. Loops with a break statement will keep running until either one of two conditions has been met. In the example above, the program will keep printing numbers (starting from 1936) and increasing them by 4 after each iteration until either 2020 (or the closest possible number to 2020) OR a number evenly divisible by 7 has been reached. In this case, 1960 would be the first number evenly divisible by 7, but the program will stop printing at the closest possible number-1956.

Now let’s try implementing a continue statement:

x = 2
while (x <= 20):
x += 2
if (x == 10):
continue
print(x)

And here’s the output:

4
6
8
12
14
16
18
20
22

Unlike the break statement, the continue statement won’t stop running a loop if a certain condition is met. Rather, if a certain condition is met, the continue statement will skip a certain iteration of the loop but then continue to run the loop. In this example, x is 2 and will keep increasing by 2 until x reaches 20. However, the continue statement says if (x == 10) continue. This means that 10 will not be displayed in the final output; rather, the program will jump from 8 to 12, as it was told to skip 10.

Now I’ll discuss for loops in Python. They are similar to their Java counterparts, except that they don’t require an indexing value to be set beforehand.

  • In case you’re wondering, the x in all of my while loop examples is an indexing variable. In Python while loops, an indexing variable acts as a “guide” by telling the loop where to start.

Another difference between Python for loops and their Java counterparts is that Python for loops are mostly used just to run through sequences of characters or Strings while Java for loops have more mathematical capabilities. In other words, with Java for loops, you’re able to do calculations with each iteration, but that isn’t possible with Python for loops. However, you can run through basic number sequences with Python for loops, which I will explain later.

Let’s demonstrate a basic Python for loop:

for y in “Michael”:
print(y)

And here’s the output:

M
i
c
h
a
e
l

In this program, I have a basic for loop that will run through all the letters in my name-Michael-and print out each letter one by one.

Notice that the syntax for Python for loops is much simpler than for their Java counterparts. In Java, you would need one line with three different statements whereas in Python, you only need one line for one statement, which always goes like for _____ in _____ followed by the body of the loop.

Now let’s try adding a break statement with a for loop:

teams = [“Heat”, “Cavaliers”, “Timberwolves”, “76ers”, “Jazz”]
for y in teams:
print(y)
if (y == “76ers”):
break

And here’s the output:

Heat
Cavaliers
Timberwolves
76ers

In this example, the loop will run through all of the elements in this sequence before stopping once it reaches the 76ers element, which will be the last element displayed in the output.

Now let’s try a for loop with a continue statement:

teams = [“Heat”, “Cavaliers”, “Timberwolves”, “76ers”, “Jazz”, “Nets”, “Hawks”]
for y in teams:
if (y == “Jazz”):
continue
print(y)

And here’s the output:

Heat
Cavaliers
Timberwolves
76ers
Nets
Hawks

In this program, the loop will run through MOST of the elements, but Jazz will be skipped, since that’s where the loop will continue.

  • One thing I wanted to mention is that, with both for and while loops, if you have a break statement in the loop, put the print before the break statement. However, if you have a continue statement, put the print after the continue statement.

Now, I did mention that even though Python for loops aren’t capable of doing much in the way of calculations, they are capable of running through basic number sequences. Here’s an example:

for y in range(11):
print(y)

And here’s the output:

0
1
2
3
4
5
6
7
8
9
10

In this program, the range(11) function will print out 11 numbers. You might be thinking “What 11 numbers?”. You might be thinking the numbers 1-11 will be printed, but that is a common misconception. Whenever the range(N) function is used, the first number printed will always be 0, with each successive number being incremented by 1, until N-1 is reached, which is 10 in this case.

However, range() sequences don’t always have to begin with 0. Here’s an example of that:

for y in range(4, 13):
print(y)

And here’s the output:

4
5
6
7
8
9
10
11
12

In this example, range() has the parameters 4, 13. The program then prints out numbers between 4 and 13, but not including 13 (I’m not totally sure why 4 was printed but 13 wasn’t, but I guess it’s one of those weird coding rules).

Another thing about the range() function is that, even though it defaults to an increment by 1 pattern, you can change the increment pattern simply by adding a third parameter. Here’s how:

for y in range(20, 100, 14):
print(y)

And here’s the output:

20
34
48
62
76
90

In this program, range() has the parameters 20, 100, 14. The program will print out numbers between 20 and 100 using an increment by 14 pattern. The loop will stop running when it has reached the closet possible number to 100 (using the increment pattern).

You can also use decrement patterns in your for loops. Here’s how:

for y in range(112, 16, -8):
print(y)

And here’s the output:

112
104
96
88
80
72
64
56
48
40
32
24

In this program, the parameters for range() are 112, 16, -8. The program will start by printing 112; each subsequent number will be decreased by 8 until the closest possible number to 16 (using this pattern) is obtained. If 16 can be reached with this pattern (which it can), it will not be printed.

  • With increments, make sure your second number is greater than your first. On the other hand, with decrements, make sure your first number is greater than your second.
  • Also, remember to make the third parameter negative to denote a decrement pattern.

Now, let me show you what the else statement can do in a for loop:

for y in range(112, 16, -8):
print(y)
else:
print(“All done”)

And here’s the output:

112
104
96
88
80
72
64
56
48
40
32
24
All done

The else statement in a for loop is simple to understand, as it tells the loop what to do (or what to print) when it finishes iterating. In this case, the program prints out the same thing as the previous example along with the message All done when the loop is finished iterating.

Last but not least, I want to  demonstrate and discuss the concept of a nested for loop. Here’s an example:

adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”, “hamster”]
for x in adj:
for y in animal:
print(x, y)

And here’s the output:

young dog
young cat
young ferret
young hamster
old dog
old cat
old ferret
old hamster
hairy dog
hairy cat
hairy ferret
hairy hamster
playfu] dog
playfu] cat
playfu] ferret
playfu] hamster

In this example, the program will print out one element from adj (or x) and one element from animal (or y). Since x is the first parameter of print adj (or adjective) will print first followed by y (or animal). In other words, the adjective describing the animal will be printed first, followed by the name of the animal. Since this is a loop, every animal’s name will appear once alongside every adjective.

But what if there weren’t the same amount of elements in each sequence? Here’s an example of that case (it’s the same program with the word hamster omitted):

adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”]
for x in adj:
for y in animal:
print(x, y)

And here’s the output:

adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”]
for x in adj:
for y in animal:
print(x, y)

So, even though I omitted a word, essentially nothing changes (well, aside from the omitted word). Each animal’s name still appears once alongside every adjective.

  • For the record, you can’t create nested while loops.

Thanks for reading,

Michael

R Lesson 16: R Loops

Hello everybody,

It’s Michael, and today’s lesson will be on loops in R. I’ve posted about loops before, but those were for my Java lessons. However, while there may be some differences between Java loops and R loops, the basic ideas are the same. In fact, two of the three main types of Java loops-while and for-are also the two main types of R loops. The do-while loop doesn’t exist in R…..at least not yet. In its place, R has something called the repeatloop.

Let’s demonstrate the forloop first:

Screen Shot 2019-06-02 at 1.02.22 PM

In this for loop, the factorials for the numbers 1-10 are printed. The i is a common symbol in R loops-it represents the indexes (or elements) of a loop. The i will traverse through all 10 elements of the loop-in this case, the numbers 1 through 10-and print out the factorials of each number along with the corresponding text-The factorial for , i , is, factorial(i).

  • In case you weren’t aware, the factorial of a number is the product of that number and all numbers below it (stopping at 1). So 4 factorial would be 24, since 4*3*2*1 equals 24. Factorials are denoted with an exclamation point by the number, so 4 factorial would be written as 4!. You might have come across this concept in your algebra class.

Now let’s take a look at the differences in syntax between a Java for loop and an R for loop (using the same factorial output)

R for loop:

for (i in 1:10)

{print(paste(“The factorial for” , i , “is” , factorial(i)))}

Java for loop:

int fac = 1;

for (int i = 1; i <= 10; i++)

{

fac *= i;

System.out.println(“The factorial of  ” + i + ” is ” + fac );

}

So, where are all of the differences? Let me name 5:

  1. The commands to print the output are different. Java requires System.out.println (or System.out.print). R requires print(paste()).
  2. Java needs 6 lines of code to do what R can accomplish in two lines-which is to calculate the factorials of the numbers 1-10 and print the specified output.
  3. The way to concatenate strings and numbers is different-Java requires a plus sign while R uses a comma
  4. You will often need to declare a variable outside the loop in Java (like I did with fac = 1). That is usually not necessary in R.
  5. The forloop parameters in R are much simpler than those in Java. Here’s how:
    • The Java for loop parameters go (initializing condition; condition to stop the loop; action to perform after each iteration)
    • The R for loop parameters go (index variable in starting value:ending value). The starting value:ending value part tells the loop the startpoint and endpoint.

Next, let’s demonstrate a nested for loop. Just like in Java, you can make nested for loops:

Screen Shot 2019-06-02 at 3.45.40 PM

And here’s the output (it was too large to capture in a single screenshot):

[1] “I times J is 6”
[1] “I times J is 8”
[1] “I times J is 10”
[1] “I times J is 12”
[1] “I times J is 14”
[1] “I times J is 16”
[1] “I times J is 18”
[1] “I times J is 9”
[1] “I times J is 12”
[1] “I times J is 15”
[1] “I times J is 18”
[1] “I times J is 21”
[1] “I times J is 24”
[1] “I times J is 27”
[1] “I times J is 12”
[1] “I times J is 16”
[1] “I times J is 20”
[1] “I times J is 24”
[1] “I times J is 28”
[1] “I times J is 32”
[1] “I times J is 36”
[1] “I times J is 15”
[1] “I times J is 20”
[1] “I times J is 25”
[1] “I times J is 30”
[1] “I times J is 35”
[1] “I times J is 40”
[1] “I times J is 45”
[1] “I times J is 18”
[1] “I times J is 24”
[1] “I times J is 30”
[1] “I times J is 36”
[1] “I times J is 42”
[1] “I times J is 48”
[1] “I times J is 54”
[1] “I times J is 21”
[1] “I times J is 28”
[1] “I times J is 35”
[1] “I times J is 42”
[1] “I times J is 49”
[1] “I times J is 56”
[1] “I times J is 63”
[1] “I times J is 24”
[1] “I times J is 32”
[1] “I times J is 40”
[1] “I times J is 48”
[1] “I times J is 56”
[1] “I times J is 64”
[1] “I times J is 72”

In this nested forloop, I have two important segments. The I segment traverses through the numbers 2-8 while the J segment traverses through the numbers 3-9. However, the statements on their own are useless. The only line that really matters is the output line-"I times J is" , i*j. This line will print out the product of i and j.

OK, so that isn’t as simple as it looks. That is because the loop will traverse through every element of the I and J statements. In other words, the products of every element in the I statement and every element in the J statement will be displayed. For instance, the answer to 2*3 will be displayed, followed by 2*4, 2*5, all the way up to 2*9. Then all of the products from 3*3 to 3*9 will be displayed, and so forth, until you hit the 8 range (meaning from 8*3 to 8*9).

Now let’s create a while loop:

Screen Shot 2019-06-03 at 3.43.39 PM

And here is the output (it was too long to fit on the same screenshot as the loop):

Screen Shot 2019-06-03 at 3.43.55 PM

In this loop, I use 1902 as a starting point and 2018 as a stopping point. For each iteration, num will increase by 4 (starting from 1902) until 2018 is reached. In case you are wondering where I’m going with this, I’m printing out every even-numbered non-leap year between 1902 and 2018 inclusive.

  • Unfortunately, R doesn’t recognize increment/decrement symbols like ++, --, +=, -=, /=, *= the way Java does. So you’ll just have to increment/decrement in long form, as I did with the num <- num + 4 line.

Unlike for loops between Java and R, while loops between Java and R are very similar. Here’s the R loop for this program:

num <- 1902

while (num <= 2018)

{

print (num)

num <- num + 4

}

And here’s a Java whileloop that will do the exact same thing as the R loop:

num = 1902;

while (num <= 2018)

{

System.out.println(num)

num += 4;

}

One of the similarities between the two while loops are the parameters of the loop. In both loops, the lone parameter is what I’d like to call the running condition, which is the condition that tells the loop that while that condition is true, keep the loop running. In both cases, the running condition is num <= 2018.

The differences between the two loops are related to the difference in functions between Java and R. For instance, Java output requires System.out.printlnwhile R output simply requires print(or print(paste()) for outputs with strings). The other main difference is how to denote incrementing/decrementing in the loop, which I already discussed earlier in this post.

The third type of R loop is the repeat; this is the loop that is exclusive to R (just as the do-while loop is exclusive to Java). In R, a repeat loop is similar to a while loop in the sense that both loops have a stop condition (which is the condition that stops the loop from running). However, in while loops, the stop condition also functions as the running condition. For instance, the statement num <= 2018acts as both a running condition and a stop condition, since it tells the loop to keep running as long as num is less than or equal to 2018 but it also tells the loop to stop running as soon as 2018 (or the closest number to it) is reached.

Repeat loops don’t have a running condition per se, since they can be infinite. As a result, including a stop condition is totally optional. However, if you wish to include a stop condition, write an ifstatement (they’re formatted just like Java if statements) ending with the word break, which indicates that the loop will stop if the if statement condition is met.

Here’s an example of a repeat loop with a breakclause:

Screen Shot 2019-06-03 at 10.34.01 PM

In this loop, I start with num <- 5 just outside the loop. Once I get inside the loop, numkeeps getting multiplied by 2 until a number that is either greater than or equal to 1000 is reached. All of the products of num * 2 are printed, and the last output is 1280, which is 640*2.

  • Had I not included a breakstatement, this loop would have gone on and on. Inf would be displayed after a certain point to denote that the loop would be infinite.

Thanks for reading,

Michael

Java Lesson 7: Random Number Generator

Hello everybody,

It’s Michael, and I’ve decided to give you guys another series of java lessons. In this post, I’ll show you how to create your own random number generator, which is a tool that can generate random numbers in Java. Generating random numbers in Java is a common task that is used for a variety of purposes, such as gambling, statistical sampling, and any other scenario where you would need to simulate unpredictable behavior. Random number generators can also be used with arrays, which will be the topic of my next Java post.

Now let’s begin with an example of a simple random number generator:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();
int random = generator.nextInt(50);
System.out.println(random);
}
}

 

And here are two sample outputs:

run:
46
BUILD SUCCESSFUL (total time: 0 seconds)

run:
12
BUILD SUCCESSFUL (total time: 1 second)

Before writing the code for your program, remember to import java.util.Random (include this package anytime you plan on using the random number generator).

So what does all of this code mean? First of all, the Random generator = new Random () line indicates your random number generator variable. You keep the parentheses empty since you will indicate the boundaries in a separate int variable, which in this case is found in the line int Random = generator.nextInt(50). This line indicates that you want your program to print out a random number between 0 and 50 (the number in the parentheses indicates the upper limit of your random number generator). System.out.println(random) prints out a random number between 0 and 50

But what if you wanted to print out several random numbers? We can do just that, with the help of our random number generator and a handy for-loop:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();

for (int i = 0; i <= 8; i++)
{
int random = generator.nextInt(120);
System.out.print(random + ” , “);
}

}
}

And here are two sample outputs:

run:
6 , 17 , 20 , 98 , 82 , 46 , 43 , 5 , 19 , BUILD SUCCESSFUL (total time: 1 second)

run:
65 , 13 , 116 , 16 , 5 , 1 , 6 , 28 , 72 , BUILD SUCCESSFUL (total time: 2 seconds)

I kept the variables the same as the previous example; all I did here was add a for loop (for int = 0; i <= 8; i++) and changed the upper limit to 120. This program will print out 8 random numbers between 0 and 120, each separated by a comma.

So what if you want to use a custom range for your random number generator, as opposed to relying on the default of 0? Here’s how:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();

for (int i = 0; i <= 8; i++)
{
int random = 200 + generator.nextInt(600);
System.out.print(random + ” , “);
}

}
}

And here are two sample outputs:

run:
555 , 211 , 587 , 707 , 545 , 653 , 594 , 785 , 520 , BUILD SUCCESSFUL (total time: 2 seconds)

run:
415 , 345 , 579 , 462 , 660 , 695 , 593 , 337 , 505 , BUILD SUCCESSFUL (total time: 2 seconds)

The program is the same as the previous example, save for changing the upper limit to 600 and adding 200 + in front of the generator.nextInt line. Remember how I said I was going to show you how to use a custom range for your random number generator? Well, the 200 + is exactly how you can do that because putting this (or any number for that matter) in front of the generator.nextInt(600) line ensures that the range of your random number generator will only be from 200 to 600.

And last but not least, let’s see what happens when you want to input the value for the upper limit:

package javalessons;
import java.util.Random;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();
Scanner sc = new Scanner (System.in);
System.out.println(“Please choose a number: “);
int custom = sc.nextInt();

for (int i = 0; i <= 8; i++)
{
int random = generator.nextInt(custom);
System.out.print(random + ” , “);
}

}
}

And here are two sample outputs (using 35 for the first example and 91 for the second):

run:
Please choose a number:
35
31 , 23 , 4 , 5 , 22 , 9 , 14 , 11 , 10 , BUILD SUCCESSFUL (total time: 4 seconds)

run:
Please choose a number:
91
78 , 45 , 63 , 82 , 89 , 58 , 12 , 8 , 61 , BUILD SUCCESSFUL (total time: 2 seconds)

In this program, I added a Scanner variable (along with importing the Scanner class) and a custom int variable, which allows you to choose the endpoint for your random number generator (the start-point is still 0). As you can see from each sample output, the program will print out 8 random numbers that are less than or equal to the number that was inputted.

Thanks for reading,

Michael

Java Program Demo 1: Factorials and Fibonacci Sequences

Hello everybody,

It’s Michael, and today’s Java post will be a little different from the previous six because I am not giving you guys a lesson today. See, when I launched this blog in June 2018, I said I was going to posts lessons and analyses with various programs. However, in the case of Java, I feel it is better to give you guys program demos that cover the concepts I’ve discussed so far (loops, if-else statements, etc.). In this post, I will show you guys two programs that cover all the Java concepts I’ve discussed so far.

Here is this code for the first program (video in link)-Fibonacci sequence program:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Please choose a number: “);
int num = sc.nextInt();

int start = 0;
int t2 = 1;

if (num >= 0)
{
while (start <= num)
{
System.out.print(start + ” + “);

int sum = start + t2;
start = t2;
t2 = sum;
}
}

else
{
System.out.println(“Need a 0 or a positive number”);
}
}
}

This program prints every number in the Fibonacci sequence up to a certain point. If you’re wondering, the Fibonacci sequence is a pattern of numbers that starts with 0 and 1 and calculates each subsequent element by finding the sum of the two previous numbers.

  • Here are the first 10 numbers of the Fibonacci sequence-0,1,1,2,3,5,8,13,21,34,55. Notice how every element after the 3rd is the sum of the previous two numbers (e.g. 13 is found by calculating 5+8-the two numbers that directly precede 13 in the series)

To calculate the Fibonacci sequence, I first ask the user to type in a number. That number will serve as the endpoint for my while loop where I calculate each element in the Fibonacci sequence; in other words, my while loop will find every element in the sequence until it reaches the closest possible number to the user’s input. For instance, if I wanted to find every number in the Fibonacci sequence stopping at 600, the program would stop at the closest possible number to 600-which is 377.

  • I decided to add an endpoint because the Fibonacci sequence is infinite, and had I decided not to have an endpoint, I would’ve created an infinite loop.

Notice the if-else statement in my program. The loop will only run IF the user inputs a positive number. Otherwise, the user will just see a message that goes Need a 0 or a positive number. I decided to include the if-else statement since Fibonacci sequences don’t have any negative numbers.

Let’s see some sample output:

run:
Please choose a number:
112
0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 + BUILD SUCCESSFUL (total time: 6 seconds)

run:
Please choose a number:
-5
Need a 0 or a positive number
BUILD SUCCESSFUL (total time: 3 seconds)

As you can see, my first output-112-displays the Fibonacci sequence up to 112 while my second output-negative 5-displays a message that is shown when a negative number is chosen.

Here is the code for my next program (video in link)-Factorial program:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Please choose a number: “);
int num = sc.nextInt();

long factorial = 1;

if (num >= 1)
{
for(int i = 1; i <= num; ++i)
{
factorial *= i;
}
System.out.println(“The factorial of ” + num + ” is ” + factorial);
}

else
{
System.out.println (“Number is too low”);
}
}
}

This program calculates the factorial of a number greater than 0. For those wondering, a factorial is the product of a positive number and all positive numbers below it (stopping at 1). For instance 3 factorial is 6, since 3*2*1=6. Just so you guys know, factorials are denoted by the exclamation point (!), so 3 factorial is 3!.

I have three conditional statements in this program that account for the three possible scenarios of user input (>0,0, and <0). If the user enters a number greater than 0, then the for loop will execute and the factorial of the number will be calculated. If the user enters 0, then the message The factorial of 0 is 1 will be displayed, since 0!=1. If the user enters a negative number, then the message Number is too low will be displayed, since factorials only involve positive numbers.

  • If you are wondering why I used long for the factorial variable, I thought it would be more appropriate since factorials can get pretty long (13! is over 6 billion), and long has a wider range than int (9 quintillion as opposed to 2 billion).

Now, let’s see some sample output

run:
Please choose a number:
11
The factorial of 11 is 39916800
BUILD SUCCESSFUL (total time: 12 seconds)

run:
Please choose a number:
0
The factorial of 0 is 1
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please choose a number:
-14
Number is too low
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please choose a number:
344
The factorial of 344 is 0
BUILD SUCCESSFUL (total time: 3 seconds)

In the first output sample, I chose 11 and got 39,916,800 as the factorial (11!=39,916,800). In the second output sample, I chose 0 and got 1 as the factorial (remember than 0! is 1). In the third output sample, I chose -14 and got the Number is too low message since factorials only involve positive integers.

Now I know I mentioned that there were three possible scenarios for this program. There are actually 4. See, if you type in a number like 700 or 344 (as I did above), you will get 0 as the factorial, even though the actual factorial will be considerably larger. A 0 will be displayed if the actual factorial is greater than 9 quintillion since long doesn’t extend past 9 quintillion.

This concludes my current series of Java posts, but don’t worry, there will be more Java lessons soon! In the meantime, you can look forward to more R posts.

Thanks for reading,

Michael

Java Lesson 6: Loops

Hello everybody,

It’s Michael, and today’s lesson will be on Java loops. For those who do not know, loops repeat groups of statements in Java by executing the same actions over and over until a certain condition is met. The block of code inside the loop is called the body, while each repeat of the loop is referred to as an iteration of the loop.

Loops are important because Java programs often need to repeat actions. For instance, if you were trying to make a step-counter program, you would need a loop to increase the step-count by 1 every time a step is taken. You would ideally want to keep increasing by 1 until a certain count is reached-let’s say 10,000 steps (though you could also make your step-counter loop infinite).

There are three types of loops-while, do-while, and for-which each have their own distinct functions.

First off, I’ll discuss the for loop. Here’s a program demonstrating the use of a for loop (source code below)-For loops demo.

package javalessons;

public class JavaLessons
{

public static void main(String[] args)
{

for (int i = 2; i <= 400; i*=2)
{
System.out.println(i);
}
}
}

The basic structure of the for loop goes like this:

  • for (variable assignment; condition to end the for loop; updating action), followed by the body
  • ALWAYS remember to write your loop in this order; the compiler will throw error messages if you try to do otherwise!

In this program, I am using a for loop to calculate successive powers of 2 and display the results from top to bottom. My variable assignment-int i=2-goes first so that the loop knows the starting condition (that I am starting off with 2). The condition to end the loop-i <= 400-goes next so that the loop knows where to end (the program will keep displaying powers of 2 until a number that is either the closest to 400 or exactly 400 is reached). The updating condition-i*=2-tells the loop how to update the output (keep multiplying i by 2 until the ending condition is met).

  • By the way, you can put i = i* 2 instead of i*=2 . Either will be accepted by the compiler, the latter is just convenient shorthand. The same logic goes for addition, division, and subtraction.

Now let’s try some sample output:

run:
2
4
8
16
32
64
128
256
BUILD SUCCESSFUL (total time: 0 seconds)

The program will display all the powers of 2 that are less than 400, starting with 2 and ending with the maximum power of 2 that is less than 400-296.

Next I’ll discuss the while loop, with a demo program (source code below)-

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Pick an even numbered year: “);
int year = sc.nextInt();

int baseYear = 2100;
while (year < baseYear)
{
if (year % 4 != 0)
{
System.out.println (year);
System.out.println(“Winter Olympics Year”);
}

else
{
System.out.println (year);
System.out.println(“Summer Olympics Year”);
}

year += 4;
}
}
}

The basic structure of the while loop goes like this:

  • while (condition to keep while loop going), followed by the body.
  • Variable declarations are always included outside of the while loop; ideally just above the line where the while loop begins.

In this program, I enter an even numbered year and the program will tell me if it’s a Winter or Summer Olympics year and based on that, it will tell me the next Winter/Summer Olympics years until 2100 (since my while condition was that the loop will keep going and increasing the year by 4 until 2100 is reached).

  • If you’re wondering what the % means in Java, it means remainder. The statement if (year % 4 != 0) executes the output in the body of the code if the year entered has a remainder and isn’t divisible by 4, since Winter Olympics years occur during even numbered years that aren’t easily divisible by 4 (2006, 2010, 2014, and so on). If the year entered is divisible by 4, then Summer Olympics years would be displayed, since they occur during even-numbered leap years (which are years divisible by 4)-think 2012, 2016, 2020 and so on.

Let’s try some sample output:

Output 1:

run:
Pick an even numbered year:
2014
2014
Winter Olympics Year
2018
Winter Olympics Year
2022
Winter Olympics Year
2026
Winter Olympics Year
2030
Winter Olympics Year
2034
Winter Olympics Year
2038
Winter Olympics Year
2042
Winter Olympics Year
2046
Winter Olympics Year
2050
Winter Olympics Year
2054
Winter Olympics Year
2058
Winter Olympics Year
2062
Winter Olympics Year
2066
Winter Olympics Year
2070
Winter Olympics Year
2074
Winter Olympics Year
2078
Winter Olympics Year
2082
Winter Olympics Year
2086
Winter Olympics Year
2090
Winter Olympics Year
2094
Winter Olympics Year
2098
Winter Olympics Year
BUILD SUCCESSFUL (total time: 10 minutes 55 seconds)

I chose an even-numbered non-leap year, 2014, and the program printed out all Winter Olympics years from 2014 until the Games happening right before the year 2100 (the 2098 Winter Games).

Output 2:

run:
Pick an even numbered year:
2020
2020
Summer Olympics Year
2024
Summer Olympics Year
2028
Summer Olympics Year
2032
Summer Olympics Year
2036
Summer Olympics Year
2040
Summer Olympics Year
2044
Summer Olympics Year
2048
Summer Olympics Year
2052
Summer Olympics Year
2056
Summer Olympics Year
2060
Summer Olympics Year
2064
Summer Olympics Year
2068
Summer Olympics Year
2072
Summer Olympics Year
2076
Summer Olympics Year
2080
Summer Olympics Year
2084
Summer Olympics Year
2088
Summer Olympics Year
2092
Summer Olympics Year
2096
Summer Olympics Year
BUILD SUCCESSFUL (total time: 3 seconds)

I chose an even-numbered leap-year, 2020, and the program printed out all Summer Olympics years from the year 2020 until the Games right before the year 2100 (which would be the 2096 Summer Games).

Output 3:

run:
Pick an even numbered year:
2110
BUILD SUCCESSFUL (total time: 3 seconds)

I chose a year greater than 2100-2110 and the loop doesn’t execute at all, since my initial response exceeded the base year.

The main difference between the while and for loops is that variable declarations and updating conditions (like incrementing variables) are done either in the body of the loop or outside the loop when dealing with while, but both of those things are handled in the constructor of the loop when dealing with for.

Finally, the last loop I will discuss is the do-while loop, which is very similar to the while loop, except that the body of a do-while loop always runs at least once, while the body of a while loop might not run at all. This is because the body of the do-while loop comes before the constructor, not after.

Here’s the basic structure of the do-while loop:

  • do {body of loop} while (condition to keep loop running)
  • After each iteration, the condition is checked to see if it still holds true. As long as it does, the loop keeps running.

Here’s a sample program (code below)-Do-while loop demo:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Pick a number: “);
double number = sc.nextDouble();

double base = 1000;
do
{
number *= 1.05;
System.out.print (number + ” , “);
} while (number <= base);

}
}

In this program, I enter a number and the do-while loop will calculate 5% growth so long as the number being increased by 5% is less than the base of 1000. I could’ve written the program using a while loop, but there would’ve been a chance that the while loop might not have run at all, but the do-while loop will run at least once, which I wanted (plus I felt it was important to discuss).

Let’s try some sample output:

Pick a number:
456
478.8 , 502.74 , 527.8770000000001 , 554.2708500000001 , 581.9843925000001 , 611.0836121250002 , …..

I typed in 456, and the program kept displaying 5% increases starting with the first increase-478.8-until the program reached a number that was either 1000 or the closest possible calculation to 1000.

Now, when dealing with Java loops, one thing you should watch out when writing your code is the infinite loop, which are loops that don’t end.

Infinite loops can be caused by something as simple as a sign. Here’s an infinite loop from the do-while example in this post (code first, then output)-:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Pick a number: “);
double number = sc.nextDouble();

double base = 1000;
do
{
number *= 1.05;
System.out.print (number + ” , “);
} while (number >= base);
}
}

run:
Pick a number:
45600
47880.0 , 50274.0 , 52787.700000000004 , 55427.08500000001 , 58198.43925000001 , 61108.361212500015 , 64163.779273125016 , 67371.96823678126 , 70740.56664862033 , 74277.59498105134 , 77991.47473010392 , 81891.04846660912 , 85985.60088993958 , 90284.88093443656 , 94799.12498115838 , 99539.08123021631 , 104516.03529172714 , 109741.8370563135 , 115228.92890912917 , 120990.37535458563 , 127039.89412231492 , 133391.88882843067 , 140061.4832698522 , 147064.55743334483 , 154417.78530501208 , 162138.6745702627 , 170245.60829877583 , 178757.88871371464 , 187695.78314940038 , 197080.5723068704 , 206934.60092221393 , 217281.33096832462 , 228145.39751674086 , 239552.66739257792 , 251530.3007622068 , 264106.81580031716 , 277312.15659033303 , 291177.7644198497 , 305736.6526408422 , 321023.4852728843 , 337074.6595365285 , 353928.39251335495 , 371624.8121390227 , 390206.05274597387 , 409716.3553832726 , 430202.1731524362 , 451712.28181005805 , 474297.89590056095 , 498012.79069558904 , 522913.4302303685 , 549059.1017418869 , 576512.0568289813 , 605337.6596704304 , 635604.5426539519 , 667384.7697866495 , 700754.008275982 , 735791.7086897811 , 772581.2941242702 , 811210.3588304837 , 851770.876772008 , 894359.4206106084 , 939077.3916411388 , 986031.2612231958 , 1035332.8242843556 , 1087099.4654985734 , 1141454.4387735021 , 1198527.1607121774 , 1258453.5187477863 , 1321376.1946851755 , 1387445.0044194343 , 1456817.2546404062 , 1529658.1173724267 , 1606141.023241048 , 1686448.0744031004 , 1770770.4781232555 , 1859309.0020294185 , 1952274.4521308895 , 2049888.1747374341 , 2152382.583474306 , 2260001.7126480215 , 2373001.7982804226 , 2491651.8881944437 , 2616234.482604166 , 2747046.2067343746 , 2884398.5170710934 , 3028618.442924648 , 3180049.3650708804 , 3339051.8333244245 , 3506004.4249906456 , 3681304.646240178 , 3865369.8785521872 , 4058638.372479797 , 4261570.291103787 , 4474648.805658977 , 4698381.245941926 , 4933300.308239022 , 5179965.323650974 , 5438963.589833523 , 5710911.7693252 , 5996457.35779146 , 6296280.225681033 , 6611094.236965085 , 6941648.94881334 , 7288731.396254007 , 7653167.966066708 , 8035826.364370043 , 8437617.682588546 , 8859498.566717973 , 9302473.495053872 , 9767597.169806566 , 1.0255977028296895E7 , 1.076877587971174E7 , 1.1307214673697326E7 , 1.1872575407382194E7 , 1.2466204177751305E7 , 1.308951438663887E7 , 1.3743990105970815E7 , 1.4431189611269357E7 , 1.5152749091832826E7 , 1.5910386546424467E7 , 1.6705905873745691E7 , 1.7541201167432975E7 , 1.8418261225804623E7 , 1.9339174287094854E7 , 2.0306133001449596E7 , 2.1321439651522078E7 , 2.2387511634098183E7 , 2.3506887215803094E7 , 2.468223157659325E7 , 2.5916343155422915E7 , 2.7212160313194063E7 , 2.8572768328853767E7 , 3.0001406745296456E7 , 3.150147708256128E7 , 3.3076550936689347E7 , 3.4730378483523816E7 , 3.646689740770001E7 , 3.829024227808501E7 , 4.020475439198926E7 , 4.2214992111588724E7 , 4.432574171716816E7 , 4.654202880302657E7 , 4.8869130243177906E7 , 5.1312586755336806E7 , 5.387821609310365E7 , 5.6572126897758834E7 , 5.9400733242646776E7 , 6.237076990477912E7 , 6.548930840001808E7 , 6.876377382001899E7 , 7.220196251101995E7 , 7.581206063657095E7 , 7.96026636683995E7 , 8.358279685181947E7 , 8.776193669441044E7 , 9.215003352913097E7 , 9.675753520558752E7 , 1.0159541196586691E8 , 1.0667518256416026E8 , 1.1200894169236827E8 , 1.1760938877698669E8 , 1.2348985821583603E8 , 1.2966435112662785E8 , 1.3614756868295926E8 , 1.4295494711710724E8 , 1.5010269447296262E8 , 1.5760782919661075E8 , 1.654882206564413E8 , 1.7376263168926337E8 , 1.8245076327372655E8 , 1.915733014374129E8 , 2.0115196650928354E8 , 2.1120956483474773E8 , 2.2177004307648513E8 , 2.328585452303094E8 , 2.4450147249182487E8 , 2.5672654611641613E8 , 2.695628734222369E8 , 2.830410170933488E8 , 2.971930679480162E8 , 3.12052721345417E8 , 3.276553574126879E8 , 3.4403812528332233E8 , 3.6124003154748845E8 , 3.793020331248629E8 , 3.9826713478110605E8 , 4.181804915201614E8 , 4.390895160961695E8 , 4.6104399190097797E8 , 4.840961914960269E8 , 5.0830100107082826E8 , 5.337160511243697E8 , 5.604018536805882E8 , …

As you can see, I changed the sign in the do-while loop from “less than or equal to” to “greater than or equal to”. If you type a number greater than the base of 1000, then your loop can go on and on, as you can see here (of course, you can always hit the stop button).

Before I go, here are the answers to the number conversion problems from my previous post Java Lesson 5: Java Numbering Systems:

Binary-to-Decimal

  • 0110-6
  • 10011-19
  • 1100001-97
  • 1001001-73

Octal-to-Decimal

  • 523-339
  • 3455-1837
  • 123023-42515
  • 2346523-642387

Hexadecimal-to-Decimal

  • 4BF-1215
  • 67AC-26540
  • AF12-44818
  • 192DCC-1650124

Thanks for reading.

Michael