Don't print space after last number [duplicate] - c++

This question already has answers here:
How can I print a list of elements separated by commas?
(34 answers)
Closed 7 years ago.
LANGUAGE: C++
Hello, in the following function (code block) i have written a line to print an space between characters but i don't want print spaces after last characters. How can i solve this problem?
bool perfecto(int n)
{
int suma, i;
suma = 0;
for (i = 1; i < n; i++)
{
if (n % i == 0)
{
suma += i;
cout << i << " ";
}
}
if (suma == n)
return true;
else
return false;
}
Best regards.
Ángel Manuel.

The simplest way would be to turn the problem around: if you only print spaces before printing the number (and not after) then it becomes how not to print the first time, which is much easier.
I'll let you figure it out :)

bool perfecto(int n)
{
int suma, i;
suma = 0;
bool first = true;
for (i = 1; i < n; i++)
{
if (n % i == 0)
{
suma += i;
if ( !first )
{
cout << " ";
}
cout << i;
first = false;
}
}
if (suma == n)
return true;
else
return false;
}

You can either check if i is equal to n - 1 and not print it in that case, or something like
std::cout << "1";
for (int i = 2; i < n; ++i)
{
std::cout << " " << i;
}
In the second case, you have to watch for for a case where n is 1 or less

There are a variety of options. In this case, probably the easiest is to print spaces BEFORE elements except the first and use a flag to track the first element:
bool perfecto(int n)
{
int suma, i;
suma = 0;
bool first = true;
for (i = 1; i < n; i++)
{
if (n % i == 0)
{
suma += i;
if(!first)
{
std::cout << " ";
}
else first = false;
cout << i;
}
}
if (suma == n)
return true;
else
return false;
}
EDIT: Other popular alternatives are printing the first item and no delimiter outside the loop completely and then inside the loop you can always pre-print the item with no if-check at all. This approach wouldn't work as well with your loop though since you don't always know when the first item will print. You can also create wrapper ostream like classes that keep track of their internal printing state and know when to put the spaces.

Replace this line: cout << i << " ";
with:
cout << i;
if (i == n-1)
cout << endl;
else
cout << " ";

Related

Binary THEN Sequential Search if size of search list reduces to less then certain amount

Still new to C++ here. I am writing a program that compares two different search's comparison counts, a binary search alone and a binary search that switches to a sequential search once the search list size is lower than 18.
The array is of size 1000, randomly generated values (1-1000), and is sorted before searching.
The binary search works fine with a max comparison count of 10 I believe.
However, the combo search repeats forever if the sequential search loop starts.
Here is the combo search function:
template <class T>
void BinaryandSequentialSearch(const T arr[], int n, const T& search_key)
{
int arrBegin = 0;
int arrEnd = n - 1;
int count = 0;
int middle, i, newListSize;
bool found = false;
while (!found && arrBegin <= arrEnd)
{
count++;
middle = (arrBegin + arrEnd) / 2;
if (arr[middle] == search_key)
found = true;
else if (arr[middle] < search_key)
arrBegin = middle + 1;
else if (arrEnd - arrBegin < 18)
{
cout << "\nEntered sequenctial search.\n";
newListSize = arrEnd - arrBegin;
cout << newListSize << endl;
for (i = 0; i < newListSize; i++)
{
count++;
if (arr[middle] == search_key)
{
found = true;
break;
}
middle++;
}
}
else
arrEnd = middle - 1;
}
if (!found)
cout << "\nThe value " << search_key << " is not in the array\n";
else
{
cout << "\nThe value is located at index " << middle << " in the array"
<< endl << "Number of comparisons = " << count << endl;
}
}
Even if newListSize = 6, the for loop seems to loop forever.
Here's my main function if any context is needed:
int main()
{
const int size = 1000;
int A[size];
int search_key;
srand (time(NULL));
for (int i = 0; i < size; i++)
A[i] = rand() % 1000 + 1;
Print(A, size, "Random unsorted array:");
BubbleSort<int>(A, size);
Print(A, size, "Array Sorted:");
cout << "Enter an integer you want to search from array: ";
cin >> search_key;
//BinarySearch(A, size, search_key);
BinaryandSequentialSearch(A, size, search_key);
return 0;
}
After completing the sequential search, judging by the logic of your program, the loop should break. Or else, you will enter this line again:
while (!found && arrBegin <= arrEnd)
If found is false the first time through, since the sequential search did not change arrBegin and arrEnd, this loop will enter the sequential search again, and again, and again...
(So, it's not your for loop that's looping forever, it's your while loop that repeatedly executes the for loop).
It's an easy fix. See below.
else if (arrEnd - arrBegin < 18)
{
cout << "\nEntered sequenctial search.\n";
newListSize = arrEnd - arrBegin;
cout << newListSize << endl;
for (i = 0; i < newListSize; i++)
{
count++;
if (arr[middle] == search_key)
{
found = true;
break;
}
middle++;
}
break; // <--- I did something!!
}

C++ breaks out of the loop when filling the array

So basically I am trying to create a loop that fills a matrix with random numbers. I need to make it so every column has a different range, unique to it.
//Variables
int lsx = 3;
int lsy = 10;
int lust[lsy][lsx];
int i = 0;
int l = 0;
int shpp = 7;
//List setup
for (i = 0; i < lsy; i++)
{
for (l = 0; l < lsx; l++)
{
lust[i][l] = 0;
}
}
while (true)
{
//List generator
for (i = 0; i < lsy; i++)
{
for (l = 0; l < lsx; l++)
{
//Column 1
if (i == 0)
{
lust[i][l] = rand() % flx;
cout << lust[i][l] << '\n';
}
//Column 2
if (i == 1)
{
lust[i][l] = rand() % fly;
cout << lust[i][l] << '\n';
}
//Column 3
if (i == 2)
{
lust[i][l] = rand() % shpp;
cout << lust[i][l] << '\n';
}
}
cout << "Endline reached! \n \n";
}
for (i = 0; i < lsy; i++)
{
for (l = 0; l < lsx; l++)
{
cout << lust[i][l] << " ";
}
cout << "\n";
}
}
}
This only generates 3 lines. Does anyone have any ideas on why this could happen?
I tried changing some stuff around but only got weirder results that wouldn't fill the array in completely eitherThis is what the program displays when I try and run it
for (l = 0; l < lsx; l++)
{
Column 1
if (i == 0)
}
lust[i][l] = rand() % flx;
cout << lust[i][l] << '\n';
}
Column 2
if (i == 1)
}
lust[i][l] = rand() % fly;
cout << lust[i][l] << '\n';
}
Column 3
if (i == 2)
{
lust[i][l] = rand() % shpp;
cout << lust[i][l] << '\n';
}
}
cout << "Endline reached! \n \n";
You're using i (the line iterator) to evaluate what you're going to fill. Which means your code will only concern itself with lines 0, 1 and 2. Instead, shift that i to l - your column iterator. It should work.
Also, consider removing the while true loop. Not only is it redundant, it's also pretty dangerous considering there's no break condition - in this case it's safe, since you'll be around to shut it down, but as a good practice stay out of while(true) unless you can't write your break condition as a boolean expression

