Repeat odd numbers with do while

Asked

Viewed 64 times

1

Hi,

I need to make a code inside a switch, which reproduces all odd numbers from 0 to 200, with the repeating structure do while. I googled and only found with for. I tried to put the "odd 200%2!= 0" inside the do, but the problem persists; keeps repeating all the numbers from 0 to 200, including the pairs. The Code is like this:

case '3': {    // com problemas!!

    impar0a200%2!=0;

    do
    {
        cout<<"\n Os números a seguir são os ímpares entre 0 e 200:  " <<impar0a200;
        impar0a200++;
    }   while (impar0a200<=200);


    break;
}

2 answers

0


The verification impar0a200%2 != 0 is correct, just then use this condition in a if and being true, display the number.

if (impar0a200 % 2 != 0) {
  cout << impar0a200 << endl;
}

This condition should be inside your do/while, thus displaying all odd numbers until the end of the loop.


See an example using part of your code:

#include <iostream>

using namespace std;

int main() {
  char teste = '3';
  int impar0a200 = 0;

  switch (teste) {
    case '3': {         
      cout << "\nOs números a seguir são os ímpares entre 0 e 200: " << endl;

      do {
        if (impar0a200 % 2 != 0) {
          cout << impar0a200 << endl;
        }

        impar0a200++;
      } while (impar0a200 <= 200);

      break;
    }
  }

}

See online: https://repl.it/repls/PopularCleverPrediction

  • 1

    Very grateful. Was missing put the if, this was the main. Thank you Daniel Mendes.

0

In this particular case it could simplify to:

case '3': {
    impar0a200 = 1;
    cout<<"\n Os números a seguir são os ímpares entre 0 e 200:  " << endl;
    do
    {
        cout << "\t" << impar0a200;
        impar0a200 += 2;
    } while (impar0a200 <= 200);
    break;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.