Understanding what happens within function loop - c++

I would like to know why the inner for loop executes. My understanding is that since j = 1 and i = 0, j <= i; would produce nothing as j is already greater than i. Therefore, the inner loop would be skipped, producing the same result as the initial array.
void sortArray(int myArray[], int size)
{
int num1 = 0;
int num2 = 0;
int temp = 0;
for (int i = 0; i < size; i++)
{
int first = 0;
for (int j = 1; j <= i; j++)
{
if (myArray[j] > myArray[first])
{
first = j;
}
temp = myArray[first];
myArray[first] = myArray[i];
myArray[i] = temp;
}
}
}

The inner loop is skipped during first iteration. After i is incremented, j is now equal to i, therefore the inner loop will execute 1 time. Inner loop exits, outer loop increments i by 1, inner loop now iterates twice as i == 2.
This will repeat until i == size - 1 OR i < size (same condition, different wording).

The inner loop should skip for 1 iteration of the outer loop then will run for 1 time as j<=i returns true. (first iteration i=0, second iteration i=1)
this is equivalent to:
for (int j = 1; j <= 0; j++)
After that the second loop will run 1 time equivalent to
for (int j = 1; j <= 1; j++)
and so on..
for (int j = 1; j <= 2; j++)

Related

What does a semicolon after for-loop means? Why is there a j++ in first loop statement?

I need to implement my own version of Dijkstra algorithm based on priority queues, and while searching some sites about it, I saw an algorithm that actually works but with strange for-loop statements:
int i,j,n;
cin >> n; //number of vertexes
bool *QS = new bool [n];
//whole QS is set to false here
for(i = 0; i < n; i++) {
for(j = 0; QS[j]; j++);
for(u = j++; j < n; j++)
if(!QS[j] && (d[j] < d[u])) //d[i] is table of distances
u = j;
QS[u] = true;
//some code
}
I know that ; after loop means it's empty statement, but if I comment second for-loop this program stops working, so it actually means something. I believe that this u = j++ was meant to be like start form u = j+1, but I'm not so sure.
for(j = 0; QS[j]; j++); is used as j=0; while(QS[j])j++;
i.e. to find the first j that QS[j] is false
for(j = 0; QS[j]; j++);
sets j to 0 and then increments j until the first element in QS that is false. You then use that value for the initial value of the third loop.
It is a cleaver way to write it but you can be a lot more expressive on what it is doing using std::find and std::distance like
for(i = 0; i < n; i++) {
int j = std::distance(std::begin(QS), std::find(std::begin(QS), std::end(QS), false));
for(u = j++; j < n; j++)
if(!QS[j] && (d[j] < d[u])) //d[i] is table of distances
u = j;
QS[u] = true;
//some code
}
which explicitly states that j will be the distance from the beginning of the array to the first false element.
the second for loop walks through all of the array QS which is an
array of booleans. Which will break when one is false, saving the current value of j and starting the next loop with that value +1.

Skipping vector iterations based on index equality

Let's say I have three vectors.
#include <vector>
vector<long> Alpha;
vector<long> Beta;
vector<long> Gamma;
And let's assume I've filled them up with numbers, and that we know they're all the same length. (and we know that length ahead of time - let's say it's 3.)
What I want to have at the end is the minimum of all sums Alpha[i] + Beta[j] + Gamma[k] such that i, j, and k are all unequal to each other.
The naive approach would look something like this:
#include <climits>
long min = LONG_MAX;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k=0; k < 3; k++) {
if (i != j && i != k && j != k) {
long sum = Alpha[i] + Beta[j] + Gamma[k];
if (sum < min)
min = sum;
}
}
}
}
Frankly, that code doesn't feel right. Is there a faster and/or more elegant way - one that skips the redundant iterations?
The computational complexity of your algorithm is an O(N^3). You can save a very small bit by using:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if ( i == j )
continue;
long sum1 = Alpha[i] + Beta[j];
for (int k=0; k < 3; k++) {
if (i != k && j != k) {
long sum2 = sum1 + Gamma[k];
if (sum2 < min)
min = sum2;
}
}
}
}
However, the complexity of the algorithm is still O(N^3).
Without the if ( i == j ) check, the innermost loop will be executed N^2 times. With that check, you will be able to avoid the innermost loop N times. It will be executed N(N-1) times. The check is almost not worth it .
If you can temporarily modify the input vectors, you can swap the used values with the end of the vectors, and just iterate over the start of the vectors:
for (int i = 0; i < size; i++) {
std::swap(Beta[i],Beta[size-1]); // swap the used index with the last index
std::swap(Gamma[i],Gamma[size-1]);
for (int j = 0; j < size-1; j++) { // don't try the last index
std::swap(Gamma[j],Gamma[size-2]); // swap j with the 2nd-to-last index
for (int k=0; k < size-2; k++) { // don't try the 2 last indices
long sum = Alpha[i] + Beta[j] + Gamma[k];
if (sum < min) {
min = sum;
}
}
std::swap(Gamma[j],Gamma[size-2]); // restore values
}
std::swap(Beta[i],Beta[size-1]); // restore values
std::swap(Gamma[i],Gamma[size-1]);
}

