In this post we will discuss why and how to use the loop in any programming language, here we discuss an example in java language you can check the syntax for related language.



Why Loops?

To iterate the set of lines of code or statements in the program we use loops. In easy words, if we want to same work much time in our program so we write some code for that many times to overcome this problem we use the loops. loops repeat the peace of code as we want in our program, for example, I want to print "Hello world" once or twice we can do that simply with println. but if I want to print 100 or a thousand times then it's difficult to write if we write those lines of code and we want to change the place of "hello world" to "hello reader" then it's a very difficult and time-consuming process to change the code again and again. So, we use the loop in any programming language.

Type of loops?

there are two types of loops available in any programming language.

  • Conditional 
  • Counter
Conditional: In conditional, the loop repeats the lines of code either condition remain true. conditional have two loops while and do-while loop.
Counter: In counter, the lines of code repeat to the given number of times, this loop based on the count of repetition of code in the program.
the counter has only one loop called for loop.

while and do-while:
while first check the condition the execute the statement and do-while the first time execute the statement and then check the condition, In do while it's compulsory that the statement stub execute once.

while loop syntax:
while(condition){

//statement body

}


do-while syntax:

do{
    //statement body
}
while(condition);


for loop syntax:

for( init; condition; increment)
{
    //statement body
}


Some list of programs of loops related:

  • print the natural number
  • the sum of the natural number
  • print table of any number given by the user
  • Fibonacci number
  • print even or odd number from 1 to 100
  • print prime number up to 100
  • write the sum of the number between a given range by user (ex: 10-20  => 10+11+12+...+20)
you can try these programs and done using all the loops after completing this program you can easily solve the problem related itereation.

If you face any problem then you can mention it in the comment section. Thank You


Post a Comment

Previous Post Next Post