Why does the compiler skip the for-loop? - c++

I have tried to do some practice with vector, and I made a simple for loop to calculate the sum of the elements within the vector. The program did not behave in the way I expect, so I try to run a debugger, and to my surprise, somehow, the compiler skips the for loop altogether, and I have not come up with a reasonable explanation.
//all code is written in cpp
#include <vector>
#include <iostream>
using namespace std;
int simplefunction(vector<int>vect)
{
int size = vect.size();
int sum = 0;
for (int count = 0; count == 4; count++) //<<--this for loop is being skipped when I count==4
{
sum = sum + vect[count];
}
return sum; //<<---the return sum is 0
}
int main()
{
vector<int>myvector(10);
for (int i = 0; i == 10; i++)
{
myvector.push_back(i);
}
int sum = simplefunction(myvector);
cout << "the result of the sum is " << sum;
return 0;
}
I have done some research, and usually the ill-defined for loop shows up when the final condition cannot be met (Ex: when setting count-- instead of count++)

Your loop's conditions are wrong, as they are always false!
Look at to the loops there
for (int i = 0; i == 10; i++)
// ^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
and
for (int count=0; count==4; count++)
// ^^^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
you are checking i is equal to 10 and 4 respectively, before incrementing it. That is always false. Hence it has not executed further. They should be
for (int i = 0; i < 10; i++) and for (int count=0; count<4; count++)
Secondly, vector<int> myvector(10); allocates a vector of integers and initialized with 0 s. Meaning, the loop afterwards this line (i.e. in the main())
for (int i = 0; i == 10; i++) {
myvector.push_back(i);
}
will insert 10 more elements (i.e. i s) to it, and you will end up with myvector with 20 elements. You probably meant to do
std::vector<int> myvector;
myvector.reserve(10) // reserve memory to avoid unwanted reallocations
for (int i = 0; i < 10; i++)
{
myvector.push_back(i);
}
or simpler using std::iota from <numeric> header.
#include <numeric> // std::iota
std::vector<int> myvector(10);
std::iota(myvector.begin(), myvector.end(), 0);
As a side note, avoid practising with using namespace std;

Related

Command terminated right after vector input

I created this program:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n;
cin>>n;
vector<int> m(n);
for(int i=0;i<n;i++){
cin>>m[i];
}
sort(m.begin(),m.end());
vector<bool> used(n,false);
for(int i=n;i>0;i--){
for(int j=i;j>0;j--){
if((m[i]/m[j]>=2)&&(used[i]==false))
used[j]=true;
}
}
int numOfElem=0;
for(int i=0;i<n;i++){
if(used[i]!=true){
numOfElem++;
}
}
cout<<"\n"<<numOfElem<<"\n";
return 0;
}
Now for some reason right after I input elements of vector m I get command terminated, does anyone know the cause of this problem?
You access the vectors m and used out of bounds since you start iterating with i == n (the size of the vectors). This causes your program to have undefined behavior and a crash is one possible outcome of that.
Suggested fix:
for(int i = n - 1; i >= 0; i--) { // start with n-1 and ...
for(int j = i; j >= 0; j--) { // ... include 0 in the loop
Also note that m[i] / m[j] may be a division by zero and throw an exception, so you may want to check if m[j] == 0 before doing the division too.

How to find the minimun of an array?

I was trying to solve this question
but codechef.com says the answer is wrong.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t, n, diff, mindiff;
cin >> t;
cin >> n;
int val[n];
while(t--)
{
mindiff = 1000000000;
for(int i = 0; i<n; i++)
{
cin >> val[i];
}
int a = 0;
for(a = 0; a<n ; a++)
{
for(int b=a+1; b<n ; b++)
{
diff = abs(val[a] - val[b]);
if(diff <= mindiff)
{
mindiff = diff;
}
}
}
cout << mindiff << endl;
}
return 0;
}
The results are as expected (for at least the tests I did) buts the website says its wrong.
There are a few things in your code that you should change:
Use std::vector<int> and not variable-length arrays (VLA's):
Reasons:
Variable length arrays are not standard C++. A std::vector is standard C++.
Variable length arrays may exhaust stack memory if the number of entries is large. A std::vector gets its memory from the heap, not the stack.
Variable length arrays suffer from the same problem as regular arrays -- going beyond the bounds of the array leads to undefined
behavior. A std::array has an at() function that can check boundary access when desired.
Use the maximum int to get the maximum integer value.
Instead of
mindif = 1000000000;
it should be:
#include <climits>
//...
int mindiff = std::numeric_limits<int>::max();
As to the solution you chose, the comments in the main section about the nested loop should be addressed.
Instead of a nested for loop, you should sort the data first. Thus finding the minimum value between two values is much easier and with less time complexity.
The program can look something like this (using the data provided at the link):
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
int main()
{
int n = 5;
std::vector<int> val = {4, 9, 1, 32, 13};
int mindiff = std::numeric_limits<int>::max();
std::sort(val.begin(), val.end());
for(int a = 0; a < n-1 ; a++)
mindiff = std::min(val[a+1] - val[a], mindiff);
std::cout << mindiff;
}
Output:
3
To do this you can use a simple for():
// you already have an array called "arr" which contains some numbers.
int biggestNumber = 0;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] > biggestNumber) {
biggestNumber = arr[i];
}
}
arr.size will get the array's length so that you can check every value from the position 0 to the last one which is arr.size() - 1 (because arrays are 0 based in c++).
Hope this helps.

