Print even numbers up to 10 using 12 as predefined variable

//this program needs to print even numbers form 2 - 10
#include <iostream>
using namespace std;

int main()
{
int count;
int x = 0;
while (x!=10)//(x!=12)
//I used 10 instead of 12 and it works fine but it
//needs to use 12 instead 10
{
x = x + 2;
cout << x << "\n""\n";
count++;
cout << endl;
}
return 0;
}
Firstly, I don't see why you need count involved. Neither do you need to use endl, given that you're already using "\n".

What you've done wrong is have x = x + 2 before cout << x.
It means that the loop continues when x = 10, but will then add 2 and cout << x.

This should work just fine:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main(){

int x = 2; 
  
  while(x < 12){              
      cout << x << "\n""\n";
      x = x + 2;       
  }

return 0;
}



Thanks georgep...it work perfectly now.
That code works ONLY for constant values,what IF the user were to supply the values and an odd number(value) were inputted?then you'll have to optimize your code farther
Okay MatriX, that sounds interesting....lets see the code for that, please
Its this
1
2
3
4
5
6
7
8
9
//include everything that starts your source code blah blah
cin>>count_to;
for(int n=0;n<=count_to;n++)
{
if (n%2==0)
cout<<n;
}
/*you input the rest of the codes here 
tada */
Last edited on
Topic archived. No new replies allowed.