C++ Looping | Find output programs | Set 1

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

Program 1:

#include <iostream>

int main()
{
    int i;

    for (i = NULL; i < 5; i++) {
        std::cout << "Hello ";
    }

    return 0;
}

Output:

Hello Hello Hello Hello Hello

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.

Program 2:

#include <iostream>
using namespace std;

int main()
{
    int i;

    for (; i < 4; i++) {
        cout << "Hello ";
    }

    return 0;
}

Output:

It may not print anything on the console screen.

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.

Program 3:

#include <iostream>
using namespace std;

int main()
{
    int i = 0;
    void* ptr;

    for (; i < sizeof(ptr); i++) {
        std::cout << "Hello ";
    }

    return 0;
}

Output:

On 32-bit system: Hello Hello Hello Hello 
On 64-bit system: Hello Hello Hello Hello Hello Hello Hello Hello 

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.






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.