i want to know the sequence of values tobe printed out by this algorithm

count = 0
while(count<2)
print the value of x
x=x+2
else print the value of x

my answers are as follows
0;2
i need clarity

You need to clarify the algorithm first. Are count and x the same entity? Because if not, you need to specify what the starting value for x is and update count in the loop or it will run infinitely. Is the else clause tied to your while loop such that it runs when the loop ends, or do you have an if statement somewhere that is missing?

Assuming the former in both cases, your answer is correct.

#include<iostream>
using namespace std;
int main ()
{
    x=0;
    while(x<2)
        cout<"x">endl;
    x=x+1;
    else cout<"x">endl;
    return 0;
}

i was trying to prove it but i got some errors.please note thet i am a new use of c++

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Hello taumang,
Your if statement is missing and i think you might have got the error "Misplaced else" and your while loop will print x infinite times (x=x+1 will not be done at all). cout is given as cout<< in c++.

Edited 5 Years Ago by Arbus: n/a

This is equivalent to your original algorithm.

#include <iostream>

int main()
{
    int x = 0;

    while (x < 2) {
        std::cout<< x <<'\n';
        x = x + 2;
    }
    
    std::cout<< x <<'\n';
}

thanks but i need else statement on the program so that the program will be able to print 0;2;2

Comments
Horrible job explaining the algorithm then.

You should have the if statement first. For example if x<2 then it should print the value of x and then increment it. Here is an example of if else block.

int x=0;
if(x<2)
{cout<<x<<"\n";
 x=x+2;
}
else
{cout<<x<<"\n";
}

Edited 5 Years Ago by Arbus: n/a

just have a look on this i got an error and i am non able to deal with it

#include <iostream> 
using namespace std;
int main()
{
    int x = 0; 
    while (x < 2)
    {      
        std::cout<< x <<'\n'; 
        x = x + 2; 
    }
    std::cout<< x <<'\n';
if(x<2)
{
    cout<<x<<"\n";
    x=x+2;
}
else
{
    cout<<x<<"\n";
    return 0;
}

Edited 3 Years Ago by Nick Evan: Fixed formatting

You have given return(0) in the else part. Give it after else part.
use code tags

Edited 5 Years Ago by Arbus: n/a

okay thanks for all your advises now my program is giving the right output that i was looking for

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