Home > OS >  How to properly set up the condition in a do-while loop (C)
How to properly set up the condition in a do-while loop (C)

Time:10-15

While finishing an assignment I had to figure out how to check if the first two numbers of an input are of certain combination. While I have the idea what to do, I seem to have an error in the first part of my code. I wanted to ''isolate'' the first two numbers by dividing the input by 10 while the input is more than 2. I wrote this block of code

do
    {
        card_number = card_number / 10;
    }
    while (card_number > 2);

I was expecting the result to be '45' for example, but everytime I run the code and use printf to see the result, the only thing coming back is a zero.

CodePudding user response:

If you're trying to isolate the first two digits of card_number, then your condition should check that the length of the number is 2, not the value. Another way to do this is to keep dividing by 10 if the value is greater than 100.

#include <stdio.h>

int main(void) {
  int card_number = 450;
  printf("%i\n", card_number);

  while(card_number > 100) {
    card_number = card_number / 10;
  }

  printf("%i\n", card_number);
  return 0;
}

(Since you're trying to isolate the first two digits, I assume the value does start out greater than 100.)

CodePudding user response:

Updated to "isolate" first 2 digits...

I think this is what you're asking ...

int main() {
  //TEST CASES = Longer and Shorter than 2 digits
  //Comment and uncomment c_num as required for testing both cases

  long c_num = 1234567812345678;

  //long c_num = 12;

  int count = 0;

  long n = c_num;
  long long n1 = c_num, n2 = c_num; // n2 will hold the first two digits. 

  while (n) {
    n2 = n1;
    n1 = n;
    n /= 10;
  }
  printf("The first 2 numbers of the long are %lld\n", n2);

  /* Run loop till num is greater than 0 */
  do {
    /* Increment digit count */
    count  ;
    /* Remove last digit of 'num' */
    c_num /= 10;
  }
  while (c_num != 0);

  printf("Total digits: %d\n", count);

  if (count > 2) {
    /* Do work */
    printf("Total digits is more than 2");
  } else {
    /*Do other work */
    printf("Total digits is NOT more than 2");
  }

  return 0;
}
  •  Tags:  
  • c
  • Related