开发者

C++ while problem

开发者 https://www.devze.com 2023-01-27 12:49 出处:网络
I have a problem with while loop in c++. I write this code: #include <iostream.h> main () { int a, av = 0;

I have a problem with while loop in c++. I write this code:

#include <iostream.h>
main () {
    int a, av = 0;
    cout << "Enter a number: ";
    cin >> a;

        for (int i = 1; i <= a; i++) {
            while (av == 1) {
                cout << "abc" << a / i;
                if (a % i == 0) {
                    av = 1;
          开发者_如何学C      }
            }
        }
}

This program should print "abc", but it doesn't print any thing. I know the problem is in while section, but how can I fix it? Thanks ..


It should be while (av == 0) to get in the inner loop.


av is 0 when you get to the while loop so the condition av==1 is always false.


At the beginning, av is equal to 0. Its value never gets changed, because the while loop is never entered (since av is NOT equal to 1).


You never initialize av to 1. Try changing your first statement to:

int a, av = 1;


Well the while loop will never be entered since av = 0 and the loop predicate is av == 1.


Two cases when abc would not be printed:

1 : The user enters 0 as the input for 'a' - The for loop is exited in the first loop itself as i would never be 0.

2 : initial value of av is 0 and and while (av==1) would never be true irrespective of the number of times the 'for' loop is run

to print abc:

Set av == 1 initially or make sure user enter a number > 0 always

OR

change the code as follows: while (av == 1) { cout << "abc" << a / i; } if (a % i == 0) av = 1;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号