linear search for number vector in c++

I am trying to output 9 random non repeating numbers. This is what I've been trying to do:
#include <iostream>
#include <cmath>
#include <vector>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
vector<int> v;
for (int i = 0; i<4; i++) {
v.push_back(rand() % 10);
}
for (int j = 0; j<4; j++) {
for (int m = j+1; m<4; m++) {
while (v[j] == v[m]) {
v[m] = rand() % 10;
}
}
cout << v[j];
}
}
However, i get repeating numbers often. Any help would be appreciated. Thank you.
With a true random number generator, the probability of drawing a particular number is not conditional on any previous numbers drawn. I'm sure you've attained the same number twice when rolling dice, for example.
rand(), which roughly approximates a true generator, will therefore give you back the same number; perhaps even consecutively: your use of % 10 further exacerbates this.
If you don't want repeats, then instantiate a vector containing all the numbers you want potentially, then shuffle them. std::shuffle can help you do that.
See http://en.cppreference.com/w/cpp/algorithm/random_shuffle
When j=0, you'll be checking it with m={1, 2, 3}
But when j=1, you'll be checking it with just m={2, 3}.
You are not checking it with the 0th index again. There, you might be getting repetitions.
Also, note to reduce the chances of getting repeated numbers, why not increase the size of random values, let's say maybe 100.
Please look at the following code to get distinct random values by constantly checking the used values in a std::set:
#include <iostream>
#include <vector>
#include <set>
int main() {
int n = 4;
std::vector <int> values(n);
std::set <int> used_values;
for (int i = 0; i < n; i++) {
int temp = rand() % 10;
while (used_values.find(temp) != used_values.end())
temp = rand() % 10;
values[i] = temp;
}
for(int i = 0; i < n; i++)
std::cout << values[i] << std::endl;
return 0;
}

Function returning sum of even numbers in an array

