Njgardner90
Njgardner90

Reputation: 71

Condition within for loop not executing

I'm writing a trivial program that doubles the amount of rice grains per each square on a chess board. I'm trying to work out the amount of squares required for at least 1 000 000 000 grains of rice. The problem is, what ever I try, the second if statement gets skipped even though 'test' is false after first iteration.

I've tried an else after the if statement, but the else is skipped when 'test' variable is false.

    constexpr int max_rice_amount = 1000000000;  
    int num_of_squares = 0;
    int rice_grains = 0;
    bool test = true; // so we can set rice_grains amount to 1

    for (int i = 0; i <= max_rice_amount; i++)
    {
        if (test == true)
        {
            rice_grains = 1;  // This will only happen once
            test = false;
        }
        else if (test == false)
            rice_grains *= 2;

        ++num_of_squares;
        std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";

    }

Upvotes: 0

Views: 76

Answers (2)

Bathsheba
Bathsheba

Reputation: 234715

The else causes the issue. But C++ is more powerful than you can imagine. Rework your loop to

for (
    int rice_grains = 1, num_of_squares = 1;
    rice_grains <= max_rice_amount;
    rice_grains *= 2, ++num_of_squares
){

with

 std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";

as the loop body; and weap at the beauty.

Upvotes: 1

JVApen
JVApen

Reputation: 11317

Looking at the problem description, this looks a good fit for a while loop or a do-while loop.

#include <iostream>

void f()
{
    constexpr int max_rice_amount = 1000000000;  

    int num_of_squares = 1;
    int rice_grains = 1;

    while (rice_grains < max_rice_amount)
    {
        std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";
        rice_grains *= 2;
        ++num_of_squares;
    }
}

Code at compiler explorer

Here you recognize 3 big blocks:

  • Initialization
  • The 'until' condition in the while
  • The manipulation

Upvotes: 0

Related Questions