LOOP QUESTIONS






Q1: Print numbers from 1 to 5

for(int i=1;i<=5;i++)
    cout << i << " ";

Output: 1 2 3 4 5

Q2: Print numbers from 5 to 1

for(int i=5;i>=1;i--)
    cout << i << " ";

 Output: 5 4 3 2 1

Q3: Find sum of first 5 natural numbers

int sum=0;
for(int i=1;i<=5;i++)
    sum+=i;
cout << sum;

Output: 15


Q4: Print even numbers between 1 and 10

for(int i=1;i<=10;i++)
{
    if(i%2==0)
        cout << i << " ";
}

Output: 2 4 6 8 10

Q5: Print odd numbers between 1 and 10

for(int i=1;i<=10;i++)
{
    if(i%2!=0)
        cout << i << " ";
}

Output: 1 3 5 7 9

Q6: Print square of numbers from 1 to 5

for(int i=1;i<=5;i++)
    cout << i*i << " ";

Output: 1 4 9 16 25


Q7: Print multiplication table of 2

for(int i=1;i<=10;i++)
    cout << 2*i << " ";


Output: 2 4 6 8 10 12 14 16 18 20


Q8: Find factorial of 5

int fact=1;
for(int i=1;i<=5;i++)
    fact*=i;
cout << fact;

Output: 120

Q9: Print * pattern

for(int i=1;i<=3;i++)
{
    for(int j=1;j<=i;j++)
        cout << "*";
    cout << endl;
}


Output:


*
**
***

Q10: Print number pattern

for(int i=1;i<=3;i++)
{
    for(int j=1;j<=i;j++)
        cout << j;
    cout << endl;
}

Output:

1
12
123

Q11: Predict the output

int i=1;
while(i<=5)
{
    cout << i << " ";
    i++;
}

Output: 1 2 3 4 5

Q12: Predict the output

int i=5;
while(i>0)
{
    cout << i << " ";
    i--;
}


Output: 5 4 3 2 1


Q13: Predict the output

int i=1;
do{
    cout << i << " ";
    i++;
}while(i<=5);

Output: 1 2 3 4 5


Q14: Predict the output


int i=1;
do{
    cout << i << " ";
}while(i++ < 1);

Output: 1

Q15: Use of break

for(int i=1;i<=5;i++)
{
    if(i==3)
        break;
    cout << i << " ";
}

Output: 1 2

 Q16: Use of continue

for(int i=1;i<=5;i++)
{
    if(i==3)
        continue;
    cout << i << " ";
}

Output: 1 2 4 5

Q17: How many times loop runs


for(int i=1;i<=10;i=i*2)
    cout << i << " ";

 Output: 1 2 4 8

Q18: Print characters from A to E

for(char c='A';c<='E';c++)
    cout << c << " ";

Output: A B C D E

Q19: Infinite loop with break

int i=1;
while(true)
{
    if(i==4)
        break;
    cout << i << " ";
    i++;
}

Output: 1 2 3

Q20: Find output

for(int i=0;i<5;i++)
    cout << i%2 << " ";

 Output: 0 1 0 1 0

Comments

Popular posts from this blog

C++ Programming for Beginners – Step by Step Guide

If-Else Statement in C++

Variables and Data Types in C++