Reputation: 3
So the main task is to find all numbers divisible by 7 between 0 - 100 then sort them in descending order without using an array. I'm just starting c++ and one of my first lab tasks was this, however when I finished it I was told that I shouldn't have used an array. I'm now curious as to how to do so otherwise. The code here only finds the numbers divisible by 7 and naturally displays them in an ascending sort.
I'm unsure how I would sort them without storing the value in an array then changing switching the values that way.
#include <iostream>
using namespace std;
int main() {
for( int i = 0; i <= 100; i++){
if(i%7 == 0){
//Display every integer divisible by 7
cout << i << endl;
}
}
return 0;
}
Upvotes: 0
Views: 322
Reputation: 2076
Bling it like its 2020 .. (You will get great grades ;-) )
#include <iostream>
using namespace std;
int main() {
int i=101;
while(--i)i%7?cout:cout<<i<<endl;
}
Upvotes: 0
Reputation: 9786
Just reverse the for loop:
for( int i = 100; i >= 7; i--){ //There is no integer lower than 7 that is divisible by 7
if(i%7 == 0){
cout << i << endl;
}
}
Upvotes: 1
Reputation: 311
What you can do is start at max and go down from there; as follows:
for(int i = 100; i >= 0; i--){
if(i % 7 == 0){
cout << i << endl;
}
}
Upvotes: 0
Reputation: 49803
Change your loop to go in descending order; then you won't have to sort anything.
Upvotes: 0
Reputation: 4203
One approach is to find the lagest number divisible by 7 (here, 98) and just continue removing 7 to it until you run across the lowest boundary.
Upvotes: 2