user5321246
user5321246

Reputation:

syntax - c++ - Cant make my code works correctly

I'm trying to make my program calcul all these multiplications: 999*999 , 999*998, 998*998, 998*997, ......... Until 100*100.

Right now, it only calcul 999*999 998*998 997*997 ... 100*100. I don't get why? Can you take a look on my code? Thanks BR

#include <iostream>
#include <vector>
#include <cmath>


int main () {
    int i = 999;
    int j = 999;
    while (j >= 100) {
        i == j ;
        while (i >= j-1) {
            std::cout << i*j  << std::endl;
            i -= j;
        }
        j = j-1;
    }

    return 0; 
}

Upvotes: 0

Views: 70

Answers (3)

Flynsee
Flynsee

Reputation: 596

You are not seeing your loops correctly. Try to write the numbers you want to compute in a table first, and use it to build your loops.

For one value of your first loop variable - call it i, you want it multiplied by one, then two, then three (etc), values of j.

Regardless of what those values of j actually are, your loops should look like:

for(int i=999; i>=100; --i)
     for(int j=999; j>=i; j--)
           ; //computation goes here

Here you clearly see that for one value of i, you will use one value of j when i=999, then two values of j, then thre...

If you are new at coding, I would recommend starting with for loops and switch to while when you feel comfortable with the former ones.

Upvotes: 2

felix
felix

Reputation: 2222

I was trying to correct your code, but the inner while loop really should be deleted. After I deleted it, I can't tell whether I am rewriting it or correcting it. Anyway, it is delete, no need of it at all.

Here is the right code :

#include <iostream>
#include <vector>
#include <cmath>

int main () {
  int i = 999;
  int j = 999;
  while (j >= 100) {
    std::cout << i << " " << j << std::endl;

    if (i==j)
      --j;
    else
      --i;
  }

  return 0;
}

The logic is simple, whenever i==j, we --j. Whenever i!=j, we --i. We begin with i and j at the same position, during the loop, when i is one step behind j, i takes a step. When i and j is at the same position, j takes a step.

Upvotes: 0

Jonas
Jonas

Reputation: 7017

You can use two for loops like this:

#include <iostream>

int main()
{
    for (int i = 999; i > 99; --i)
    {
        for (int j = 0; j < 2; ++j)
        {
            std::cout << i * (i - j) << std::endl;
        }
    }
}

Upvotes: 0

Related Questions