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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.