Sort entered number - difference between FOR and WHILE

I have to write a code which sort digits in one entered number.
For example: input: 4713239
output: 1233479
It doesn't work properly when I enter repeating digits(like 33) when I have the last loop as FOR:
for(int j = 0; j < arr[i]; j++) // in this loop my output is: 123479.
When I change this loop from FOR to WHILE it works properly.
It means:
while(arr[i]) // and the number is sorted correctly (1233479)
True be told, I don't know what is the difference between these operations in this code.
Why FOR loop doesn't work properly? Could somebody explain me this?
I wrote a code:
int sort(int arg)
{
int var, score = 0;
int arr[10] = {0};
for(int i = 0; i < 10; i++)
{
var = arg % 10;
arr[var]++;
arg = arg / 10;
}
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < arr[i]; j++) //while(arr[i]) --> works correctly
{
score = score * 10 + i;
arr[i]--;
}
}
return score;
}
You modify both arr[i] and j, therefore the loop will end too fast when both are part of the comparison.
for(int j = 0; j < arr[i]; j++) // increase j, compare with arr[i]
{
score = score * 10 + i;
arr[i]--; // decrease arr[i]
}

Calculating Operation Count of this code

I'm trying to understand the operation count of the code given below.
void add(matrix a, matrix b, matrix c, int m, int n)
{
for(int i = 0; i < m; i++)
{
count++; //for 'for' i -------(a)
for(int j = 0; j < n; j++)
{
count++; //for 'for' j -------(b)
c[i][j] = a[i][j] + b[i][j];
count++; //for assignment ------(c)
}
count++; //for last time of 'for' j ------(d)
}
count++; //for lastime of 'for' i ---------(e)
}
The variable count has been used by the author in which this code is to calculate operation count. I do know that the declarative statements (int i = 0; int j = 0) have operation count of 0.
Every time each the for loop will run it, the following expressions should do 2 operation counts for i < m; i++ when only 1 operation i < m is performed.
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
But the author has only calculated it once (a) and (b). Does that means i < m and j < n is not calculated in operation count?
In this line the operation count should be 2: 1 addition operation and 1 assignment operation.
c[i][j] = a[i][j] + b[i][j];
Again he has only calculated it once (c).
Because of the questions I don't know why he incremented count at (d) and (e).
//Simplified program with counting only
line void add (matrix a, matrix b, matrix c, int m, int n)
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < m; j++)
count += 2;
count += 2;
}
count++;
}
Thank you :)

For loop goes forever

I want this loop to decrement from the value I set it to from 10 to 0. Why does it keep going forever?
int lengthString = 10;
for (int j = lengthString; lengthString > 0; j--)
{
cout << j;
}
Change to
for (int j = lengthString; j > 0; j--)
lengthString doesn't change in your loop.
Also, you might want to verify that lengthString is greater than 0 (in your real code) if you declare j as an int, because if j is initialized to a negative number, the loop will run "forever" (until it overflows and gets decreased to 0 again, that is).
You're exit condition is lengthString > 0, and since lengthString doesn't change in you're loop you're just saying while(10 > 0), which is true forever.
I believe you meant:
for (int j = lengthString; j > 0; j--)
for (int j = lengthString; j >= 0; j--)
Your loop decrements j, and checks if lengthString is > 0.
int lengthString = 10;
for (int j = lengthString; j > 0; j--)
{
cout << j;
}
You are only decrementing j, but loop condition doesn't use j
It should be j that you are checking in your greater than, not lengthstring.
for (int j = lengthString; j > 0; j--)
Try this one:
for (int lengthString = 10, *j = &lengthString; lengthString > 0; lengthString--)
{
cout << *j;
}