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);
}
Let's walk through your code and explain it. There are 2 important parts that have cout:
for (int i = 0; i < x; i += 3)
{
cout << i << " ";
}
What does this loop mean? Well
i at 0i is less than xi by 3i.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With