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

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

mrdaliri
  • 7,148
  • 22
  • 73
  • 107
  • 2
    [The return type of `main()` must be `int`](http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main/4207223#4207223). The standard library header is named `` (no `.h`). The standard library entities are in the `std` namespace and must be qualified (e.g. `std::cout`, `std::cin`, etc.). – James McNellis Nov 28 '10 at 17:19

6 Answers6

3

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

Mariy
  • 5,746
  • 4
  • 40
  • 57
3

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

WolfgangP
  • 3,195
  • 27
  • 37
2

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

Dave McClelland
  • 3,385
  • 1
  • 29
  • 44
1

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

int a, av = 1;
johnhforrest
  • 991
  • 1
  • 8
  • 17
0

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

ronag
  • 49,529
  • 25
  • 126
  • 221
0

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;

Jaykay
  • 666
  • 1
  • 4
  • 17