'How to remove the leading 0 and the last 0 in this code?
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);
}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lev M. |
