David Scarpa
David Scarpa

Reputation: 11

while loop countdown from integer input by user

I have a program that runs fine, but I need some help transforming it into a program that instead of taking a fixed integer and counting to 0 then back up to fixed integer, takes a integer entered via scanf and does so.

here is code

#include <stdio.h>
int main()
{

int count = 10;
while (count >= 1)
{
    printf("%d \n", count);
    count--;
}

printf("*****\n");


while (count <= 10)
{
    printf("%d \n", count);
    count++;
}
getchar();
return 0;
}

Upvotes: 0

Views: 2771

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

I can suggest the following solution. The program outputs numbers horizontally instead of vertically.

#include <stdio.h>

int main( void )
{
    while (1)
    {
        printf("Enter a number (0 - exit): ");

        int n;

        if (scanf("%d", &n) != 1 || (n == 0)) break;

        int i = n;

        do
        {
            printf("%d ", i);
        } while (n < 0 ? i++ : i--);

        i = 0;

        while (( n < 0 ? i-- : i++ ) != n) printf("%d ", i);

        putchar('\n');
    }

    return 0;
}

Its output might look like

Enter a number (0 - exit): 10
10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10
Enter a number (0 - exit): -10
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Enter a number (0 - exit): 0

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596703

Simply replace the two occurances of 10 with a variable, and then populate that variable from user input.

#include <stdio.h>

int main() {

    int number;
    scanf("%d", &number);

    int count = number;
    while (count >= 1) {
        printf("%d \n", count);
        count--;
    }

    printf("*****\n");

    while (count <= number) {
        printf("%d \n", count);
        count++;
    }

    getchar();
    return 0;
}

Upvotes: 1

Related Questions