Aditya Das Utsha
Aditya Das Utsha

Reputation: 1

Why does not while loop get reached?

input two numbers n and k. find the kth number that can not be divided by n starting from 1.problem is my while loop is not working. Here is my code:

 #include<iostream>
    using namespace std;
    int main ()
    {
        int k=0,n,l,c=0;
            cin>>n>>l;

     while(k++)
     {
         while(k%n==0)
            c++;

            if (c==l)
                cout<<k;
            else if(c>l)
                break;

     }
     }

Upvotes: 0

Views: 46

Answers (1)

john
john

Reputation: 88027

while(k++)

k has the value 0, so the value of k++ is also 0 (because you are using the post increment operator). When used in a while loop condition 0 is considered to be false, so the while loop is never entered.

I'd like to suggest how you can fix this code, but it seems rather confused. I would start again. One thing you can do is name your variables better, since the problem description says you are entering a number k it doesn't make sense to have that variable called l. It's a symptom of confused thinking I think.

It should also be clear from the problem description that you only need one loop. You are looping from 1, incrementing by 1 each time, until you find the number. So a single loop is all you need.

Upvotes: 5

Related Questions