user2950439
user2950439

Reputation: 19

Loop in visual studio

We are supposed to create a program that accepts 15 telephone numbers. All numbers consist of 8 digits. Fixed lines start with 17 and mobile lines start with 39. Prog should cout the number of fixed and mobile lines. Also, prog should stop when the user enters a negative number.

Here is my code:

#include <iostream>
using namespace std;
void main ()
{

int n, c=1, cm=0, cf=0;

cout << "Enter a telephone number or enter a negative number to stop ";

while (c <= 15){
    cin >> n;

    if (n/1000000 == 39){
        c++;
        cm++;
    }

    else if (n/1000000 == 17){
        c++;
        cf++;
    }

    else cout << "Wrong telephone number" << endl;

    cout << "Enter the next telephone number or enter a negative number to stop ";
    cin >> n;

}

cout << "The number of fixed lines is " << cf << endl;
cout << "The number of mobile lines is " << cm << endl;

system ("PAUSE");

}

I have two problems:

  1. I don't know how to end the program when the user enters a negative number.

  2. Program doesn't cout "Enter the next telephone number or enter a negative number to stop " after entering the second number.

Upvotes: 1

Views: 665

Answers (2)

Iłya Bursov
Iłya Bursov

Reputation: 24146

  1. to stop loop when user enters negative number you need to use break statement
  2. check how your logic works: at the end of the loop you're output string, ask for number and go to the start of loop, where you're asking for number again

consider following code:

int n, c=1, cm=0, cf=0;
while (c <= 15) {
    std::cout << "Enter the next telephone number or enter a negative number to stop ";
    std::cin >> n; // output prompt and ask for number only once per loop iteration
    if (n <= 0)
        break; // ends while loop if user entered incorrect value
    if (n/1000000 == 39)
        cm++, c++;
    else if (n/1000000 == 17)
        cf++, c++;
    else
        std::cout << "Wrong telephone number" << std::endl;
}
std::cout << "The number of fixed lines is " << cf << std::endl;
std::cout << "The number of mobile lines is " << cm << std::endl;

Upvotes: 3

Enigma
Enigma

Reputation: 1717

Problem 1:

  • you could check for negative and use the keyword break to exit the while loop.

Problem 2:

  • place: cout << "Enter a telephone number or enter a negative number to stop "; within the while loop.

Upvotes: 0

Related Questions