Showing posts with label Loop. Show all posts
Showing posts with label Loop. Show all posts

Wednesday, September 23, 2020

Apptitude Tests MCQ Short Questions On Loop BlueJ


In this page you will find short questions on BlueJ loop. These questions are MCQ  apptitude tests questions.

1. class LoopMCQ
{
    public void show()
    {
        for(int i = 0; i <= 5; i++ )
        {
            System.out.println("i = " + i );
        }
        System.out.println("End of Loop = " + i );
    }
}


A. i = 0
   i = 1
   i = 2
   i = 3
   i = 4
   i = 5
   End of Loop = 6

B. i = 0
   i = 1
   i = 2
   i = 3
   i = 4
   i = 5
   i = 6

C. Compilation Errors

D. i = 0
   i = 1
   i = 2
   i = 3
   i = 4
   i = 5

    Correct Answer: C. 'i' is declared in the for loop so scope and lifetime of the variable is within that loop only.


2.class LoopMCQ
{

    public void show()
    {
        int i = 0;
        for(;i <= 5; i++ )
        {
            System.out.println("i = " + i );
        }

        System.out.println("End of Loop = " + i );
    }
}

A.   i = 0
      i = 1
      i = 2
      i = 3
      i = 4
      i = 5
     End of Loop = 6

B. i = 0
     i = 1
     i = 2
    i = 3
    i = 4
    i = 5
    i = 6

C. Compilation Errors

D. i = 0
     i = 1
     i = 2
     i = 3
     i = 4
     i = 5

 Correct Answer: A. 

3. class LoopMCQ
{

    public void show()
    {
        int a, b;
        for(a = 1, b = 4; a < b; a++, b--)
        {
            System.out.println("a = " + a);
            System.out.println("b = " + b);
        }
    }
}

A. Compilation error 

B. a = 1
     b = 4
     a = 2
     b = 3
     a = 3
     b = 2

C. a = 1
    b = 4
    a = 2
    b = 3

D. Run Time Error

Correct Answer: C. when 'a' becomes 3 and 'b' becomes 2, the loop terminates.

4. class LoopMCQ
{
    public void show()
{
    int i=0;
    for(;;)
    {
        if(i==10)
            break;
        System.out.print(++i);
    }
    
}
}

A. 0 1 2 3 4 5 6 7 8 9 10
B.  0 1 2 3 ... infinite times
C.  1 2 3 4 5 6 7 8 9 10
D.  1 2 3 4 5 6 7 8 9

Correct Answer: C. Prefix operator is used within System.out.print() method , so value of 'i' get incremented before display. Initial value of 'i' is 0, so the display starts from 1 and when the value of 'i' is 9, the loop displays 10 (prefix operator) and in the next iteration, loop terminates.

