do-while loop – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Fri, 29 May 2020 16:05:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.9 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg do-while loop – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Loops in Java https://shishirkant.com/loops-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=loops-in-java Fri, 29 May 2020 16:05:09 +0000 http://shishirkant.com/?p=1316 for loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form:

for (initialization; condition; update) {
statements;
}

The for loop defines three types of statements separated with semicolons ( ; ), as follows:

  • Initialization statements
  • Termination condition
  • Update clause (executable statement)

Example:

public class Myclass {
public static void main(String[] args) {
int tableOf = 25;
for (int ctr = 1; ctr <= 5; ctr++) {
System.out.println(tableOf * ctr);
}
}
}
Output:
25
50
75
100
125

The above code will execute five times. It starts with an initial value of 1 for the variable ctr and executes while ctr is less than or equal to 5. The value of ctr will increment by 1 ( ctr++ ).

The code executes for ctr values 1, 2, 3, 4, and 5. Because 6 <= 5 evaluates to false, now the for loop completes its execution without executing the set of statements.

The for loop operates as follows.

Step 1: Initialization. It sets the value of the loop control variable, which acts as a counter that controls the loop. The initialization expression is executed only once.

Step 2: Condition. This must be a Boolean expression. It tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates.

Step 3: Iteration. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression then executing the body of the loop and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.

The update clause executes after all the statements defined within the for loop body. The initialization section, which executes only once, may define multiple initialization statements. The update clause may define multiple statements. But there can be only one termination condition for a for loop.


Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution of the statement.

Example:

public class Myclass {
public static void main(String[] args) {
int num = 9;
boolean divisibleBy7 = false;
while (!divisibleBy7) {
System.out.println(num);
if (num % 7 == 0)
divisibleBy7 = true;
--num;
}
}
}

Output:
9
8
7

Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the condition is false to begin with.


Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.

Example:

public class Myclass {
public static void main(String[] args) {
int num = 9;
boolean divisibleBy7 = false;
do {
System.out.println(num);
if (num % 7 == 0)
divisibleBy7 = true;
num--;
} while (divisibleBy7 == false);
}
}

Output:
9
8
7

For-each Loop

The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through a collection of objects, sequentially from start to finish.

The general form of the for-each version of the for loop is like

for(type count_var : collection) statement-block

The type specifies the type of the variable count_var. It receives the elements from a collection one at a time and iterates from beginning to end. With each iteration of the loop, the next element in the collection is retrieved and stored in count_var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection, the type must be the same as(or compatible with) the elements stored in the collection. Thus, when iterating over arrays, type must be compatible with the element type of the array.

We can also easily iterate through nested collections using the enhanced for loop.

Example:

import java.util.ArrayList;
public class Myclass {
public static void main(String[] args) {
ArrayList myList = new ArrayList();
myList.add("Java");
myList.add("Loop");
myList.add("for-each");
for (String val : myList) {
System.out.println(val);
}
}
}

Output:
Java
Loop
for-each

One thing we should consider here is, what will happen if we try to modify the loop variable in enhanced for loop?.

The answer lies in the fact that, if we are traversing through the object or primitive type. If we’re iterating through an array of primitive values, manipulation of the loop variable will never change the value of the array being iterated because the primitive values are passed by value to the loop variable in an enhanced for loop.

When we iterate through a collection of objects, the value of the collection is passed by reference to the loop variable. Therefore, if the value of the loop variable is manipulated by executing methods on it, the modified value will be reflected in the collection of objects being iterated.

Limitation of enhanced for loop

  • It can’t be used to delete or remove the elements from a collection:- The enhanced for loop hides the iterator used to iterate through the elements of a collection, we can’t use it to remove or delete the existing collection values because we can’t call the remove method.
  • We can not iterate over multiple collection arrays in the same loop.
  • The enhanced for loop can’t be used to initialize an array and modify its elements.
]]>
1316
LOOP CONTROL STATEMENTS https://shishirkant.com/loop-control-statements/?utm_source=rss&utm_medium=rss&utm_campaign=loop-control-statements Tue, 12 May 2020 13:36:44 +0000 http://shishirkant.com/?p=145 Loop:- The process of repeated executing a block of statements is called loop. C supports three types of looping statements.  They are…

  • While Loop
  • do-while loop and
  • for-loop            

Any loop has three things. They are…

  • Initialize the index
  • Test condition
  • Update the index

1. while loop:- It is a conditional control loop statement in C language.

Syntax:- while(test condition)

                              {

                                Statements;

                                }

First the test condition is evaluated and if it is true then the statement block will be executed.  After the execution of statements the test condition is evaluated once again.

Then if it is true the statement block will be executed continuous until the test condition finally becomes false.

Program: Write a program to display natural numbers from 1 to given number using 'While Loop'
#include<stdio.h>
#include<conio.h>
void main()
{
  int n,i=1;
  clrscr();
  printf("Enter no of elements:");
  scanf("%d",&n);
  printf("Natural Numbers from 1 to %d:\n",n);
  while (i<=n)
   {
      printf("%d\t",i);
      i++;
   }
  getch();
}

2. do-while loop:- It is an alternative form of while loop.  The only difference between while and do while is the minimum number of execution of ‘while’ is ‘0’.  For minimum no of execution of ‘do-while’ is ‘1”.

Syntax:-
do
{
  Statements;
}
While(test condition);

First the statement block will be executed and then test condition will be evaluated.  If the condition is true then the statement block will be executed once again.  This process of repeated executed continuous until  the test condition finally becomes false

Program: Write a program to accept and display natural numbers, from one to given number using do-while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf(“Enter any number:”);
scanf(“%d”,&n);
printf(“Natural numbers form 1 to %d:\n”,n);
do
{
printf(“%d\t”,i);
i++;
}
while(i<=n);
getch();
}

3. for loop:- It is the most commonly used loop statement in C language. It consisting of three expressions.

Syntax:-
for(exp1; exp2; exp3)
{
Statements;
}

The first expression is used to the initialize the index, second expression is used to check whether the loop is to be continued or not, third expression is used to change the index for further iteration (increment or decrement).

For Loop

Program: Write a program to accept any number and check whether the given number is perfect or not.
*sum of factors except that number is called perfect number
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,i;
clrscr();
printf(“Enter any number:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf(“Given number is perfect”);
else
printf(“Given number is not pefect “);
getch();
}

Nested loops:-  Using a loop statement within another loop is called Nested loop.

Program: Write a program to display palindrome numbers from 1 to given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,rev;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Palindrome number from 1 to %d:\n",n);
for(i=1;i<=n;i++) 
 { 
   m=i; 
   rev=0; 
   while(m>0)
   {
     rev=rev*10+(m%10);
     m=m/10;
   }
 if(rev==i)
   printf("%d\t",i);
 }
getch();
}

Program: Write a program to generate the following pattern    

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
  {
    for(j=1;j<=i;j++)
    {
       printf("%3d",i);
    }
  printf("\n\n");
  }
getch();
}

                       

]]>
145