How to separated numbers by a comma in output? [duplicate]

This question already has answers here:
For loop prints an extra comma
(9 answers)
Closed 2 years ago.
I want to find prime numbers in a given range.
The output number must be separated by a comma.
#include <iostream>
using namespace std;
int main()
{
int i,j,lower, upper;
cin >> lower;
cin >> upper;
for (i = lower + 1; i < upper; i++)
{
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
break;
}
}
if (j == i)
{
cout << i ;
cout << ",";
}
}
}
Input:11 20
Output must be : 13,17,19
but my code prints an extra comma and it is not just between the numbers. Would you please help me?!
Instead of printing the result right away, you can store it in a vector, so you know exactly how many numbers you want to print. Then you print your vector this way :
std::vector result;
std::string output = "";
for (size_t i = 0; i < result.size(); ++i) // Notice the ++i, not i++
{
if (i != 0)
output += ", ";
output += result[i];
}
If you don't want to store your result in a vector, you can define a boolean firstResult to true if you don't have printed a coma yet, then to false when you have printed the first result, and you print the coma before the number.
int main()
{
bool firstResult = true;
[...]
if (j == i)
{
if (!firstResult)
cout << ",";
firstResult = false;
cout << i ;
}
}

How to fix: for loops not reading for a vector

School assignment for coding a cows and bulls game. Final scoring loops not working and I am not sure what the reason is.
I have tried renaming the vectors, changing iterators, changing where in the code the vectors are declared/initialized (still not sure exactly the difference)
//Get Number to Guess
if (numlen == 0) {
cout << "Enter the number to guess: ";
cin >> num;
cout << "Enter the number of digits in code: ";
cin >> numlen;
numstr = to_string(num);
if (numstr.length() < numlen) {
int diff = numlen - numstr.length();
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
numstr = addz + numstr;
}
num = stoi(numstr);
}
vector<int> numvct(numlen, 0);
max1 = 1;
for (l = 1; l < numlen; ++l) {
max1 = max1 * 10;
}
for (j = max1, k = 0; j >= 1, k < numlen; j = j / 10, ++k) {
int addval1 = num / j;
num = num - (addval1 * j);
numvct.at(k) = addval1;
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << numvct.at(r) << "-";
}
}
}
else {
//Fill vector to pick from
for (i = 0; i <= 9; ++i) {
pickvct.push_back(i);
}
//Pull to random number
vector<int> numvct(numlen);
for (k = 0; k < numlen; ++k) {
tempnum1 = rand() % (pickvct.size() - 1);
numvct.at(k) = pickvct.at(tempnum1);
pickvct.erase(pickvct.begin() + tempnum1);
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << r << "-";
}
}
}
//Get guess
do {
do {
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
if (guesslen < numlen) {
int diff = numlen - guesslen;
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
guessstr = addz + guessstr;
}
guess = stoi(guessstr);
guesssame = true;
}
if (guesslen == numlen) {
guesssame = false;
}
while (guesslen > numlen) {
cout << "You can only enter " << numlen << " digits." << endl;
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
}
for (s = 0; s < guesslen; ++s) {
for (t = s + 1; t < guesslen; ++t) {
if (guessstr.at(s) == guessstr.at(t)) {
guesssame = true;
}
else {
guesssame = false;
}
}
}
if (guesssame == true) {
cout << "Each number must be different." << endl;
guesssame = true;
}
} while (guesssame == true);
vector<int> guessvct(guesslen, 0);
max2 = 1;
for (m = 1; m < guesslen; ++m) {
max2 = max2 * 10;
}
for (n = max2, o = 0; n >= 1, o < guesslen; n = n / 10, ++o) {
addval2 = guess / n;
guess = guess - (addval2 * n);
guessvct.at(o) = addval2;
}
//Check the guess
for (p = 0; p < guesslen; ++p) {
guessdigit = guessvct.at(p);
cout << "Guess digit at " << p << ": " << guessdigit << endl;
for (q = 0; q < guesslen; ++q) {
numdigit = numvct.at(q);
cout << "Num digit at " << q << ": " << numdigit << endl;
if (numdigit == guessdigit && q == p) {
bulls = bulls + 1;
if (bulls == numlen) {
win = true;
break;
}
cout << bulls << " bulls" << endl;
}
else {
if (numdigit == guessdigit && q != p) {
cows = cows + 1;
cout << cows << " cows" << endl;
}
}
}
}
} while (win == false);
To make sure the loop was working right I added the cout statements but it is printing the first one only:
Enter guess: ####
Guess digit at 0: #
Program finished
//Get Number to Guess
if (numlen == 0) {
...
}
else {
//Fill vector to pick from
...
}
Within this if else block, you have the following two lines:
vector<int> numvct(numlen, 0);
and
vector<int> numvct(numlen);
These lines declare and initialize vectors which pass out of scope when the program leaves their respective if / else blocks. You use this vector numvct again later, though, so I assume you also declared and initialized it before any of the shown code, and it probably starts off empty. Because those two numvct vectors within the if / else block pass out of scope, all the work you do to them goes away aswell. That means that when you try to use numvct again later, you're working with the (presumably) empty one that you declared at the very beginning of the program.
Instead of redeclaring numvct, try just resizing it:
//vector<int> numvct(numlen);
numvct.resize(numlen);
and
//vector<int> numvct(numlen, 0);
numvct.resize(numlen, 0);
Also you might want to try cutting down on the number of variables you're using here, and try to declare them only within the code blocks where they are really needed. It will make it easier to keep track of what's going on.
Edit: I just want to add that I suggest resizing the vectors, as opposed to any other operation you could perform on a vector, because I don't really know what your exact intended use for them was. I ran your code with these changes, as well as with the addition of ~25 other variable declarations that you did not include in your post, and it did things that seemed reasonable i.e. allowed me to choose a number, guess its digits, print number of cows and bulls etc.

