Looping
Looping
Iterative Constructs in
Java
Tick () the correct option.
1. A type of loop that is usually used when the number of iteration is known.
a. for b. while
c. do-while d. None of these
Ans. a. for
2. A type of loop when the loop executes atleast once even if the test expression evaluates to
‘true’.
a. for b. while
c. do-while d. None of these
Ans. c. do-while
3. In while and do-while loops, a statement causes control to be transferred directly to the
conditional expression that controls the loop.
a. break b. pause
c. start d. continue
Ans. d. continue
4. By using you can force immediate termination of loop, bypassing the conditional expression and
any remaining code in the body of the loop.
a. switch b. break
c. continue d. default
Ans. b. break
5. What is an infinite loop?
a. A loop that functions infinitely well b. A loop that runs forever
c. A loop that never starts d. A loop that will never function
Ans. b. A loop that runs forever
6. What is the value of k after the following code fragment?
int k = 0;
int n = 12
while (k < n)
{
Section A
Answer the following questions.
1. Explain the term loop with an example.
Ans. A loop is a sequence of instruction s that is continually repeated until a certain condition is
reached.
The following program illustrates the use of for loop.
public class Loops
B. Answer as directed:
1. Convert the following segment into an equivalent do loop.
int x,c;
for(x=10,c=20;c>10;c=c-2)
x++;
Ans.
int x,c;
x=10;
c=20;
do
{
c=c-2;
x++;
}while(c>10);
SECTION B
2 3 4 5 6 n
2 3 4 5 6 n
x 2
x 3
x 4
x 5
x 6
x 7
xn
v. x − + + + + + − ... ±
2 3 4 5 6 7 n
Ans.
import java.util.*;
class Q21
{
static void i()
{
int i,x,n;
double s=0;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the values of x and n:”);
x=sc.nextInt();
n=sc.nextInt();
for(i=1;i<=n;i++)
{
s=s+Math.pow(x,i)/i;;
}
System.out.println(“Sum =”+s);
}
static void ii()
{
int i,x,n;
double s=0;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the values of x and n:”);
x=sc.nextInt();
n=sc.nextInt();
for(i=1;i<=n;i++)
{
s=s+Math.pow(x,i)/(i+1);;
}
System.out.println(“Sum =”+s);
x2 + y2
Z=
x+ y
Where, x ranges from 0 to 50 and y is to be taken as input.
Ans.
import java.util.*;
class Q47
{
static void main()
{
Scanner sc=new Scanner(System.in);
int x,y,z;