Home > Software design >  For loop not providing correct integers? Syntax error?
For loop not providing correct integers? Syntax error?

Time:09-29

The prompt for this question is:

First, read in an input value for variable inCount. Then, read inCount integers from input and output each integer on a newline after the string "number-".

The code I'm using is

for (int inCount = 0; inCount <= 90; inCount  ) {
      cin >> inCount;
      cout << "number-" << inCount << endl;
}

The program tests this code with a few sets of numbers to see if the code works properly and isn't accidentally an IL or something, but to save space I'll just share the first one:

My output:

number-5
number-30
number-85
number-90

The correct output:

number-30
number-85
number-90
number-65
number-70

Can anyone help me with what I'm doing wrong? Thanks ahead of time.

CodePudding user response:

I think they were describing something more like this

int count = 0;
std::cin >> count;

for (int i = 0; i < count;   i)
{
    int value = 0;
    std::cin >> value;
    std::cout << "number-" << value << std::endl;
}

In other words count represents how many values to read in, then loop that many times and write out the value that was provided each iteration.

CodePudding user response:

Here is the working example using while loop.


#include <iostream>

using namespace std;

int main()
{
    std::cout<<"Hello World"<<std::endl;
    int count = 0;
    std::cin >> count;

while(count > 0)
{
    int value = 0;
    std::cin >> value;
    std::cout << "number-" << value << std::endl;
    
    --count;
}
    return 0;
}

CodePudding user response:

You are using the same variable to both drive your loop and read the user's input into. As soon as a number >= 90 is entered by the user, inCount increments inCount to a value that is > 90 causing your loop condition to break.

You need to use separate variables instead, eg:

int inCount;
cin >> inCount;

for (int i = 0; i < inCount;   i) {
    int inNumber;
    cin >> inNumber;
    cout << "number-" << inNumber << endl;
}
  • Related