0

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

3
Contributors
10
Replies
11
Views
5 Years
Discussion Span
Last Post by taumang
0

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.

0
#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 by mike_2000_17: Fixed formatting

0

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 by Arbus: n/a

0

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';
}
-1

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.
0

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 by Arbus: n/a

0

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 by Nick Evan: Fixed formatting

0

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

Edited by Arbus: n/a

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.