Aug 13, 2017 at 8:26pm UTC
Basically,
I need to write a program which would print numbers that are possible to divide by 3 from a set of [2, 16). The question is, how do I make one?
Aug 13, 2017 at 8:51pm UTC
One option is a for loop from 2 to 16 and check each number. If divisible by 3 print it.
Aug 13, 2017 at 9:05pm UTC
Another option to find the first number, and add 3 to that in a loop until you reach the highest number.
Aug 13, 2017 at 9:49pm UTC
So I tried something like that.
I want to type in three numbers and if they are all in [2, 16) have them sorted from the smallest to the biggest one.
It does not work, code is having problems at printf.
Also, I believe that while can be shortened.
I could very well use double for that but while does not allow it.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
main()
{
int x, y, z;
cout<<"Enter x, y and z: ";
vector<int> numbers;
cin>>x>>y>>z;
numbers.push_back(x);
numbers.push_back(y);
numbers.push_back(z);
do
{
cin.clear();
return main();
}while(cin.bad() || x < 2 || x>=16 || y < 2 || y>=16 || z < 2 || z >=16 || x % 3 == 1 || y % 3 == 1 || z % 3 == 1);
sort(numbers.begin(), numbers.end());
printf("%9d", numbers);
return main();
}
Last edited on Aug 13, 2017 at 9:50pm UTC
Aug 13, 2017 at 10:19pm UTC
printf is wrong. Printf has no clue what a vector is, it has to print the values only.
you want
for( I = 0; I < numbers.size(); I++)
printf("%9d\n", numbers[I]);
Last edited on Aug 13, 2017 at 10:19pm UTC
Aug 13, 2017 at 10:28pm UTC
I don't get that whole "for" thing.
No clue why would I need it and how it works.
From what I've understood, it adds 1 to i if it's 0 or less than the size of numbers.
Still no idea why would I need it in my example. I want to output what my vector contains.
Aug 13, 2017 at 10:44pm UTC
you have a vector, which is an array of 3 numbers, and you need to print 3 numbers. Printf does not understand what a vector is, and your original print statement is printing the address of the vector container, not the data inside it.
the loop gets the data inside the container and prints each item.
its the same as
printf("%d", numbers[0]); //first value
printf("%d", numbers[1]); //2nd value
printf("%d", numbers[2]); //3rd value
Last edited on Aug 13, 2017 at 10:48pm UTC