5. class LoopMCQ
{
    public void show()
{
    int i;
    for(i=0;i<10;++i)
    {
        System.out.print("#");
        if(i>6)
            continue;
        System.out.print(i);
    }
}   

A. #0#1#2#3#4#5#6###
B. #0#1#2#3#4#5#6#7#8#9#10
C. #0#1#2#3#4#5##7#8#9#10
D. #0#1#2#3#4#5#*/

Correct Answer: A. The loop displays both '#' and '0' until 'i' becomes 7. For the values 7,8 and 9 of 'i', only the '#' symbol is displayed as contunes statement sends the control to re-initialisation statement of the loop.

6. class LoopMCQ
{
    public void show()
{
    int i,j;
    char ch='A';
 
    for(i=5;i>=1;i--)
    {
        for(j=0;j< i;j++)
          System.out.print((char)(ch+j));
        System.out.println();
    }
}
}

1.  A B C D E
    A B C D E
    A B C D E
    A B C D E
   A B C D E
        
2.  A B C D
    A B C D
    A B C D
    A B C D
        
3.  A B C D
    A B C
    A B
    A
        
4.  A B C D E
    A B C D
    A B C
    A B
    A

 Correct Answer: 4. Outer loop executes for 5 times and on each iteration of outer loop, one new line is feed. So, answers may be 1 or 4. Inner loop's iteration is gradually decreased with the iteration of outer loop. So the answer is 4.


7. class LoopMCQ
{
    public void show()
{
    int i=1;
    while(i>=10)
    {
        System.out.print(i);
        i+=1;
    }
            System.out.print("End of Loop"+i);
           System.out.println();
}
}

A. After loop i=1
B. 1,
C. After loop i=2
D. After loop i=2

Correct Answer: A. Loop will not be executed for a single time. Only display and that is from outside the loop.

8. class LoopMCQ
{
public void show()
{
int i = 1, j = 1;
for(--i , j++ ; i<10; i+=2)
{
System.out.print(i+" ");
}
}
}

A. Compilation error

B. Program never ends

C. 0 2 4 6 8

D. None of the above

Correct Answer: C.  'i' starts the loop with value 0 and gradually increases by step 2.

Output of following


1. for(i=1;i<=5;i++)
{
 System.out.println(i+ ++i);
}

12
34
56

2. int a=2,i
for(i=8;i>=1;i--)
{
 System.out.println(i+a);
i-=a
}
82
52
22

3. for(i=1;;i+=2)
{
if(i<=6)
 System.out.println(i*2);
else
break;
}

2
6
10


4. for(i=2;i<=8;i*=2)
System.out.println(i);
System.out.println(i*2);

2
4
8
32

5. for(char a=’A’=2;a<=’E’;a++)
System.out.println((char)a+1);

B
C
D
E
F


6. for(i=10;i>=1;i--)
{

System.out.println(i);
if(i<6)
break
}
10
9
8
7
6
5


7. for(i=1;i<=10;i++)
{

if(i==7)
continue;
else
System.out.print(i);
}

1 2 3 4 5 6 8 9 10


8. for(i=10;;i--)
{

if(i==0)
break;
System.out.print(i+ “ “);
}

10  9  8  7  6  5  4  3  2  1


Monday, February 8, 2010

C Programs on palindrome checking using while loop and do while loop

Using while loop we will calculate the square value of different integer numbers. This process will continue until the user wants to discontinue the loop.

#include < stdio.h >
void main ()
{
char ch;
int num, sq;
clrscr ();
printf ("Want to display the square value? (y/n)\n");
scanf ("%c", &ch);
while (ch!='n')
{
printf ("Enter an integer\n");
scanf ("%d", &num);
sq=num*num;
printf ("The square of %d", num);
printf (" is: %d\n", sq);
fflush (stdin);
printf ("Any more\n");
scanf ("%c", &ch);
}
getch ();
}


Here in this program the user can enter integer values as long as he wants. At the end of input the program will display the total value of the inputs, their average and the total number of inputs.

#include < stdio.h >
void main ()
{
char ch;
int num, sum, n;
clrscr ();
sum=0;
n=0;
printf ("Want to start? (y/n)\n");
scanf ("%c", &ch);
while (ch!='n')
{
printf ("Enter an integer\n");
scanf ("%d", &num);
sum=sum+num;
n++;
fflush (stdin);
printf ("Any more\n");
scanf ("%c", &ch);
}
printf ("The sum is: -%d\n", sum);
printf ("Average is: -%.2f\n", (float) sum/n);
printf ("Total number of input is:-%d\n", n);
getch ();
}


C program on palindrome checking


#include < stdio.h >
void main ()
{
int i, x, a, j=0;
clrscr ();
printf ("Enter the value");
scanf ("%d", &x);
a=x;
while (x>10)
{
i=x%10;
x=x/10;
j=(j*10)+i;
}
j=(j*10)+x;
if (j==a)
printf ("The number is palindrome ");
else
printf ("not");
getch ();
}

In the next exercise we can take maximum 100 inputs from the user. The user can enter any double value and the square root of the value will be displayed. User can stop the loop by entering 10000.If the user enters any negative value, then the input will not be counted and the program will ask for another input. At the end of the loop, the program will display the total number of valid inputs and the total number of negative inputs by the user.math.h is a header file which contains several math functions.sqrt () is a function of math.h file. This function takes a value (integer, float or double) and returns it's square root value.

#include < stdio.h >
#include < math.h >
void main ()
{
int count, negative;
double number, sqroot;
clrscr ();
printf ("Enter 10000 to stop\n");
count=0;
negative=0;
while (count<=100)
{
printf ("Enter a number-\n");
scanf ("%lf", &number);
if (number==10000)
break;
if (number<0)
{
printf ("The number is negative.\n");
negative++;
continue;
}
sqroot=sqrt (number);
printf ("Number=%.2lf\nSquare root = %.2lf\n", number, sqroot);
count++;
}
printf ("Total valid inputs:-%d\n", count);
printf ("Total negative inputs:-%d", negative);
getch ();
}

Program to calculate a to the power of n using while loop.

#include < stdio.h >
void main ()
{
int count, a, result, n;
clrscr ();
result=1;
count=1;
printf ("Enter two integer values:");
scanf ("%d%d", &a, &n);
while (count<=n)
{
result=result*a;
count++;
}
printf ("a= %d; n=%d; a to the power n=%d", a, n, result);
getch ();
}

do-while loop


do-while loop or do loop is an exit control type loop. That means that the condition of the loop is evaluated at the end of the loop body. In for and while loop we found that the loop control variable was evaluated against a value before the start of the loop body. In case, the condition is false, the loop body won't be executed at all. This is not the case with do-while loop.
As the condition is evaluated at the end of the loop body, the loop will be executed unconditionally for the first time. At the end of the first iteration if the condition is found true, then the loop will be executed again. Otherwise the loop will stop execution after the first iteration.
The syntax of do-while loop is: -
do
{
body of the loop
} while (condition);

Any Question ? Put Your comments

Monday, February 1, 2010

While loop in c programming language

While loop is also an entry controlled type loop in c language.  It’s working style is same as the for loop. The difference is that the three expressions (initialization, conditional and reinitialisation) are not kept in a same place like for loop. They are placed in different positions. The sequence of execution followed by a while loop is same as for loop.

The syntax of while loop is:

While (test expression)
{
Body of the loop.
Within the loop body the loop control
variable is to be reinitialized. Initialization
will be done somewhere above the control
statement
}

No semicolon after the while statement. Like for loop the control statement and the body of the loop makes one statement. In the following exercise we will see how a while loop works.

#include < stdio.h >
void main ()
{
int x=9,i=0;
/*x' is the loop control variable and it is initialized here*/
clrscr ();
while (x! =0) /*test expression*/
{
printf ("Enter any integer value ('0' for exit):");
scanf ("%d", &x);
/*Reinitialisation of 'x'*/
i++;
}
printf ("You have entered: %d", i-1);
printf (" values before breaking the loop");
getch ();
}

How many times the loop body will be executed depends on the user, the program does not decide it.

#include < stdio.h >
void main ()
{
char x;
int i=0;
clrscr ();
printf ("Do you want to see my name on screen (y/n)\n");
scanf ("%c", &x);
while (x=='y')
{
printf ("My name is ***********\n");
fflush (stdin);
printf ("Do you want to see my name again on the screen (y/n)\n");
scanf ("%c", &x);
i++;
}
if (i > 1)
{
printf ("So weak memory! took %d times to memorize my name", i);
}
getch ();
}

Any Question ? Put Your comments

Thursday, December 31, 2009

C programs on series using for loop

Evaluate the following expression S=1+ x + x^2 +x^3+....+x^n using for loop.

#include < stdio.h>
#include < stdio.h>
void main()
{
int i,sum=0,x,n;
clrscr();
printf("Enter the value of 'x' and 'n':-");
scanf("%d%d",&x,&n);
for(i=0;i < =n;i++)
{
if(i < n)
printf("%d^%d+",x,i);
else
printf("%d^%d=",x,i);
sum=sum+pow(x,i);
}
printf("\t%d",sum);
getch();
}


Program to compute exponential series ex=1+x+x2/2!+x3/3!+x4/4!
+.....+xn/n! where 'n' represents the number of terms using for loop.


#include < stdio.h>
void main()
{
float x,t,sum;
int i,n,ffact;
clrscr();
printf("Enter value for 'x' and 'n':-");
scanf("%f%d",&x,&n);
printf("\n%f\n%d",x,n);
t=1;
sum=1;
for(i=1;i < n;i++)
{
ffact=i;
t=t*x/ffact;
sum+=t;
}
printf("\nE raised to power x=%.2f",sum);
getch();
}


Write the output of the following C codes
@ for(i=3;i > =0;i--)
{
for(j=0;j < =4;j++)
{
if((j%2)==0)
break;
printf(“%d”,j);
}
if((i%2)==0)
continue;
printf(“%d”,i);
}
Ans:- 3 and 1 , both from the statement printf(“%d”,i);
@ int i=2;
unsigned j=5;
for(i=2;i >= 0;i--)
{
printf(“\nXYZ”);
}
for(j=8;j >= 0;j--)
{
printf(“\nPQR”);
}

This program in for loop  will show compile time error. As j is unsigned variable it can hold only positive value, so the
control statement for(j=8;j >= 0;j--) will be always true.


@ int I=0,x=0;
for(I=1;I < 10;++I)
{
if(I%2==1)
x+=I
else
x--;
printf(“%d”,x);
}
printf(\nx=%d”,x);
}
Output will be 1 0 3 2 7 6 13 12 21
and x=21