How to fix my program crashing?

I'm writing a code for projecteuler.net's 7th problem and I kind of succeeded but i need to find the 10001st prime number and what happens is my program crashes if i try to find higher number than 2262 so I'm unable to get the answer I need. I've tried changing int to other data types such as long but that doesn't seem to be a problem here and I'm just stuck now. What do I need to do for my program to not crash when I try to go beyond 2262nd prime number?
int main()
{
int numbersList[10000], prime[10000], rez;
int where1=1, where=0;
bool remainder;
prime[0] = 2;
for(int i = 2; i < INT_MAX; i++)
{
numbersList[where] = i;//2
where++;
for(int j = 0; j < where1; j++)
{
if(i % numbersList[j] != 0)
{
remainder = true;
}
else
{
remainder = false;
break;
}
}
if(remainder)
{
prime[where1] = i;
where1++;
}
if(where1==2262)// Which primary number you want. More or equal to 2263 crashes.
{
rez = prime[where1-1];
break;
}
}
cout << endl << where1 << " primary number: " << rez << endl;
return 0;
}
I think it has a small typo.
Modulus operation will be done using prime array instead of numberList array
int main()
{
int numbersList[1000000], prime[100000], rez;
int where1=1, where=0;
bool remainder;
prime[0] = 2;
for(int i = 2; i < 1000000; i++)
{
numbersList[where] = i;//2
where++;
remainder = true;
for(int j = 0; j < where1; j++)
{
if(i % prime[j] != 0)
{
remainder = true;
}
else
{
remainder = false;
break;
}
}
if(remainder)
{
prime[where1] = i;
where1++;
}
if(where1==10001)//104743
{
rez = prime[where1-1];
break;
}
}
cout << endl << where1 << " primary number: " << rez << endl;
return 0;
}
I am running first for-loop till 10^6 which will be enough to give first 10001st prime. There are 78489 prime from 1 to 1,000,000 numbers.For more details on numbers of prime you can refer this link