x =5
while(x<7)
print the value of x
x=x+1
while(x>2)
print the value of x
x=x-2
so i was thinking that the output of the program will be 5677753 but my program is against my opinion so i want to know the right output

#include <iostream>
using std::endl;
using std::cin;
int main()
{
int x = 5;
while(x < 7)
{
std::cout<<" value of x."<<x<<'\n';
x=x+1;
}
while(x > 2)
{
std::cout<<" value of x."<<x<<'\n';
x=x-2;
cin.get();
}
return 0;
}

How were you expecting 7 to be printed three times when the first loop stops upon reaching 7 and the second loop decrements it immediately after printing?

My question remains the same. Why do you think 7 is printed twice when the first loop stops before processing 7, and the second loop decrements it immediately after printing? Run this instead, the first loop stops when x reaches 7:

#include <iostream>

int main()
{
    int x = 5;
    while(x < 7)
    {
        std::cout<<"first loop value of x."<<x<<'\n';
        x=x+1;
    }
    while(x > 2)
    {
        std::cout<<"second loop value of x."<<x<<'\n';
        x=x-2;
    }
}

Edited 5 Years Ago by Narue: n/a

what if the statement is in this form
x=5
while(x<7)
print the value of x
x=x+1
print the value of x
while(x>2)
print the value of x
x=x-2

I'm mentally making the code reasonable by applying braces, but in that case you would print 7 twice. It would be equivalent to this:

#include <iostream>

int main()
{
    int x = 5;

    while(x < 7)
    {
        std::cout<<"first loop value of x."<<x<<'\n';
        x=x+1;
    }

    std::cout<<"outside loop value of x."<<x<<'\n';

    while(x > 2)
    {
        std::cout<<"second loop value of x."<<x<<'\n';
        x=x-2;
    }
}

Thanks that is what i was looking for,it is just that my question were not clear

This article has been dead for over six months. Start a new discussion instead.