Home > OS >  C program that displays all numbers in between the two integer inputs in ascending order
C program that displays all numbers in between the two integer inputs in ascending order

Time:11-11

I tried to do this activity but there is always an extra "result" in the output output:

Enter integer a:10
Enter integer b:1

Result: 1
Result: 10
Result: 9
Result: 8
Result: 7
Result: 6
Result: 5
Result: 4
Result: 3
Result: 2
Result: 1
Result: 0

ideal output:

Enter integer a:10
Enter integer b:1
Result: 10
Result: 9
Result: 8
Result: 7
Result: 6
Result: 5
Result: 4
Result: 3
Result: 2
Result: 1
#include <stdio.h>

main() {
  int a;
  int b;

  printf("Enter integer a:");
  scanf("%d", &a);

  printf("Enter integer b:");
  scanf("%d", &b);

  do {
    printf("Result: %d\n", b);
    b--;
  } while (a <= b);

  do {
    printf("Result: %d\n", a);
    a--;
  } while (a >= b);
}

CodePudding user response:

use while instead of do-while, do-while will always run one time.

CodePudding user response:

Just remove the first while loop that generates the unwanted output (the first Result: 1) and modifies the limit used by the second loop (the last Result: 0).

#include <stdio.h>

main() {
  int a;
  int b;

  printf("Enter integer a:");
  scanf("%d", &a);

  printf("Enter integer b:");
  scanf("%d", &b);

  do {
    printf("Result: %d\n", a);
    a--;
  } while (a >= b);
}

So after taking the additional requirement into account:

#include <stdio.h>

main() {
  int a;
  int b;

  printf("Enter integer a:");
  scanf("%d", &a);

  printf("Enter integer b:");
  scanf("%d", &b);

  if(b > a)
  {
      do {
        printf("Result: %d\n", b);
        b--;
      } while (a <= b);
  }
  else
  {
      do {
        printf("Result: %d\n", a);
        a--;
      } while (a >= b);
  }
}

I prefer a if statement since it communicates the intention clearer than changing the do ... while to while.

  •  Tags:  
  • c
  • Related