×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

C++ Looping | Find output programs | Set 2

This section contains the C++ find output programs with their explanations on C++ Looping (set 2).
Submitted by Nidhi, on June 06, 2020

Program 1:

#include<iostream>
using namespace std;

int main()
{	
	for(;;)
	{
		cout<<"Hello ";
	}
		
	return 0;
}

Output:

Hello Hello .... Infinite loop

Explanation:

In the above code, the loop will execute infinitely. In C++, if we did not mention any condition in the loop then I will consider it as a true. Then the condition will never false, so the loop will never terminate. Then the "Hello" will print infinite times on the console screen.

Program 2:

#include <iostream>
using namespace std;

int main()
{
    for (; EOF;) {
        cout << "Hello ";
    }

    return 0;
}

Output:

Hello Hello .... Infinite loop

Explanation:

In the above code, the loop will execute infinitely. In the above code w mentioned EOF in place of loop condition, In C++, EOF is a predefined MACRO, the value of EOF is -1. And as we know that, In C++ any non-zero value is considered as a true for conditions. so the loop will never terminate. Then the "Hello" will print infinite times on the console screen.

Program 3:

#include <iostream>
using namespace std;

int main()
{
    int i = 0;
    int a = 10, b = 10;

    while (a > b ? 0 : 1) {
        i++;
        cout << "Hello ";
        if (i > 2)
            break;
    }
    return 0;
}

Output:

Hello Hello Hello

Explanation:

Here, we declared three local variables i, a, and b with initial values 0, 10, 10 respectively. Here we use a while loop.

Let's understand the condition of a while loop.

while(a>b?0:1)

In the while loop, we used a ternary operator, here condition (10>10)  is false then it returns 1, so the condition for while loop will be true always.

In the body of the while loop we used a counter variable i and cout<<"Hello " to print "Hello " on the console.

Here "Hello " will be printed 3 times, because the loop will terminate when the value of the variable i becomes 3 that is greater than 2.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.