This section contains the C++ find output programs with their explanations on C++ Looping (set 1).
Program 1:
#include <iostream>
int main()
{
int i;
for (i = NULL; i < 5; i++) {
std::cout << "Hello ";
}
return 0;
}
Program 2:
#include <iostream>
using namespace std;
int main()
{
int i;
for (; i < 4; i++) {
cout << "Hello ";
}
return 0;
}
Program 3:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
void* ptr;
for (; i < sizeof(ptr); i++) {
std::cout << "Hello ";
}
return 0;
}
Answer Program 1:
Output:
Explanation:
The above code will print "Hello " 5 times.
Let's understand the program step by step.
In the above program, we declared an uninitialized variable i. And initialize variable i by NULL in the "for" loop. The value of NULL is 0. So the loop will run five times from 0 to 4, it means the condition will be valid up to 4.
Now, come to the below statement:
std::cout<<"Hello ";
In the above program, we did not include namespace std. so we have to use std with a scope resolution operator to access the cout object.
Answer Program 2:
Output:
Explanation:
The above code may not print anything, because, in the above code, we did not initialize variable i, then it will contain garbage value. So the loop will not execute, the condition will be false for the first time.
It may print something if the garbage value of i is less than 4.
Answer Program 3:
Output:
Explanation:
We compiled my program on a 32-bit system, it printed "Hello " 4 times. .
In the above program, we declared a variable i with initial value 0 and we also declared a void pointer.
As we know that the size of any type of pointer is fixed, it depends on the architecture of the system, we are using a 32-bit system, so that size of the pointer will be 4. Then the loop will execute 4 times.
need an explanation for this answer? contact us directly to get an explanation for this answer