Any Question ? Put Your comments

Wednesday, December 9, 2009

C programs on displaying series using for loop

Evaluate the following expression using for loop S= x + 2x2 +3x3+....+nxn

#include < stdio.h>
#include < stdio.h>
void main()
{
int i,sum=0,x,n,a=0;
clrscr();
printf("Enter the value of 'x' and 'n':-");
scanf("%d%d",&x,&n);
for(i=1;i<=n;i++)
{
a++;
if(i < n)
printf("%d*%d^%d+",a,x,i);
else
printf("%d*%d^%d=",a,x,i);
sum=sum+a*pow(x,i);
}
printf("\t%d",sum);
getch();
}

Another program on for loop. Evaluate the expression sin x= x-x3/3!+x5/5!-x7/7!+.... 


#include < stdio.h>
void main()
{
float x,t,sum,d1,d2;
int i,j,n,c,counter=0;
clrscr();
printf("Enter value for 'x' and 'n':-");
scanf("%f%d",&x,&n);
sum=x;
for(i=3;i<=n;i=i+2)
{
c=1;
d1=x;
while(c
{
d1=d1*x;
c=c+1;
}
d2=1;
for(j=i;j>0;j--)
{
d2=d2*j;
}
d1=d1/d2;
counter=counter+1;
if(counter%2!=0)
sum=sum-d1;
else
sum=sum+d1;
}
printf("\nsinx=%.2f",sum);
getch();
}

Evaluate the following expression S= x + 2x^2 +3x^3+....+nx^n  using for loop.


#include < stdio.h>
#include < stdio.h>
void main()
{
int i,sum=0,x,n,a=0;
clrscr();
printf("Enter the value of 'x' and 'n':-");
scanf("%d%d",&x,&n);
for(i=1;i<=n;i++)
{
a++;
if(i < n)
printf("%d*%d^%d+",a,x,i);
else
printf("%d*%d^%d=",a,x,i);
sum=sum+a*pow(x,i);
}
printf("\t%d",sum);
getch();
}

Tuesday, December 1, 2009

C programs on combination lock, magic number, prime number using for loop

A combination lock does not have any key. Setting digits on dials open it. Suppose in our combination lock we have three dials. We will write a program to take the three numbers from the user. The numbers will be compared with the preset digits of the dials. If match is found, the lock will be opened. Otherwise the user will be given chances .If the user fails to open the lock after four chances, the program will display the combination digits.

#include < stdio.h>
void main ()
{
int first, second, third, i;
clrscr ();
for (i=0;i<4;i++)
{
printf ("enter the three numbers: -");
scanf ("%d%d%d", &first, &second, &third);
if ((first==4)&&(second==2)&&(third==0))
{
printf ("Lock open\n");
break;
}
else
{
if (i!=3)
printf ("Try again\n");
}
}
if (i==4)
printf ("The combination is:%d%d%d", 4,2,0);
getch ();
}




The following exercise will take the weight and height in Kg. and ft. respectively of ten boys as input. Then the program will calculate the total number of boys with weight greater than 80 Kg. and height is less than 5 feet 4 inches. Program on for loop.


#include < stdio.h>
void main ()
{
int i, counter=0;
float wt, ht;
clrscr ();
printf ("Enter the weight in Kg.and height in ft. of '10' boys:-\n");
for (i=0;i<10;i++)
{
scanf ("%f%f", &wt, &ht);
if ((wt>80)&&(ht<5.4))
{
counter++;
}
}
printf ("The number of boys with weight greater than 60 Kgs\n");
printf ("and height less than 5 feet 6 inches are: %d", counter);
getch ();
}
Next is an example with for loop.If the entered value is less than 0, then the value will not be displayed.
#include
void main ()
{
int x, i=0;
clrscr ();
for (i=0;i<10;i++)
{
printf ("Enter a value:-\n");
scanf ("%d", &x);
if (x<0)
continue;
printf ("The value is: -%d\n", x);
}
getch ();
}



C program on magic number

Write program using for loop to display all the magic numbers less than 500.An integer is said to be a magic number when all the digits of the number are added till a single digit is obtained is 1.


#include < stdio.h>
void main()
{
int i,j=0;
clrscr ();
for (i=1;i<=500;i=i+9)
{
printf ("%d ", i);
j++;
if (j%10==0)
printf ("\n");
}
getch ();
}

program on prime number.


#include < stdio.h>
void main ()
{
int i, j;
clrscr ();
printf ("Enter the number:\n");
scanf ("%d", &i);
for (j=2;j<=i-1; j++)
{
if (i%j==0)
break;
}
if (j==i)
printf ("The number is prime number.\n");
else
printf ("The number is not a prime number.\n");
getch ();
}




Evaluate 12+32+52=....+(2n-1)2 using ‘for’ loop


#include < stdio.h>
#include < stdio.h>
void main ()
{
int i,n,sum=1,val=3,x;
clrscr ();
printf ("Enter the value of 'n': -");
scanf ("%d", &n);
for(i=1;i<=n-1;i++)
{
x=val*val;
sum=sum+x;
val=val+2;
}
printf ("The sum is:-%d",sum);
getch ();
}


Evaluate the following expression using for loop 22+42+62+....+2n2


#include < stdio.h>
void main ()
{
int i,n,sum=0,val=2,x;
clrscr ();
printf ("Enter the value of 'n': -");
scanf ("%d", &n);
for(i=0;i<=n-1;i++)
{
x=val*val;
sum=sum+x;
val=val+2;
}
printf ("The sum is:-%d",sum);
getch ();
}

Need Your Comments.

Sunday, November 22, 2009

C programs on for loop

In this program we will use multiple statements in a for loop body. Here we will display the cube value of the numbers starting from 1 to 10.

#include < stdio.h>
void main ()
{
int num, cube;
clrscr ();
for (num=1;num<=10;num++) 

 {
 printf ("%d", num); 
cube=num*num*num; 
printf (": Cube value is: %d\n", cube);
 } 
getch (); 



The following program will display the sum of the first ten natural numbers using for loop.


 #include < stdio.h>
void main ()
{
int n,i,num;
float sum=0;
clrscr();
printf("Enter the number of elements to be entered::");
scanf("%d",&n);
for(i=0;i < 10;i++)
 
 sum=sum+i;
 printf("\nSum of the numbers divisible by 2 but not by 3 is:\t%d",sum);
 getch(); 



How we proceed in this program


We have used the variable 'sum' as a counter to store the total sum of the first ten natural numbers.’ sum' has been initialized with 0 in the main function block. If it were initialized with the same value inside the body of the for loop then there would be no syntax error but we won't get the desired result. Why? There would be a logical error.


Program to display fibonacci series


# include < stdio.h>
void main ()
{
int previous, current, next, n, i;
clrscr ();
previous=0;
current=1;
printf ("Series of how many elements?");
scanf ("%d", &n);
printf ("Fibonacci series: ");
printf ("%d", previous);
printf (" %d", current);
for (i=0;i {
next=previous + current;
printf (" %d", next);
previous=current;
current=next;
}
getch ();
}

Thursday, November 12, 2009

Loops in C programming language

In many situations we have to repeat the execution of a certain number of statements for a number of times. In such case loop can be applied. The loop continues while a condition set by the programmer is true. When the condition becomes false the loop breaks and the control passes to the statement following the loop. There are three types of loop in 'C'. for loop, while loop and do-while loop.

 A loop consists of two parts: -
1.control statement
2. Body of the loop.
 Again control statement can be of two types
i) Entry control
ii) Exit control

 In entry control the condition of the loop is tested before the loop body is executed. And on each repetition of the loop this checking is done. So it may happen that the loop body is not executed for a single time if the condition is false from the beginning. In case of exit control statement the condition is checked at the end of the loop body. So in this type of control statement the loop body is executed unconditionally for the first time. The easiest among the three is for loop.

For loop is an entry control loop. Here the condition is checked before the execution of the body. The syntax of for loop is:
 for (initialization; condition; reinitialisation) control statement
{ Body of the loop (statement /statements)
}
end of the loop body The sequence of execution followed by a for loop can be stated as:
1.initialization.
2.Conditional expression
3.Body of the loop
4.Reinitialization
5.Steps 2, 3 and 4 will repeat until the condition becomes false.

 Here all the loop control elements are gathered in one place. for is a keyword followed by parentheses that contains three expressions separated by semicolons. When the control hits the for statement, it first executes the initialization expression. In this part a variable is initialized with a value and this variable is known as loop control variable. For a for loop the initialization expression is executed only once and at the start of the loop. Then the control passes to the conditional expression and executes it. If the condition is true, the control enters the body of the loop, executes the entire body and comes back to the reinitialisation expression where it reinitializes the loop control variable. After reinitializing the control again goes to the conditional expression and executes it. If the condition is true the control again enters the loop body and repeats the process until the conditional expression becomes false. When the condition becomes false the control breaks the loop and passes to the statement following the loop body. Here is a simple program that will print the value of a variable from 0 to 9 using for loop.

 #include < stdio.h>
 void main ()
{
 int x; /* 'x' is the loop control variable.*/
 clrscr ();
for (x=0;x < 10;x++)
printf ("Value of x is: %d\n", x);
 printf ("End of loop");
 getch ();
}

  Loop control variable 'x' is initialized here with '0'.Then 0 is checked with 10 to see whether it is less than 10, found true and the loop body is executed .We will get the output as: value of x is :0 Next the control goes to the reinitialisation expression i.e. x++. Here the value of 'x' is incremented to '1' and again the conditional expression is executed with the new value of 'x'. The process of reinitialisation, execution of the conditional expression and for loop body continues until 'x' becomes 10.10<10 is false and in this stage the control breaks the loop and passes to the next statement printf ("End of loop"); So the output of this program will be: value of x is :0 value of x is: 1 value of x is: 2 value of x is: 3 value of x is: 4 value of x is: 5 value of x is: 6 value of x is: 7 value of x is: 8 value of x is: 9 End of loop One point to be noted that never put semicolon after the loop control statement. Loop control statement and the body of the loop make a single statement. If we want to display the values of 'x' from 9 to 0 then change the control statement as shown below. for (x=9;x>=0;x--)

 Any Question ? Put Your comments.

Subscribe via email

Enter your email address:

Delivered by FeedBurner