Thread: C programming beginner, problem with a loop

  1. #1
    Registered User
    Join Date
    Jun 2017
    Posts
    2

    C programming beginner, problem with a loop

    Please help!

    A program is required that prompts the user for a number between 1 and 20. The prompt should also tell the user “enter 0 to end”. The program will then print a series of asterisks to represent the number. If the user enters 0, the program stops.

    Program should print “invalid input” and ask for next input if user enters anything larger than 20 or less than 0.

    Did everything except last statement. Can’t do it without interrupting the loop.

    Please advice.

    Code:
    #include<stdio.h>
    int main(void)
    
    
    {
        int i=0;
        int asterisks;
    
    
        printf("Enter a number between 1 and 20 ( Enter 0 to end) :");
        scanf("%d", &asterisks);
    
    
        for(i=0; i<asterisks; i++)
        printf("%c ", '*');
    
    
           while(asterisks!=0)
       {
              printf("\nEnter a number between 1 and 20 ( Enter 0 to end) :");
              scanf("%d", &asterisks);
    
    
           /* if(asterisks>=21 || asterisks<0)
              printf("invalid input!"); */
    
    
              for(i=0; i<asterisks; i++)
              printf("%c ", '*');
       }
    if(asterisks==0)
        printf("\nThanks and bye!");
    
    
    return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    So you didn't try this?
    Code:
    if(asterisks>=21 || asterisks<0) {
              printf("invalid input!");
    } else { 
              for(i=0; i<asterisks; i++)
                   printf("%c ", '*');
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2017
    Posts
    2
    Thank you!

    It works)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 12-10-2012, 11:36 AM
  2. Replies: 6
    Last Post: 12-14-2011, 11:31 AM
  3. Beginner Problem with Loop
    By ToweyLeake in forum C++ Programming
    Replies: 4
    Last Post: 10-11-2011, 10:12 AM
  4. beginner loop help
    By helloalyssa in forum C++ Programming
    Replies: 3
    Last Post: 10-25-2010, 09:08 PM
  5. Windows programming for beginner (Absolute beginner)
    By WDT in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2004, 11:21 AM

Tags for this Thread