-1

I want to write a program where the user can input a number between 1 and 100. The program will then display that number with all numbers preceding it until 1. Each line should have 10 numbers only. So basically it should look like:


enter image description here


I used this code:


#include <stdio.h>
#include <conio.h>

void main(void) {
    int num, counter;
    counter = 1;

    printf("Input a number between 1 and 100: ");
    scanf("%d", &num);

    printf("\n");

    if (num> 1  && num < 100)
        while (num > 0) {
            printf("%d %d %d %d %d %d %d %d %d %d \n", num, num - 1, num - 2, num - 3, num - 4, num - 5, num - 6, num - 7, num - 8, num - 9);
            num -= 10;
        }
    else
        printf("\nInvalid value. Please enter a different number.");

    getch();
}

But at the end, it still keeps on showing 0 and negative numbers.

enter image description here

How do I fix this?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Mr_D
  • 1
  • 1
  • 1
  • 2
    Hint: you can write part of the line only, and then printing `"\n"` conditionally. – Jarod42 Nov 27 '18 at 13:20
  • 2
    Please don't post pictures of text. Post text as text. – Jabberwocky Nov 27 '18 at 13:27
  • `num -= 10` gives in example `num = 1`. The condition `num > 0` is true. You'll print then `1 0 -1 -2 -3 -4 -5 -6 -7 -8` – Cid Nov 27 '18 at 13:31
  • Your whole approach is awkward. Just print the numbers without `\n` and every 10 numbers printed you print a `\n`. – Jabberwocky Nov 27 '18 at 13:35
  • `void main(void)` --> `int main(void)` See e.g https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c – Bob__ Nov 27 '18 at 14:23

1 Answers1

2

Your problem is the line

while(num>0)

num may be 3, which is bigger than zero. However, in your printf statement you print numbers up to num-9 which would be -6. Try printing one number at a time and checking each time if you have printed your desired 10 numbers / line. You could (for example) use the modulo-operator to calculate the remainder if divided by 10. If that is zero you can start a new line.

Max
  • 39
  • 3