So the prompt I was given was "Write a function that is given an array of ints and returns the sum of the even numbers in the array. The function is not given the length of array, but the last number in the array is -1. For example, if the array contains {2,3,5,4,-1} the function returns 6. Use the header int sumEven(int myArray[]). "
and the code I've written so far is
#include <iostream>
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; i++;){
if (myArray[i] >=0) {
sum+=myArray[i];
}
}
return sum;
}
But it keeps returning back zero's? I'm not seeing what I'm doing wrong here
The typical order of parameters to a for() loop are like so:
for(<initialize variable>; <end condition>; <increment variable>)
In your example, you have the i++ as your second parameter to the for loop, which is incorrect. It will return 0 (since i starts as 0, and i++ is post-increment, so it returns 0 and then increments to 1) and your for loop will exit immediately, since 0 evaluates to false.
Instead, replace the end condition with the end condition you've described: myArray[i] != -1. You should also include a check to see if the number is even before adding it to sum, which can be done by checking to see if the remainder when divided by 2 is 0.
#include <iostream>
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; myArray[i] != -1; i++){
if(myArray[i] % 2 == 0)
sum += myArray[i];
}
return sum;
}
The error is in the for loop. You should change the for loop to for (int i=0; ; i++) and you should also add a break statement to exit the for loop.
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; ; i++){
if (myArray[i] >=0) {
sum+=myArray[i];
}
else
{
break;
}
}
return sum;
}
int sumEven(int arr[]) {
int sum = 0;
// int len = (sizeof(arr)/sizeof(*arr)); // Since this will not work for all cases.
// auto len = end(arr) - begin(arr);
for (int i = 0; arr[i] >= 0; i++) {
if(arr[i]%2==0)
sum += arr[i];
}
return sum;
}
i guess the
for (int i=0; i++;){
make no iterations, cause condition to continue loop is "i++" - which is initialy zero.
Replace it with following for example
for (int i=0; i < array_length; i++;){

Sieve of Eratosthenes C++ Implementation: not exiting loop

I'm trying to implement the Sieve by myself and with no help other than the algorithm provided...
#include <iostream>
using namespace std;
void findPrimeNumbers(int number) {
int n=0;
bool* boolArray = new bool[number]();
for(int i=0; i<number; i++) {
boolArray[i] = true;
}
for(int i = 2; i<(int)sqrt(number); i++) {
cout << "calculating...\n";
if(boolArray[i]) {
for(int j=(i^2+(n*i)); j<number; n++)
boolArray[j] = false;
}
if(boolArray[i])
cout << i << "\n";
}
return;
}
int main()
{
findPrimeNumbers(55);
system("pause");
return 0;
}
Except the program is hanging on line 37; specifically, "boolArray[j] = false". It's never exiting that loop, and I don't know why.
Edited: Ok, this fixes the hang but still isn't right, but don't answer, I want to figure it out :)
#include <iostream>
#include <cmath>
using namespace std;
void findPrimeNumbers(int number) {
int n=0;
bool* boolArray = new bool[number]();
for(int i=0; i<number; i++) {
boolArray[i] = true;
}
for(int i = 2; i<sqrt(number); i++) {
if(boolArray[i]) {
for (int j = pow(i,2) + n*i; j <= number; j = pow(i, 2) + (++n*i))
boolArray[j] = false;
}
if(boolArray[i] && number % i == 0)
cout << i << "\n";
}
return;
}
int main()
{
findPrimeNumbers(13195);
system("pause");
return 0;
}
Beyond the error pointed out by #Rapptz (^ is bitwise xor), you are incrementing n instead of j, so the termination condition is never reached.
Two problems:
The ^ operator is not the exponent operator like it is in some other languages. Just multiply i by itself instead (i*i).
your for loop:
for(int j=(i^2+(n*i)); j<number; n++)
boolArray[j] = false;
does not reevaluate the initial condition each loop. You need to reevaluate the condition at the beginning of the for loop:
for(int n=0; j<number; n++)
{
j=(i*i+(n*i));
boolArray[j] = false;
}
Your issue is the line i^2+(n*i) like the comments point out, operator^ is the XOR operator, not exponentiation. In order to exponentiate something you have to include the <cmath> header and call std::pow(a,b) where it is equivalent to the mathematical expression a^b.
Although you didn't ask for code review, it should be noted that using dynamic allocation for a bool array is probably not a good idea. You should use std::vector<bool> and a proper reserve call. It should also be noted that the pow call would be completely unnecessary, as you are only multiplying it by itself (i.e. 2^2 is the same as 2*2).
A better naive prime sieve would be something similar to this:
#include <vector>
#include <iostream>
template<typename T>
std::vector<T> generatePrimes(unsigned int limit) {
std::vector<T> primes;
std::vector<bool> sieve((limit+1)/2);
if(limit > 1) {
primes.push_back(2);
for(unsigned int i = 1, prime = 3; i < sieve.size(); ++i, prime += 2) {
if(!sieve[i]) {
primes.push_back(prime);
for(unsigned int j = (prime*prime)/2; j < sieve.size(); j += prime)
sieve[j] = true;
}
}
}
return primes;
}
int main() {
std::vector<unsigned> primes = generatePrimes<unsigned>(1000000);
for(auto& i : primes)
std::cout << i << '\n';
}
You can see it here.
You have a number of problems:
int j=(i^2+(n*i))
^ is not power in C++, it's the bitwise XOR operator. To fix this, you'll need to #include <cmath> and utilize pow, or simply use i * i.
Secondly, as others have mentioned, you are incrementing n. The easiest fix for this is to use a while loop instead:
int j = std::pow(i, 2) + (n*i);
while(j < number) {
//Set bool at index to false
j += i;
}
Thirdly, you have a memory leak - you new without a delete. Further, there's no reason to use new here, instead you should have:
bool b[number];
This will deallocate b automatically when the function exits.
Finally, why return at the bottom of a void function? Technically you can do it, but there is no reason to.