Sorting output numbers without an array - c++

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;
}

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.

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;
}
}

Change your loop to go in descending order; then you won't have to sort anything.

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;
}
}

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;
}

Related

Program not loading array correctly

Question at hand: Write a function primeTableInRange to generate a table to show whether each number in the range from startNum up to endNum is a prime number. When the number is not a prime number, we will only show a ‘*’. When the number is a prime number, we will show the number.
My code:
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum;
int userarray[arraysize];
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<arraysize;i++)
{
bool prime=true;
for (int r=2;r*r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}
Issue is it doesn't start at "startNum" and doesn't end at "endNum". It actually goes from 0 to arraysize. Also it calculates 4 as a prime number. What am I missing here?
Be careful! Arrays always start at 0 and end at arraysize in your case. You cannot have arbitrary indexing. You could do the following:
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=0;i<arraysize;i++)
userarray[i]= startNum+i;
Also, since we start at 0 you need to add +1 in ´arraysize´ to include ´endNum´ in your ´userarray´
try to change this
from:
for (int r=2;r*r<i;r++)
to
for (int r=2;r<i;r++)
At nowhere in your printing function do you even recognize your array. You simply begin looping numbers up to your array size. If you took the array out of your function arguments it would still work, so why are you including it? Your for loops just disregard any values in your array and begin looping from 2 arbitrarily.
As for why 4 is calculated as a prime number, it is because when your second loop starts it sees that 2*2=4 and therefore not less than 4, which is the number you are testing. This results in it skipping over the loop and never setting prime to false. Make the condition in the second for loop to <= or else any perfect square with no other factors will be labelled as prime, such as 25.
Also on a side note, how did this ever compile? You use a dynaimc variable to initiate an array size. That doesn't work and when I tried to run your code to see the output I got errors. Try using std::vector<int>. When you use the for loop to fill the vector you use the values as indexes which is completely and utterly wrong. This is when you should loop from zero to your arraysize because that it the address within the array. You also include unecessary headers like ctime and cmath, and have if(true) in your code for no reason.
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=startNum;i<endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<=arraysize;i++)
{
bool prime=true;
for (int r=2;r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}
The declaration for the array (int userarray[arraysize];) is illegal, the array bounds need to be known at compile time. This should not even compile, or it produces a zero-size array.
Afterwards, you randomly access unallocated memory, whcih is UB
Change
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
To
int userarray[1];
int arraysize = endNum - startNum;
userarray[arraysize];
Also, add a return value to the primetableinarray function.
Here is the correct program .
#include <iostream>
using namespace std;
void primetableinarray(int low, int high) ;
int main()
{
int low, high, i, flag;
cout<< "Enter low numbers ";
cin>> low;
cout<< "Enter high numbers ";
cin>>high;
cout<< "Prime numbers between " << low << "and are: " << high <<endl;;
primetableinarray(low, high);
return 0;
}
void primetableinarray(int low, int high) {
int i, flag;
while (low <= high)
{
flag = 0;
for(i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout<< low <<endl;
else
cout<< "*" <<endl;
++low;
}
}
Output :
Enter low numbers 1
Enter high numbers 10
Prime numbers between 1and are: 10
1
2
3
*
5
*
7
*
*
*
There are copule of problem in your code :
int arraysize = endNum - startNum;
int userarray[arraysize];
How does it compile , it will be compilation error. you can allocate memory dynamically and use it .
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
this is wrong i = startNum and arraysize = arraysize +1 if you are comparing " i<=endNum " .
Correct way is :
for (int i=0;i<=endNum;i++)
userarray[i]= startNum++;

C++ Random Number Generator in Array

I'd like to write a program in C++, which will present 6 random numbers from 1 to 54. Below you could find the code. For some strange reason, when I run the program, I sometimes stumble upon an output like this:
Bugunku sansli loto sayiniz: 17 1 12 32 33 3418568
I couldn't figure out why the last number ignores my rule.
Any help would be appreciated.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 6; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
I couldn't figure out why the last number ignores my rule.
Because the last number accessed in the for loop is getting out of the bound of the array, dereference on it leads to UB. The for loop should be
for (int i = 0; i < 5; i++)
~
Then i will be 0 ~ 4, loop 5 times, not 6 times as your code shown.
You might use range-based for loop (since C++11) to avoid such kind of mistake:
for (auto& i : myArray) {
i = (rand() % 55) + 1;
cout << i << '\t';
}
random numbers from 1 to 54
So this is incorrect as well: (rand() % 55) + 1;
You'll need (rand() % 54) + 1;
Because you went to myArray[5] at the last time and your array don't have this place so you got it
you need to write like that:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 5; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
If you want 6 items you need to make a array for six items
int myArray[5];
this will provide 5 items where as
int myArray[6];
this will provide you 6 items
This will fix your problem

How to find divisors of number on specified interval?

I want to write a simple progam using WHILE loop, with which you could get all divisors of the number which you put in.
For example you want all divisors of number 30, which are: 1, 2, 3, 5, 6, 10, 15, 30.
Now you want program to display only numbers on interval (for example) from 5 - 10, which are 5, 6 and 10.
What i tried so far is getting all those divisors using FOR sentence, but without intervals, so I am stucked and don't know how could make it also in WHILE loop.
#include <iostream>
using namespace std;
int main() {
int input_number;
cin >> input_number;
cout << "All numbers are " << input_number << endl;
for (int i = 1; i <= input_number; i++) {
if (input_number % i == 0) {
cout << i << " ";
}
}
return 0;
}
Thanks for your help in addition.
Solving this problem in a while loop is probably not as simple (or brute-force) as solving it in a for loop.
Consider this rendition of the loop using while:
int input_number;
std::cin >> input_number;
int i = 1; //Start trying to divide the input number by 1
int limit = input_number; //Termination condition for the loop
while(i < limit) {
if(input_number % i == 0) { //If divisible by i, both i and input_number/i are factors
std::cout << i << " " << input_number / i << " ";
}
++i; //Try dividing by the next integer
/*Set the limit to our latest input_number/i so we don't get duplicate
results (e.g. (5, 6) and (6, 5) for input_number = 30)*/
limit = input_number / i;
}
For input_number = 30, this loop only runs for 5 iterations, while the for loop version runs for 30 iterations.
Bottom Line
for loops and while loops are interchangeable, but approaching a problem using a for loop might bring you to a different solution faster than approaching the problem with a while loop and vice versa as they help you think about the problem from different perspectives.
Extra Information
The for loop version allows for certain optimization techniques such as parallel accumulators, which are not possible in the while loop version as each iteration depends on the previous.
Why would you want to do this as a while loop? for is definitely the correct choice of loop here. Checking all divisors is done quite clearly via:
for (int i = 1; i <= input_number; i++) { ... }
If you want to add a narrower window to that, you can just change the bounds of the loop:
for (int i = lower_bound; i <= upper_bound; i++) { ... }
Turning that into a while loop would just involve unwrapping those statements into:
int i = lower_bound;
while (i <= upper_bound) {
...
i++;
}
But this is more error-prone - if you had a continue in your loop body, i would not get incremented.

Decimal to Binary in C++

I'm a total beginner in C++ and today I thought I'd write myself a small program that converts a decimal number to binary. The code looked something like this:
#include <iostream>
void binaryConvert(int);
int main() {
using namespace std;
cout << "Enter decimal number for conversion:" << endl;
int dec;
cin >> dec;
binaryConvert(dec);
}
void binaryConvert(int number) {
using namespace std;
while(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin;
}
}
Logically, this program would print the binary the other way around. I spent a long time trying to figure out how to invert the order of the binary digits so that the binary number would appear the right way around when I came across this piece of code:
void binaryConvert(int number) {
using namespace std;
if(number > 0) {
int bin = number % 2;
number /= 2;
binaryConvert(number);
cout << bin;
}
}
I know its probably a stupid question (I'm an absolute beginner), but I can't figure out why this code prints the bits in the correct order. Also, how come the bits actually get printed if the function gets called again before cout even gets executed?
Basically because "cout" is called after "binaryConvert". It's like putting all the bits in a stack and after that printing them.
It utilizes recursion, the bin at the end will not be printed until the base case is hit (number <= 0) and then it will go up the stack trace.
This function is a recursive one. It is calling itself recursively to print the least significant digits first, before printing out the most significant ones.
int num;
string BinaryRepresentation="";
cout<<"Input:";
cin>>num;
string newstring= "";
bool h;
h = true;
while(h){
BinaryRepresentation += boost::lexical_cast<std::string>( num % 2 );
num = num / 2;
if ( num < 1){
h = false;
}
}
for ( int i = BinaryRepresentation.size() - 1; i >= 0; i--){
newstring += BinaryRepresentation[i];
}
cout<< "Binary Representation: " << newstring <<endl;
}
Mainly the idea of the program is to find the reminder of the number and divide the number by 2 and and keep on repeating the same procedure until the number becomes 0. The you need to reverse the string in order to get the binary equivalent of the entered number.
As you have correctly mentioned your program inverted the binary as it gave the output.
To put the binary in the correct order to The second code starts giving output only once the final bit is obtained. The order of output is bin to the bin and hence we obtain the desired output. The following code may help your understanding further: http://ideone.com/Qm0m7L
void binaryConvert(int number) {
if(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin<<" one"<<endl;
binaryConvert(number);
cout << bin<<" two"<<endl;
}
}
The output obtained is:
0 one
0 one
0 one
1 one
1 two
0 two
0 two
0 two
The output that precedes " one" is what your program would have given.
I hope you understand the difference.
While I was searching online to convert from decimal to binary, didn't find a simple and an understandable solution. So I wrote a program on my own.
Here it goes.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void dtobin(int n)
{
ostringstream oss;
string st="";
if(n<0)
{
cout<<"Number is negative";
return;
}
int r;
while(n!=1)
{
r=n%2;
oss<<st<<r;
n/=2;
}
oss<<st<<1;
st=oss.str();
cout<<st;
//To reverse the string
int len=st.length();
int j=len-1;
char x;
for(int i=0;i<=len/2-1;i++)
{
x=st[i];
st[i]=st[j];
st[j]=x;
--j;
}
cout<<endl<<st;
}
int main()
{
int n;
cout<<"ENTER THE NUMBER";
cin>>n;
dtobin(n);
return 0;
}

Add Output of Integers in C++?

I am working on Project Euler, the first problem, and I've gotten this program to output the numbers I need, but I cannot figure out how to take the outputted numbers and add them together.
Here's the code:
#include <iostream>
#include <cmath>
int main(void) {
int test = 0;
while (test<1000) {
test++;
if (test%3 == 0 && test%5 == 0) {
std::cout << test << std::endl;
}
}
std::cin.get();
return 0;
}
The easiest option would be a total variable that you add to as the criteria match.
The first step is creating it and initializing it to 0, so you end up with the right number later.
int total = 0;
After that, subtotals are added to it, so that it accumulates the overall total.
total += 5;
...
total += 2;
//the two subtotals result in total being 7; no intermediate printing needed
Once you've added on the subtotals, you can just print it as the overall total.
std::cout << total;
Now, here's how it fits into the code at hand, along with some other pointers:
#include <iostream>
#include <cmath> //<-- you're not using anything in here, so get rid of it
int main() {
int test = 0;
int total = 0; //step 1; don't forget to initialize it to 0
while (test<1000) { //consider a for loop instead
test++;
if (test % 3 == 0 && test % 5 == 0) {
//std::cout << test << std::endl;
total += test; //step 2; replace above with this to add subtotals
}
}
std::cout << total << std::endl; //step 3; now we just output the grand total
std::cin.get();
return 0; //this is implicit in c++ if not provided
}
The typical way to do this is to use another variable to hold the sum. You gradually add each number to this variable until you have to total at the end of your loop.