Home > OS >  How to remove the leading 0 and the last 0 in this code?
How to remove the leading 0 and the last 0 in this code?

Time:01-27

I am attempting to write a program that asks for user input of a positive integer larger than 2. The program is supposed to output all the positive integers that are smaller than the user input and that are multiples of 3. However, when running my code I noticed there are two annoying 0’s that keep appearing and aren’t supposed to be there. Any help on how to remove them or make the code better? Thank you!

#include <iostream>
using namespace std;

int get_numbers(int x) 
{

    for (int i = 0; i < x; i  = 3) 
    {
      cout << i << " ";
    }
return 0;
  
}

int main() 
{
  int integer = 0;
  cout << "Enter a positive integer larger than 2: ";
  cin >> integer;
  cout << get_numbers(integer);
}

CodePudding user response:

Lets walk through your code and explain it in english. There are 2 important parts that have cout:


for (int i = 0; i < x; i  = 3) 
{
  cout << i << " ";
}

What does this loop mean? Well

  1. Start i at 0
  2. Go while i is less than x
  3. Increment i by 3
  4. Print every i.

The important part is 1. You are starting i at 0, you will print 0. To fix this, don't start at 0! Start at a different number (probably 3 from your description of the desired behaviour).


The other cout is here:

cout << get_numbers(integer);

You are printing the return of the function get_numbers. If you look in that function, it only returns 1 thing:

return 0;

So you are going to print 0!

This function doesn't need to return anything, so just do:

void print_numbers_in_increments_of_3(int x);

And remove the cout.

CodePudding user response:

Well, the zeroes aren't just appearing.
You put them there on purpose.

First zero is in your loop - you start at 0, and print i every iteration.

You should instead start with 3:

for (int i = 3; i < x; i  = 3) 
{
  cout << i << " ";
}

Don't worry about numbers smaller than 3, the loop just won't be executed at all, which is ok, nothing will be printed.

Your second (last) zero comes from this line:

cout << get_numbers(integer);

You print the value get_numbers returns.

Except there is no reason for it to return a value, and there is no reason for you to print it.

So just remove cout << from than line, and change get_numbers to be of type void instead of int.

Also, get rid of return 0.

  •  Tags:  
  • Related