Thread: Home work issues..

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    19

    Home work issues..

    Alright so i'm trying to create a program that prints a number of dots specified by the user, there 4 options to do any loop type or to exit the menu. i'm having problems making it so that after you enter a value and it displays the specified number of dots it clears the results. Also we have to make it so that if a negative integer is entered it still prints out the appropriate amount of dots ie: user puts -9 it prints 9 dots, i know you use the abs() function but it doesn't seem to be working for me. i realize that you guys aren't suppose to just tell me the answer but any suggestions or help would be greatly appreciated. i'm assuming my problem with the abs function is i'm not using it correctly but i'v tried searching and i can't figure out what exactly i'm doing wrong. Please use case 1 as the example for the rest because i'm trying to implement everything on one case at a time, thanks everyone!

    Code:
    int main()
    {
    
    
                                            ///initialization statements
        int Num1 = 0;
        char dot = '.';
    
    
    
    
    
    
                                            ///Main menu options of program
        printf("Choose a loop type to demonstrate\n");
        printf(" 1   While loop\n");
        printf(" 2   do-while loop\n");
        printf(" 3   for loop\n");
        printf(" 4   quit the program\n\n");
        printf("Enter your choice: ");
                                            ///switch statment and data validation in do while statement
            do
            {
                if(!(scanf("%d", &Num1)))
                {
                    printf("\nPlease enter a valid menu choice");
                    return -1;
    
    
                }
    
    
                else if(Num1 <= 0 || Num1 >= 5)
                {
                    printf("This is not a valid menu option");
                    return -2;
                }
    
    
    
    
                    switch(Num1)
                    {
                         if(!(scanf("%d", &Num1)));
                         {
                             printf("\n Please enter a valid menu choice");
                         }
                        case 1:
                            printf("\nHow many dots should i print? ");
                            Num1 = abs(Num1);
                            scanf("%d",&Num1);
    
    
                            while(Num1 > 0)
                            {
                                printf("%c", dot);
                                --Num1;
                            }
                            printf("\n");
                            system("pause");
                            system("cls");
                            break;
    
    
                        case 2:
                            printf("\nHow many dots should i print? ");
                            scanf("\n%d", &Num1);
                            do
                            {
                                printf("%c", dot);
                                --Num1;
    
    
    
    
                            }
                             while(Num1 > 0);
                             printf("\n");
                             break;
    
    
    
    
                        case 3:
                           printf("\nHow many dots should i print? ");
                           scanf("\n%d", &Num1);
    
    
                           for( ; Num1 > 0;  --Num1);
                            {
    
    
                             printf("%c", dot);
                            }
                            break;
    
    
    
    
                        case 4:
                            printf("\nThanks for playing! Bye!");
                            break;
    
    
    
    
                        default:
                            printf("THIS SHOULD NEVER HAPPEN");
                            system("pause");
                    }
    }
            while(Num1!= 4);
    
    
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    For starters, I don't see any #includes. You need to include "stdlib.h" for "abs".

    Secondly, I don't think it's the "abs" that is the problem, but the logic. It would be more clear if the formatting were more consistent. I also removed the "system" calls as they aren't necessary.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        //initialization statements
        int Num1 = 0;
        char dot = '.';
    
        //Main menu options of program
        printf("Choose a loop type to demonstrate\n");
        printf(" 1   While loop\n");
        printf(" 2   do-while loop\n");
        printf(" 3   for loop\n");
        printf(" 4   quit the program\n\n");
        printf("Enter your choice: ");
    
        //switch statment and data validation in do while statement
        do
        {
            if(!(scanf("%d", &Num1)))
            {
                printf("\nPlease enter a valid menu choice");
                return -1;
            }
            else if(Num1 <= 0 || Num1 >= 5)
            {
                printf("This is not a valid menu option");
                return -2;
            }
    
            switch(Num1)
            {
                if(!(scanf("%d", &Num1)));
                {
                    printf("\n Please enter a valid menu choice");
                }
                case 1:
                    printf("\nHow many dots should i print? ");
                    Num1 = abs(Num1);
                    scanf("%d",&Num1);
                    while(Num1 > 0)
                    {
                        printf("%c", dot);
                        --Num1;
                    }
                    printf("\n");
                    //system("pause");
                    //system("cls");
                    break;
                case 2:
                    printf("\nHow many dots should i print? ");
                    scanf("\n%d", &Num1);
                    do
                    {
                        printf("%c", dot);
                        --Num1;
                    }
                     while(Num1 > 0);
                     printf("\n");
                     break;
                case 3:
                    printf("\nHow many dots should i print? ");
                    scanf("\n%d", &Num1);
                    for( ; Num1 > 0;  --Num1);
                    {
                        printf("%c", dot);
                    }
                    break;
                case 4:
                    printf("\nThanks for playing! Bye!");
                    break;
                default:
                    printf("THIS SHOULD NEVER HAPPEN");
                    //system("pause");
            }
        } while(Num1!= 4);
    
        return 0;
    }
    Overall, not a bad attempt. But some things worth mentioning:

    - On line 21, you read a menu option into "Num1" and exit if it's invalid.
    - On line 26, you validate the input and exit if it's invalid.

    Is this what you want to do, or do you want it to prompt the user again?

    - After you enter the "switch" block, you scan in a value again (line 34). I'm not sure what kind of behavior that causes, but I know it's not necessary in your code. Go right to case 1 (you've already received and validated the menu choice, after all).

    - In case 1, you prompt for input, take the absolute value, THEN read the input. This is backwards.
    - Furthermore, you're storing the read value into "Num1"! You should have separate variables for the menu selection input and the number of dots input. You need the value of "Num1" at the end of the loop, after all.

    I didn't really check out the other cases - use the last two bits of advice for those cases, if necessary.

    And if you're prompting for menu input each iteration of the loop, you might as well put the menu information in the loop.
    Last edited by Matticus; 10-08-2013 at 05:24 PM.

  3. #3
    Registered User
    Join Date
    Oct 2013
    Posts
    19
    Quote Originally Posted by Matticus View Post
    For starters, I don't see any #includes. You need to include "stdlib.h" for "abs".

    Secondly, I don't think it's the "abs" that is the problem, but the logic. It would be more clear if the formatting were more consistent. I also removed the "system" calls as they aren't necessary.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        //initialization statements
        int Num1 = 0;
        char dot = '.';
    
        //Main menu options of program
        printf("Choose a loop type to demonstrate\n");
        printf(" 1   While loop\n");
        printf(" 2   do-while loop\n");
        printf(" 3   for loop\n");
        printf(" 4   quit the program\n\n");
        printf("Enter your choice: ");
    
        //switch statment and data validation in do while statement
        do
        {
            if(!(scanf("%d", &Num1)))
            {
                printf("\nPlease enter a valid menu choice");
                return -1;
            }
            else if(Num1 <= 0 || Num1 >= 5)
            {
                printf("This is not a valid menu option");
                return -2;
            }
    
            switch(Num1)
            {
                if(!(scanf("%d", &Num1)));
                {
                    printf("\n Please enter a valid menu choice");
                }
                case 1:
                    printf("\nHow many dots should i print? ");
                    Num1 = abs(Num1);
                    scanf("%d",&Num1);
                    while(Num1 > 0)
                    {
                        printf("%c", dot);
                        --Num1;
                    }
                    printf("\n");
                    //system("pause");
                    //system("cls");
                    break;
                case 2:
                    printf("\nHow many dots should i print? ");
                    scanf("\n%d", &Num1);
                    do
                    {
                        printf("%c", dot);
                        --Num1;
                    }
                     while(Num1 > 0);
                     printf("\n");
                     break;
                case 3:
                    printf("\nHow many dots should i print? ");
                    scanf("\n%d", &Num1);
                    for( ; Num1 > 0;  --Num1);
                    {
                        printf("%c", dot);
                    }
                    break;
                case 4:
                    printf("\nThanks for playing! Bye!");
                    break;
                default:
                    printf("THIS SHOULD NEVER HAPPEN");
                    //system("pause");
            }
        } while(Num1!= 4);
    
        return 0;
    }
    Overall, not a bad attempt. But some things worth mentioning:

    - On line 21, you read a menu option into "Num1" and exit if it's invalid.
    - On line 26, you validate the input and exit if it's invalid.

    Is this what you want to do, or do you want it to prompt the user again?

    - After you enter the "switch" block, you scan in a value again (line 34). I'm not sure what kind of behavior that causes, but I know it's not necessary in your code. Go right to case 1 (you've already received and validated the menu choice, after all).

    - In case 1, you prompt for input, take the absolute value, THEN read the input. This is backwards.
    - Furthermore, you're storing the read value into "Num1"! You should have separate variables for the menu selection input and the number of dots input. You need the value of "Num1" at the end of the loop, after all.

    I didn't really check out the other cases - use the last two bits of advice for those cases, if necessary.

    And if you're prompting for menu input each iteration of the loop, you might as well put the menu information in the loop.
    Sorry i didn't copy and paste the #includes, but yes i have it in there. Yes i would like to be prompted again if the value entered does not match the options, i would also like it to prompt again and even after a valid menu option and dot value has been giving again the system pause, but i can't figure out how to do that without just making it produce the menu options all over again.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Then you shouldn't be exiting the program if the menu option is out of range. The trick here is to make use of the "default" label in the switch block.

    (Note: line numbers reference the code as I posted it in post #2.)

    Line 21: If the scanf fails, then just set the menu variable to zero.
    Line 26: Get rid of the else/if block (see comments for "Line 73" below).
    Line 34-37: Just delete these lines, they aren't contributing to the solution.
    Line 73: The default case can handle incorrect user input - just change "this should never happen" to "Invalid menu option".

    Now, if the user enters 1 - 4, the switch will execute the proper code. Anything else will result in an "invalid" message. Any any input except for 4 will result in the loop being repeated.

    As I mentioned previously, the menu should be at the top of the loop if you want to repeat it each iteration of the loop.

    Also, I'd suggest giving the menu input variable a more meaningful name. "menu_selection" or something like that is more informative than "Num1".

  5. #5
    Registered User loserone+_+'s Avatar
    Join Date
    Dec 2012
    Location
    Indonesia
    Posts
    112
    hm, another add by me,

    while(1) its better for unlimited scanf for that switch case until the user break it than do while loop i assume

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Note, you should check scanf explicitly for 1. Per the documentation:
    Quote Originally Posted by man 3 scanf
    Return Value


    These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.


    The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
    EOF is often defined as a negative number. That means, if scanf returns EOF, your code will assume it got valid input, since
    Code:
    if (!scanf())
    // becomes
    if (!EOF)
    // which may become
    if (! -1)
    // which evaluates to false, and skips the error handling
    The correct way is
    Code:
    if (scanf() != 1)  // this indicates error...of course, change 1 to however many items you are trying to scan
    Also, a while(1) with a break statement/flag is not any better here. In fact, it may be worse since if you use break in the case 4: it will only break out of the switch statement and not the while loop. You would need a separate variable to track whether you're quitting and check that separately after the switch statement, to break out of the loop. Unnecessary complication/work.

    In fact, a do-while loop is perfect for user input, since it always runs at least once, and you always want to ask the user for input at least once, before your program ends.

  7. #7
    Registered User
    Join Date
    Oct 2013
    Posts
    19
    Quote Originally Posted by Matticus View Post
    Then you shouldn't be exiting the program if the menu option is out of range. The trick here is to make use of the "default" label in the switch block.

    (Note: line numbers reference the code as I posted it in post #2.)

    Line 21: If the scanf fails, then just set the menu variable to zero.
    Line 26: Get rid of the else/if block (see comments for "Line 73" below).
    Line 34-37: Just delete these lines, they aren't contributing to the solution.
    Line 73: The default case can handle incorrect user input - just change "this should never happen" to "Invalid menu option".

    Now, if the user enters 1 - 4, the switch will execute the proper code. Anything else will result in an "invalid" message. Any any input except for 4 will result in the loop being repeated.

    As I mentioned previously, the menu should be at the top of the loop if you want to repeat it each iteration of the loop.

    Also, I'd suggest giving the menu input variable a more meaningful name. "menu_selection" or something like that is more informative than "Num1".
    i know what your saying, and i'v been trying to do it, but if i get rid of that if statement then it automatically runs straight to the default message because the variables are set to 0 i'm not sure how to get past it :x

    here's my code with the changes i'v made, also my case 3 loop only runs once and i'm not so sure why.

    Code:
    ///Name: Sean Bradley
    ///S#: s0454742
    /// Assignment - loops (While, do-while, For)
    
    
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    int main()
    {
    
    
        int Num1 = 0;
        int dotnum = 0;
        char dot = '.';
    
    
         do
            {
                                            ///States name and assignment
        printf("          Assignment 4 by Sean Bradley\n");
        printf("This assignment demonstrats three looping commands\n");
        printf("==================================================\n");
    
    
                                            ///initialization statements
    
    
    
    
    
    
    
    
                                            ///Main menu options of program
        printf("Choose a loop type to demonstrate\n");
        printf(" 1   While loop\n");
        printf(" 2   do-while loop\n");
        printf(" 3   for loop\n");
        printf(" 4   quit the program\n\n");
        printf("Enter your choice: ");
                                            ///switch statment and data validation in do while statement
    
    
                ///fflush(stdin);
                /*if(!(scanf("%d", &Num1)))
                {
                    printf("\nPlease enter a valid menu choice\n");
                    system("pause");
                    system("cls");
                    break;
    
    
                }*/
    
    
    
    
    
    
                    switch(Num1)
                    {
    
    
                        case 1:
                            printf("\nHow many dots should i print? ");
                            fflush(stdin);
                            scanf("%d",&dotnum);
                            dotnum=abs(dotnum);
                            while(dotnum > 0)
                            {
                                printf("%c", dot);
                                --dotnum;
                            }
                            printf("\n");
                            system("pause");
                            system("cls");
                            break;
    
    
                        case 2:
                            printf("\nHow many dots should i print? ");
                            dotnum=abs(dotnum);
                            fflush(stdin);
                            scanf("\n%d", &dotnum);
                            do
                            {
                                printf("%c", dot);
                                --dotnum;
    
    
    
    
                            }
                             while(dotnum > 0);
                             printf("\n");
                             system("pause");
                             system("cls");
                             break;
    
    
    
    
                        case 3:
                           printf("\nHow many dots should i print? ");
                           dotnum=abs(dotnum);
                           fflush(stdin);
                           scanf("\n%d", &dotnum);
    
    
                           for( ; dotnum > 0;  --dotnum);
                            {
                            printf("%c", dot);
    
    
                            }
    
    
                            printf("\n");
                            system("pause");
                            system("cls");
                            break;
    
    
                        case 4:
                            printf("\nThanks for playing! Bye!");
                            break;
    
    
                        default:
                            printf("\nvalid menu options are 1, 2, 3 and 4\n\n");
                            system("pause");
                            system("cls");
    
    
                        }
                    } while(Num1 != 4);
    
    
    return 0;
    }
    Last edited by Sean Bradley; 10-08-2013 at 08:21 PM.

  8. #8
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    your line 108 should be after line 110
    you do not check scanf return value
    FAQ > Why fflush(stdin) is wrong - Cprogramming.com
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with some c home work
    By cdub50 in forum C Programming
    Replies: 2
    Last Post: 01-30-2011, 01:21 AM
  2. home work
    By manav in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 03-29-2008, 02:39 PM
  3. Home Work
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 11-24-2003, 09:33 AM
  4. Work from home?
    By Shadow in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 03-25-2003, 06:09 AM
  5. home work help =)
    By pittster in forum C Programming
    Replies: 1
    Last Post: 03-20-2002, 09:30 PM