FluffyRanger
FluffyRanger

Reputation: 3

How do can I get rid of the blank lines that are created c++?


Edit: Thank you all for the quick and helpful replies. I got it working now. It was because I had to reset the counter.


I have come to ask for help as my professor is not giving me the help I need. I am new to c++ and I am trying to program a program that displays all the integers from 1 to 100 that are divisible by 6 or 7, but not both. and I have to display 5 numbers per row. I got it working except I have blank lines forming in certain areas. I don't know if it's because of how I set up the counter or what.

Here is what I got.


#include <iostream>

using namespace std;

int main()
{
    int counter = 0; // Counter for creating new lines after 5 numbers
    for (int numRange = 1; numRange <= 100; ++numRange) // Starts the loop of number 1 to 100
    {
        if (numRange % 6 == 0 || numRange % 7 == 0) // Makes the numbers divisible by 6 and 7
        {
            cout << numRange << " "; // Displays the output of the divisible numbers
            counter++; // Starts the counter

        }
        if (counter % 5 == 0) // using the counter to create new lines after 5 numbers displayed
        {
            cout << endl; // Creates a new line
        }
    }

    return 0;
}

This is what is outputted:






6 7 12 14 18


21 24 28 30 35
36 42 48 49 54

56 60 63 66 70

72 77 78 84 90
91 96 98

and this is what it's supposed to look like

  6   7 12 14 18 
21 24 28 30 35 
36 48 49 54 56 
60 63 66 70 72 
77 78 90 91 96 
98

Upvotes: 0

Views: 50

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51845

The problem that you're seeing is due to the fact that you are checking for "5 outputs" on every loop, rather than only on ones where a number has been output! So, to fix this issue (there are others), put the counter % 5 == 0 test inside the preceding if block:

    for (int numRange = 1; numRange <= 100; ++numRange) // Starts the loop of number 1 to 100
    {
        if (numRange % 6 == 0 || numRange % 7 == 0) // Makes the numbers divisible by 6 and 7
        {
            cout << numRange << " "; // Displays the output of the divisible numbers
            counter++; // Increments the counter
            if (counter % 5 == 0) // Only need this if we have done some output!
            {
                cout << endl; // Creates a new line
            }
        }
    }

Another problem is that, in this requirement:

that are divisible by 6 or 7, but not both

your code doesn't check for the "but not both" part (but that's not the 'title' question, and I'm not going to do all your homework in one fell swoop).

Upvotes: 2

Related Questions