Java (Chapter 3.1) : FOR loop (Series)
For any type of consultation, query or doubt. You may contact to the following: (+91) 9804 436 193 or, debabrataguha20@gmail.com
and join the group https://www.facebook.com/groups/331231161093613/
Hope you have already practised a good amount of programs with nested if-else statements. So now we will learn how to do repetitive work in java. In the world of logic and algorithm and brain storming , the most important thing is to handle loops. Here in this chapter we will learn to form loops with the help of “FOR” keyword. Most of us think, there is not much to learn on the basic structure of FOR loop. But still I will request you to go through the basic structure of FOR loop once again. For the newcomers, it is must to focus more on this chapter, as this is the most important chapter of your programming journey. If you are good at FOR loops, then you are good at programming logics as well. Your grading as a future programmer will be decided during these for loop chapters.
We will learn total 5 Approaches in this chapter.
First approach :
First we will try to learn the structure of FOR loop. So starting with a simple program to print all the numbers from 1 to 10.. Obviously Solution should not be the like writing System.out.println() 10 times. Or to write all the numbers inside System.out.println(“1,2,3,4,5,6,7,8,9,10”).
So to solve this we will introduce a FOR loop. The basic structure of FOR loop is as follows.
FOR ( initialization ; Condition ; assignment of values for next run)
{
Loop body ..
It may consist multiple lines.
}
In FOR loop there will be exactly 2 semicolons. These semicolons separate 3 parts of FOR loop.
1st part is Initialization à means the starting values of the variables ( Initial values before we start the FOR loop)
2nd part is Condition à Similar to IF statement. Loop will iterate till when the result of this IF is TRUE. For wrong conditional statements, a FOR loop can run for infinite times. It may become a never-ending loop. So we have to be careful at the time of writing this condition.
3rd part is Assigning values for next run à By this part, we can set values for the next iteration.
Loop body à it contains few lines that would run again and again. You may write System.out.println(“HI”) here inside 2 braces. That means Multiple “HI” will be printed in the output window.
So now, to print 1-10 in the output window, we can write the following FOR statement.
class chapter3_1_program1
{
public static void main (String args[])
So let us revisit to our statements once again with a reference to the lines of above program.
As I said,
1st part is Initialization à means the starting values of the variables ( Initial values before we start the FOR loop). Here we are setting 1 to the variable “i” before we enter into FOR loop.
2nd part is Condition à Similar to IF statement. Loop will iterate till when the result of this IF is TRUE. Here the loop will run until the value of “i” is lesser than 10. Because every time program will check IF ( i <= 10 ) . IF TRUE, then it will enter into FOR loop body, otherwise it will go to the next line of the For loop. In this program, when the value of “i” will become 11, the loop will end. So as the program will also be ended, as there is no more line left after the FOR loop in this program.
3rd part is Assigning values for next run à By this part we can set values for the next iteration. In 1st run the value of i is 1, then into the next run , the value of i will be 2 and checking if it lesser than 10 or not, if TRUE, then it will print 2 and it will be incremented to 3 and so on..
Loop body à it contains few lines that would run again and again. In the above program, it will print the value of i by the line System.out.println(i). So in output window, we will be able to see 1,2,3,…10.
Using this concept, now let us calculate the output for the following code snippets:
Code 1:
5 6 7 8
Explanation:
i is starting from 5 and running till 8, each time incrementing by 1.
Code 2:
4 6 8
Explanation:
i is starting from 4 and running till 8, each time incrementing by 2.
Code 3:
4 6 8
Explanation:
Code 4:
10 8 6
Explanation:
Code 5:
Explanation:
Code 6:
10 8 6 4 2 0 -2 -4 -6 -8 -10 -12 -14 -16 -18 ……….. infinite times
Explanation:
Code 7:
3 7 11 15 19 23 27 ……….. infinite times
Explanation:
Code 8:
1 1 1 1 1 1 1 1 1 1 1 1 1 ……….. infinite times
Explanation:
Code 9:
1 2 3 4 5 6 7 8 9 10 atlast the value is 11
Explanation:
second approach:
We have already learnt the structure of FOR loop twice in this chapter. Let’s learn again with the following code printing 1 2 3 4 5 6 7 8 9 10
1st part is Initialization à means the starting values of the variables ( Initial values before we start the FOR loop). As it only holds the starting values of the variables, then it has no relation with the further iterations. So we can write the same FOR loop in following way:
i=1;
We have moved
the first part of initialization ( i=1 ) to the top of the Loop. It will carry the same
meaning and will generate the same output ( 1
2 3 4
5 6 7
8 9 10)
2nd part is Condition à Similar to IF statement, loop will iterate till when the result of this IF is TRUE, for wrong conditional statement, a FOR loop can run for infinite times, it may become a never-ending loop. One condition should always be there you can not change that.
3rd part is Assigning values for next run à By this part we can set values for the next iteration. So we can move this part to the last line of the FOR loop body. After everything is done, this line will be executed and will increment the value of i by 1.
So we have learnt to write the FOR loop in a different way. We can apply it to all the programs we learnt. Let us take the code snippet 1 again
Code 1:
5 6 7 8
It can be written again in the following way:
Code 1 alternative way:
5 6 7 8
So now try to write all the FOR loops in computer or in your mobile app and run and check the outputs.
Third approach:
Now if anyone asks to print 10 stars (*), what would you write? It would be the same code, but printing * instead of i ..
Code 10:
Output:
Code 11:
Explanation:
Code 12:
Code 13:
Explanation:
Code 13 Alternative way#1:
Explanation:
Code 13 Alternative way#2:
So we have learnt 2 things from this approach:
So please go through following 2 code snippets. It will clarify what I want to mean.
Code 14:
Code 15:
Again we are taking 2 similar types of program examples as below:
Code 16:
Code 17:
FOURTH approach:
Sometimes we are confused with the following types of program where some numbers are with positive sign and some are with negative sign.
printing the series 5 -15 45 -135 … upto 6 terms
printing the series -5 15 -45 135 … <=1000
I will always suggest to write the code for the series first by omitting the positive and negative signs. After completing the series without any sign, then only think how can we bring that signs alternatively.
Code 18:
else
{
Code 19:
else
{
FIFTH approach:
The last part of this chapter is to print the sum of the series. It is really easy to calculate the sum of any series. I am saying if we can print the series , then we can surely calculate the sum by 3 simple steps.
Step 1: introduce a variable named “sum” with value zero before we start the FOR loop. Inside this new variable “sum” , we will collect the sum.
Step 2: Inside the FOR loop body we will not print the variable , rather we will put the printable value into “sum”.
Step 3: After the loop , print the variable “sum”
Let us take code snippet number 14 and 19..
Code 14 :: calculating SUM:
Code 19 :: calculating SUM :
else
{
I can
guarantee , if you can print the series anyhow, then by applying these simple 3
steps you can find the sum of that series. These 3 steps will be applicable to
all the series programs. If not, you can mail me one example. So to print the
sum of any series, first focus on printing the same series.
Now you have to do some hands-on before moving to the next chapter. As I previously said, these FOR loop chapters will decide your strength in this programming language. You can start solving the exercise “For Series” from the above said Facebook group. In case of any confusion, you may contact me on the abovesaid mail or whatsapp number. Best of luck..
and join the group https://www.facebook.com/groups/331231161093613/
Hope you have already practised a good amount of programs with nested if-else statements. So now we will learn how to do repetitive work in java. In the world of logic and algorithm and brain storming , the most important thing is to handle loops. Here in this chapter we will learn to form loops with the help of “FOR” keyword. Most of us think, there is not much to learn on the basic structure of FOR loop. But still I will request you to go through the basic structure of FOR loop once again. For the newcomers, it is must to focus more on this chapter, as this is the most important chapter of your programming journey. If you are good at FOR loops, then you are good at programming logics as well. Your grading as a future programmer will be decided during these for loop chapters.
We will learn total 5 Approaches in this chapter.
First approach :
First we will try to learn the structure of FOR loop. So starting with a simple program to print all the numbers from 1 to 10.. Obviously Solution should not be the like writing System.out.println() 10 times. Or to write all the numbers inside System.out.println(“1,2,3,4,5,6,7,8,9,10”).
So to solve this we will introduce a FOR loop. The basic structure of FOR loop is as follows.
FOR ( initialization ; Condition ; assignment of values for next run)
{
Loop body ..
It may consist multiple lines.
}
In FOR loop there will be exactly 2 semicolons. These semicolons separate 3 parts of FOR loop.
1st part is Initialization à means the starting values of the variables ( Initial values before we start the FOR loop)
2nd part is Condition à Similar to IF statement. Loop will iterate till when the result of this IF is TRUE. For wrong conditional statements, a FOR loop can run for infinite times. It may become a never-ending loop. So we have to be careful at the time of writing this condition.
3rd part is Assigning values for next run à By this part, we can set values for the next iteration.
Loop body à it contains few lines that would run again and again. You may write System.out.println(“HI”) here inside 2 braces. That means Multiple “HI” will be printed in the output window.
So now, to print 1-10 in the output window, we can write the following FOR statement.
class chapter3_1_program1
{
public static void main (String args[])
{
int i;
for
( i=1 ; i <=10 ; i=i+1 )
{
System.out.println
( i );
}
}
}So let us revisit to our statements once again with a reference to the lines of above program.
As I said,
1st part is Initialization à means the starting values of the variables ( Initial values before we start the FOR loop). Here we are setting 1 to the variable “i” before we enter into FOR loop.
2nd part is Condition à Similar to IF statement. Loop will iterate till when the result of this IF is TRUE. Here the loop will run until the value of “i” is lesser than 10. Because every time program will check IF ( i <= 10 ) . IF TRUE, then it will enter into FOR loop body, otherwise it will go to the next line of the For loop. In this program, when the value of “i” will become 11, the loop will end. So as the program will also be ended, as there is no more line left after the FOR loop in this program.
3rd part is Assigning values for next run à By this part we can set values for the next iteration. In 1st run the value of i is 1, then into the next run , the value of i will be 2 and checking if it lesser than 10 or not, if TRUE, then it will print 2 and it will be incremented to 3 and so on..
Loop body à it contains few lines that would run again and again. In the above program, it will print the value of i by the line System.out.println(i). So in output window, we will be able to see 1,2,3,…10.
Using this concept, now let us calculate the output for the following code snippets:
Code 1:
for
( i=5 ; i <=8 ; i=i+1 )
{
System.out.print
( i );
}
Output:5 6 7 8
Explanation:
i is starting from 5 and running till 8, each time incrementing by 1.
Code 2:
for
( i=4 ; i <=8 ; i=i+2 )
{
System.out.print
( i );
}
Output:4 6 8
Explanation:
i is starting from 4 and running till 8, each time incrementing by 2.
Code 3:
for
( i=4 ; i <=9 ; i=i+2 )
{
System.out.print
( i );
}
Output:4 6 8
Explanation:
i is starting
from 4 and running till 9, each time incrementing by 2. The output will be same
as code snippet 2.
Code 4:
for
( i=10 ; i >=5 ; i=i-2 )
{
System.out.print
( i );
}
Output:10 8 6
Explanation:
i is starting
from 10 and running till 5, each time decrementing by 2. Focus on the condition
part. It will be greater than of something when you are decreasing. See next
code snippet to find what will happen in case of wrong conditions.
Code 5:
for
( i=10 ; i <=5 ; i=i-2 )
{
System.out.print
( i );
}
Output:Explanation:
Nothing will
be printed as i is starting from 10 and before entering into the loop body, it
is checking if the value of i is lesser than 5 or not. But 10 is not lesser
than 5, so condition is FALSE and control would not be inserted into FOR loop
body.
Code 6:
for
( i=10 ; i <=10 ; i=i-2 )
{
System.out.print
( i );
}
Output:10 8 6 4 2 0 -2 -4 -6 -8 -10 -12 -14 -16 -18 ……….. infinite times
Explanation:
This program
will print infinite numbers and will keep running until we forcefully stop it. Because
i is starting from 10 and before entering into the loop body everytime it is
checking if the value i is lesser than or equals to 10 or not. It is always lesser
than equals to 10, so the values will be kept printing.
Code 7:
for
( i=3 ; i >= 2 ; i=i + 4 )
{
System.out.print
( i );
}
Output:3 7 11 15 19 23 27 ……….. infinite times
Explanation:
This program
will print infinite numbers and will keep running until we forcefully stop it. Because
i is starting from 3 and before entering into the loop body everytime it is
checking if the value i is greater than 2 or not. It is always greater than
equals to 2, so the values will be kept printing.
Code 8:
for
( i=1 ; i <= 10 ; i = i + 0 )
{
System.out.print
( i );
}
Output:1 1 1 1 1 1 1 1 1 1 1 1 1 ……….. infinite times
Explanation:
Here the value
of i will be starting from 1. As the value of i is not increasing, it will
always be satisfying the condition i <= 10. So this loop will be an infinite loop again.
Code 9:
for
( i=1 ; i <= 10 ; i=i + 1 )
{
System.out.print
( i );
}
System.out.print
( “atlast the value is “ + i );
Output:1 2 3 4 5 6 7 8 9 10 atlast the value is 11
Explanation:
Concentrate on
the last line. After the loop the value of i is 11.. It has to be.. Because to
put an end of the loop, the value of i should reach to 11. So that the condition
will be failed and the loop will end. So if we try to print the value of i outside
of the loop, it will show 11.
second approach:
We have already learnt the structure of FOR loop twice in this chapter. Let’s learn again with the following code printing 1 2 3 4 5 6 7 8 9 10
for
( i=1 ; i <= 10 ; i=i + 1 )
{
System.out.print
( i );
}
1st part is Initialization à means the starting values of the variables ( Initial values before we start the FOR loop). As it only holds the starting values of the variables, then it has no relation with the further iterations. So we can write the same FOR loop in following way:
i=1;
for
( ; i <= 10 ; i=i + 1 )
{
System.out.print
( i );
}
2nd part is Condition à Similar to IF statement, loop will iterate till when the result of this IF is TRUE, for wrong conditional statement, a FOR loop can run for infinite times, it may become a never-ending loop. One condition should always be there you can not change that.
3rd part is Assigning values for next run à By this part we can set values for the next iteration. So we can move this part to the last line of the FOR loop body. After everything is done, this line will be executed and will increment the value of i by 1.
i=1;
for
( ; i <= 10 ; )
{
System.out.print
( i );
i
= i + 1 ;
}
So we have learnt to write the FOR loop in a different way. We can apply it to all the programs we learnt. Let us take the code snippet 1 again
Code 1:
for
( i=5 ; i <=8 ; i=i+1 )
{
System.out.print
( i );
}
Output:5 6 7 8
It can be written again in the following way:
Code 1 alternative way:
i
= 5 ;
for
(; i <=8 ; )
{
System.out.print
( i );
i
= i + 1 ;
}
Output:5 6 7 8
So now try to write all the FOR loops in computer or in your mobile app and run and check the outputs.
Third approach:
Now if anyone asks to print 10 stars (*), what would you write? It would be the same code, but printing * instead of i ..
Code 10:
for
( i=1 ; i <= 10 ; i=i + 1 )
{
System.out.print
( “ * ” );
}
Output:
* * * * * * * * * *
Explanation:
Simply, loop is
iterating 10 times and is printing 10 stars.
Code 11:
for
( i=1 ; i <= 10 ; i=i + 1 )
{
System.out.print
( “ # ” );
}
Output:
# # # # # # # # # #
Explanation:
Simply the
loop is iterating 10 times and printing 10 hashes (#).
k=100;
for
( i=1 ; i <= 10 ; i=i + 1 )
{
System.out.print
( k );
}
Output:
100 100 100 100 100
100 100 100 100 100
Explanation:
Simply the
loop is iterating 10 times and printing the value of K 10 times. Means the loop
will print the value 100 ten times.
k=100;
for
( i=1 ; i <= 10 ; i=i + 1 )
{
System.out.print
( k );
k
=k + 5;
}
Output:
100 105 110 115 120
125 130 135 140 145
Explanation:
Simply the
loop is iterating 10 times and printing the value of K 10 times. At first, the
loop will print the value 100 and the value of K will be incremented to 105. Then
it will print 105 and the value will be incremented to 110 and so on.
Code 13 Alternative way#1:
k=100;
i=1;
for
( ; i <= 10 ; )
{
System.out.print
( k );
k
= k + 5;
i
= i + 1;
}
Output:
100 105 110 115 120
125 130 135 140 145
We can follow
the process of breaking FOR loop here as well. We have just learnt this process
during our 2nd approach of FOR loop in this chapter itself. I think
you can remember this approach.
Code 13 Alternative way#2:
for
( i =1 , k = 100 ; i <= 10 ; i = i + 1 , k = k + 1 )
{
System.out.print
( k );
}
Output:
100 105 110 115 120
125 130 135 140 145
Explanation:
We can follow
the reverse process of breaking FOR loop now. I think you are getting the
reverse approach as well. Here converting a BROKEN FOR loop into a Concrete FOR
loop once again. Please note that still there are 2 semicolons. Initialization statements
are separated by comma ( , ) and similarly the assignment statements are also separated
by comma ( , )
So we have learnt 2 things from this approach:
- We can put multiple statements separated by comma as initialization and assignments.
- We can print 10 terms or n terms of a series. Means we can print a series without giving the limit.
If you look
closely, we have not put any limit 145 for the last series. We are printing 10
terms only by the following FOR loop.
for
( i =1 , k = 100 ; i <= 10 ; i = i + 1 , k = k + 1 )
{
System.out.print
( k );
}
Number of
terms are being controlled by the variable i whereas the values are being hold
by the variable k.
So please go through following 2 code snippets. It will clarify what I want to mean.
Code 14:
//printing
the series 7 11 15 19 23 ….. <=50
for
( i=7; i <= 50 ; i=i + 4 )
{
System.out.print
( i );
}
Output:
The above
series will surely be terminated by 50. It may end at 47 or 48 or 49 , I have
not calculated the exact value.. But it will be surely on or before 50.
Code 15:
//printing
the series 7 11 15 19 23 ….. 10 terms
for
( k = 7 , i = 1 ; i <= 10 ; i = i + 1 , k = k + 4 )
{
System.out.print
( k );
}
Output:
If we try to
print only 10 terms of this series, then we can calculate the 10th term
on paper and then put the limit at FOR loop condition. But it will be wiser to
use the logic of variable K that we have previously used in code snippet 14
alternative way #2. Here the FOR loop will be iterating 10 times with the help
of variable i . But in output window, the value of k will be printed and k will
be updated accordingly to print the desired series.
Again we are taking 2 similar types of program examples as below:
Code 16:
//printing
the series 5 15 45 …
<=1000
for
( i = 5 ; i <= 1000 ; i = i * 3 )
{
System.out.print
( i );
}
Code 17:
//printing
the series 5 15 45 … 6 terms
for ( k = 5 , i = 1 ; i <= 6 ; i = i +1 , k = k *3 )
for ( k = 5 , i = 1 ; i <= 6 ; i = i +1 , k = k *3 )
{
System.out.print
( k );
}
FOURTH approach:
Sometimes we are confused with the following types of program where some numbers are with positive sign and some are with negative sign.
printing the series 5 -15 45 -135 … upto 6 terms
printing the series -5 15 -45 135 … <=1000
I will always suggest to write the code for the series first by omitting the positive and negative signs. After completing the series without any sign, then only think how can we bring that signs alternatively.
Code 18:
//printing
the series 5 -15 45
-135 … 6 terms
for
( k = 5 , i = 1 ; i <= 6 ; i = i +1 ,
k = k *3 )
{
if (i % 2 == 0 )
{
System.out.print
( -k );
}else
{
System.out.print
( k );
}
}
Explanation:
If you look
closely, if we omit positive and negative signs, it is similar with the code
snippet number 17. So for that reason FOR loop statements are same for both
code 17 and 18. Extra thing is the IF-ELSE part inside the FOR loop body. On the
basis of some condition, sometimes it is positive, sometimes it is negative. Here
the condition is , number is negative in each 2nd , 4th,
6th term. Means k will be negative when i is an even number.
Code 19:
//
printing the series -5 15 -45 135
… <=1000
for
( a=1 , i = 5 ; i <= 1000 ; i = i * 3
, a = a + 1 )
{
if (a % 2 == 0 )
{
System.out.print
( i );
}else
{
System.out.print
( -i );
}
}
Explanation:
If you look
closely, if we omit positive and negative signs, the series is similar with the
code snippet number 16. So for that reason, FOR loop line is almost same for both
code 16 and 19. Extra thing is the IF-ELSE part inside the FOR loop body. On the
basis of some condition, sometimes it is positive, sometimes it is negative. Here
the condition is , number is positive in each 2nd , 4th,
6th term. So to count the terms, we have introduced an extra
variable named “a” which is just counting the number of terms. Means “i” will
be positive when “a” is an even number.
FIFTH approach:
The last part of this chapter is to print the sum of the series. It is really easy to calculate the sum of any series. I am saying if we can print the series , then we can surely calculate the sum by 3 simple steps.
Step 1: introduce a variable named “sum” with value zero before we start the FOR loop. Inside this new variable “sum” , we will collect the sum.
Step 2: Inside the FOR loop body we will not print the variable , rather we will put the printable value into “sum”.
Step 3: After the loop , print the variable “sum”
Let us take code snippet number 14 and 19..
Code 14 :: calculating SUM:
//printing
the SUM of the series 7 11 15 19 23 ….. <=50
int
sum=0; //this is step 1, introducing a
new variable SUM with zero
for
( i=7; i <= 50 ; i=i + 4 )
{
//
System.out.print ( i );
sum
= sum + i; // instead of printing i ,
putting the value into sum
}
System.out.print
( “the sum is “ + sum ); // this is step 3, printing the sum
Code 19 :: calculating SUM :
//
printing the SUM of the series -5 15 -45 135
… <=1000
int
sum = 0 ;
for
( a=1 , i = 5 ; i <= 1000 ; i = i * 3
, a = a + 1 )
{
if (a % 2 == 0 )
{
sum
= sum + i ;
}else
{
sum
= sum + (- i ) ;
}
}
System.out.print
( “the sum is “ + sum );
Now you have to do some hands-on before moving to the next chapter. As I previously said, these FOR loop chapters will decide your strength in this programming language. You can start solving the exercise “For Series” from the above said Facebook group. In case of any confusion, you may contact me on the abovesaid mail or whatsapp number. Best of luck..
Comments
Post a Comment