program stopping loop when finding specific number

Hello,

I was trying to make a small program that stops running when it either finds 1, 2, or 88. When I run this number, the console is spammed with numbers even though I tried to make it only print numbers when it is either 1, 2, or 88. What am I missing?

Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
int n=1;
int k=1;
cout << "Input number" << endl;
cin >> n;
k=n*1;
while (k != 1 || n != 1 || k != 2 || n != 2 || k != 88 || n != 88)
{

    cout << n << " " << --n;
    cout << k << " " << ++k;
 }
 cout << k << n << endl;
}
You are printing
1
2
    cout << n << " " << --n;
    cout << k << " " << ++k;

every time when loop executes.

And instead of using OR use AND coz if you use OR one of those statements will always be true and you will never exit this loop

You can try this
1
2
3
4
5
6
7
while (k != 1 && n != 1 && k != 2 && n != 2 && k != 88 && n != 88)
{
    --n;
    ++k;
 }
//print those bad boys out only after the loop
cout <<"k = "<< k << "\nn = " <<  n << endl;
Last edited on
I ended up doing this. I want the program to stop as soon as either k or n find 1, 2 , or 88. I also decided to print out the "--n;" and "++k;" because it looks kind cool getting a large number and running it through there until it finds one of the digits. The program should work now, give it a spin.

Just started a week ago, does this count as my first algorithm :3 :))))))))))!!!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()
{
int n=1;
int k=1;
cout << "Input number" << endl;
cin >> n;
k=n*1;
    while (true)
{
    cout << k << "/" << n << endl;
    cout << ++k << "/" << --n << endl;

    if (k == 1 || n == 1 || k == 2 || n == 2 || k == 88 || n == 88) {
    break;
    }
 }

 cout << k << ":" << n << endl;
}
Last edited on
Sure works man! And obviously it counts man. After my 1st lesson in school I didn't even understand what int sum; means let alone something like this!
Topic archived. No new replies allowed.