Thread: return function working too soon?

  1. #1
    Eagle_o_Fire
    Guest

    Question return function working too soon?

    Hi I have a small assignment that Im doing. It has a text menu and user enters numbers to call certain functions. All but one of the functions work correctly. The main method calls a couple of functions including the menu fuction which then calls the Pyramid function below. The output should look something like what is below if the user enters 'C'
        A
      ABA
    ABCBA
    I call it and it will show me the first prompt, then it will display the menu once again. It is weird because the function asks for a character, the menu calls for a integer, but i can use an integer or a character and it will work with its corresponding function.

    Here is the code for the function:

    Code:
    void Pyramid()
    {
    	char character;
    	char current;
    	char current_line;
    	int spaces = 0;
    
    	clrscr(); /*clears screen*/
    
      printf("Please enter an uppercase character\n");
    		scanf("%c", &character);
    	character = toupper(character); /*converts to uppercase*/
    
    	for (current_line = 'A'; current_line <= character; current_line++) { /*to calculate total number of lines and when to stop printing*/
    		spaces = (character - current_line - 1); /*sets number of spaces for a particular line*/
    		for (spaces = spaces; spaces >= 0; spaces--) { /*displays spaces*/
    			printf(" ");
    		}
    		for (current = 'A'; current < current_line + 1; current++) { /*displays ascending characters*/
    			printf("%c",current);
    		}
    		current = current - 1; /*prevents repeating characters*/
    		for (current = current - 1; current >= 'A'; current--) { /*displays decending characters*/
    			printf("%c",current);
    		}
    		printf("\n"); /*starts next line*/
    	}
      //return 0;
    } /*end pyramid*/
    One thing I did notice though if I ran it as a stand alone program everything worked fine. Im rather stumped actually. Does anyone know why it seems to be missing the 'for' statements and returning, (even though i have commented it out as a precaution). Thanx

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    I compiled it and it runs just fine for me.
    I didn't quite get your problem. Did it promt you to enter another character after printing the first pyramid? Then it might be a loop in the function calling this function, ie:
    Code:
    int main()
    {
       for(;;)
       {
          Pyramid();
       }
       return 0;
    }
    Another thing, in one of your for-loops you have:
    spaces = spaces

    which is absolutely unecessary. Leave that field blank instead:
    for(; spaces >= 0; spaces--)
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Eagle_o_Fire
    Guest
    OK, i removed the spaces = spaces, it was originally int here as a fail safe, hopefully preventing errors.
    Here is what I get after I select '3' from the menu

    Please enter an uppercase character

    Please enter your choice
    **************************
    0. Display Help (this menu)
    1. Determine the squares and cubes or a range of integers
    2. Determine a suitable sport
    3. Display a pyramid
    4. Calculate how long a bank balance will last
    5. Exit the program


    From here I can either enter values for the pyramid function or the menu function and it will work accordingly. There it asks for a charachter, but doesnt give me a chance to enter it until after it has displayd the menu again. I dont understand why it is displaying the menu again. This time I also included the full code, a bit long winded, but Im pretty thrown
    Code:
    #include <stdio.h> /*standard input output*/
    #include <stdlib.h> /*for extra commands, eg. exit command */
    #include <conio.h> /*for extra commands, eg. clear screen command*/
    #include <ctype.h> /*for extra commands, eg. uppercase command*/
    
    
    /*Declares Functions*/
    void SquareCube();
    void Sport();
    void Pyramid();
    void Bank();
    void Exit();
    void StudentDetails();
    void menu();
    
    
    
    /***************************************************************************************************
    * Main method                                                                                      *
    ***************************************************************************************************/
    main ()
    {
      StudentDetails(); /*calls studentdetails*/
      menu(); /*calls menu*/
    } /*end main*/
    
    
    
    /***************************************************************************************************
    * Contains user menu to run program                                                                *
    ***************************************************************************************************/
    void menu()
    {
    	int user_option;
    
    	while (user_option) { /*takes users choice to goto seperate program functions*/
      	printf("\n");
      	printf(" Please enter your choice\n");
      	printf("**************************\n");
      	printf("0. Display Help (this menu)\n");
      	printf("1. Determine the squares and cubes or a range of integers\n");
      	printf("2. Determine a suitable sport\n");
      	printf("3. Display a pyramid\n");
      	printf("4. Calculate how long a bank balance will last\n");
      	printf("5. Exit the program\n");
      		scanf("%d", &user_option);
    
      	if (user_option == 0) menu();
      	else if (user_option == 1) SquareCube(); /*calls SquareCube function*/
      	else if (user_option == 2) Sport(); /*calls Sport function*/
      	else if (user_option == 3) Pyramid(); /*calls Pyramid function*/
      	else if (user_option == 4) Bank(); /*calls Bank function*/
      	else if (user_option == 5) Exit(); /*calls Exit function*/
        else {
        	printf("Invalid option. Please try again...\n");
          menu();
        }
    	}
    } /*end menu*/
    
    
    
    /***************************************************************************************************
    * Determines squares and cubes of entered numbers                                                  *
    ***************************************************************************************************/
    void SquareCube()
    {
    	int i,m,n;
    	int square;
    	int cube;
    	int swap;
    
    	clrscr(); /*clears screen*/
    
    	printf("Please enter two integers:\n"); /*takes integers from user*/
    		scanf("%d%d", &m,&n);
    
    	while (m < 0 || n < 0) { /*checks for numbers below zero*/
    		printf("Invalid entry. Use numbers above 0\n");
    		printf("Please re-enter two integers:\n");
    			scanf("%d%d", &m,&n);
    	}
    
    	if (n < m) { /*swaps digits to make first calculation the smallest number*/
    		swap = n;
    		n = m;
    		m = swap;
    	}
    
    	printf("\n");
    	printf("Number\t\tSquare\t\tCube\n"); /*displays column headings with tab breaks in between*/
    	for(i = 0; m <= n; m = i++) {
    		square = m * m; /*calculates square of current number*/
    		cube = m * m * m; /*calculates cube of current number*/
    		printf("%d\t\t%d\t\t%d\n", m, square, cube); /*displays results under column headings*/
    	}
    	return;
    } /*end squarecube*/
    
    
    
    /***************************************************************************************************
    * Takes an entered number and determines which sport is best                                       *
    ***************************************************************************************************/
    void Sport()
    {
    	float temp;
    	float highest;
    	float lowest;
    	float running_temp;
    	float average = 0;
    	float counter = 0;
    
    	clrscr(); /*clears screen*/
    
    	while(temp) {
    		printf("Please enter the temperature (enter 99 to exit):\n"); /*takes temperature from user*/
    			scanf("%f", &temp);
    
    		if (temp >= 99 || temp <= -99) {	/*checks whether to exit this function*/
    			if (counter == 0) { /*safeguards against division by zero program crash*/
    				printf("No temperatures entered\n");
    				return 0;
    			}
    			else {
    				average = running_temp / counter; /*calculates average on function exit*/
    				printf("Highest temperature: %f\n", highest); /*displays results*/
    				printf("Lowest temperature: %f\n", lowest);
    				printf("Average temperature: %f\n", average);
    				return 0;
    			}
    		}
    		else {
    			if (counter == 0) { /*sets benchmark highest and lowest temperatures*/
    				lowest = temp;
    				highest = temp;
    			}
    			if (temp > highest) { /*checks for new highest temperature*/
    				highest = temp;
    			}
    			else if (temp < lowest) { /*checks for new lowest temperature*/
    				lowest = temp;
    			}
    			running_temp = running_temp + temp; /*sums up entered temperatures to find average*/
    			counter = counter + 1; /*counter to work out average, determines dividing number*/
          if (temp > 30) printf("Suitable sport is swimming\n"); /*determines which sport is best*/
    			else if (temp <= 30 && temp > 20) printf("Suitable sport is tennis\n");
    			else if (temp <= 20 && temp > 0) printf("Suitable sport is golf\n");
    			else if (temp <=0 && temp > -10) printf("Suitable sport is skiing\n");
    			else printf("Suitable sport is chinese checkers\n");
    		}
    	}
    } /*end sport*/
    
    
    
    /***************************************************************************************************
    * Displays a pyramid of characters                                                                 *
    ***************************************************************************************************/
    void Pyramid()
    {
    	char character;
    	char current;
    	char current_line;
    	int spaces = 0;
    
    	clrscr(); /*clears screen*/
    
      printf("Please enter an uppercase character\n");
    		scanf("%c", &character);
    	character = toupper(character); /*converts to uppercase*/
    
    	for (current_line = 'A'; current_line <= character; current_line++) {
    		spaces = (character - current_line - 1); /*sets number of spaces for a particular line*/
    		for (; spaces >= 0; spaces--) { /*displays spaces*/
    			printf(" ");
    		}
    		for (current = 'A'; current < current_line + 1; current++) { /*displays ascending characters*/
    			printf("%c",current);
    		}
    		current = current - 1; /*prevents repeating characters*/
    		for (current = current - 1; current >= 'A'; current--) { /*displays decending characters*/
    			printf("%c",current);
    		}
    		printf("\n"); /*starts next line*/
    	}
      //return 0;
    } /*end pyramid*/
    
    
    
    /***************************************************************************************************
    * Determines the time an amount of money will last in a bank account                               *
    ***************************************************************************************************/
    void Bank()
    {
    	float bal_new;
    	float bal;
      float interest_rate;
    	float earned;
    	float withdrawl;
    	int years = 1;
    
    	clrscr(); /*clears screen*/
    
    	printf("Please enter account balance\n"); /*takes starting values from user*/
    		scanf("%f", &bal);
    	printf("Please enter yearly interest rate as percentage\n");
    		scanf("%f", &interest_rate);
    	printf("Please enter yearly withdrawl\n");
    		scanf("%f", &withdrawl);
    
    	printf("\nYear\t\tBalance\t\tInterest\tWithdrawn\tNew Balance\n"); /*displays column headings*/
    	for (bal = bal; bal >= 0; years++) { /*loops until balance is less than 0*/
    		earned = (bal * (1 + (interest_rate /100))) - bal; /*calculates earnt interest*/
    		bal_new = ((bal * (1 + (interest_rate / 100))) - withdrawl); /*calculates the new balance*/
    
    		if (bal < withdrawl) { /*displays last wihdrawl and number of years account lasts for*/
    			withdrawl = bal + earned;
    			printf("%d\t\t%f\t%f\t%f\t0\n", years, bal, earned, withdrawl);
    			printf("Number of years for account to reach zero is %d\n", years);
    			return;
    		}
    		else { /*displays running totals*/
    			printf("%d\t\t%f\t%f\t%f\t%f\n", years, bal, earned, withdrawl, bal_new);
    			bal = bal_new;
    		}
    	}
    } /*end bank*/
    
    
    
    /***************************************************************************************************
    * Exits program after completing a loop                                                            *
    ***************************************************************************************************/
    void Exit()
    {
    	int pause;
    
    	clrscr(); /*clears screen*/
    
    	printf("Please wait while program closes.....");
    	for (pause = 0; pause <= 10000000; pause = pause +1); /*counter to delay exit*/
    	exit(0);
    } /*end exit*/
    
    
    
    /***************************************************************************************************
    * Prints out student details                                                                       *
    ***************************************************************************************************/
    void StudentDetails()
    {
    	clrscr(); /*clears screen*/
    
    	printf("Name: \n");
      printf("Unit: \n");
      printf("Tutors Name: \n");
      printf("Tutorial Time: \n");
      return;
    } /*end studentdetails*/

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    So, what's so bad about fflush?

    <edit>HEY??? Why didn't this post appear at the bottom?</edit>
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  5. #5
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    I haven't looked at your program real closely but here are a couple of things I spotted in your menu() function:

    Your basic logic is:
    while(condition)
    {
    get user input
    perform chosen function
    }
    return

    You did not initialize user_option. Use a do-while loop instead. There's also no need for an exit function inside the loop. You can have it outside once your condition is not met. This seems more intuitive to me. Just my opinion.

    The reason why your pyramid function accepts either a digit or a character is because it treats the digit as a character. See what happens when you try a number like "14". Your menu on the other hand will not accept a character. It will bomb when you do.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  6. #6
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Okay I took a closer look at your program and found the problem. The reason why your pyramid function is not working is because there's still data in your buffer when you used scanf(). This can be easily resolved by calling fflush(stdin) before every scanf function. Perhaps you should look into using fgets instead.

    Also in your Sport() function, you declared it as void. However, you have some return 0 statements in there.

    Hope that helps.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  7. #7
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>This can be easily resolved by calling fflush(stdin) before every scanf function.
    Cshot, you didn't just post _that_... did you??
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  8. #8
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Yeah I did...I'm assuming now that's not right. I never used fflush before

    Enlighten me pls
    Last edited by Cshot; 09-11-2002 at 01:20 PM.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  9. #9
    Eagle_o_Fire
    Guest

    Smile

    OK thanks for your quick help. I found another few little errors like the squares/cubes not working as they should, I used the fflush(stdin); and everything is going great!!!
    Thanks alot for your help =)

  10. #10
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Originally posted by Cshot
    Yeah I did...I'm assuming now that's not right. I never used fflush before

    Enlighten me pls
    It's a sin my friend, and you don't want to be recommending it to others.

    [edit]
    Use
    >>while (getchar() != '\n');
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  11. #11
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Forgive me Hammer, for I have sinned...

    I'm sure you'll be glad to hear that this have been my first and last use of fflush. Although one time is probably one time too many.

    >> while (getchar() != '\n');
    Hear that Eagle? Use this instead. Works much more nicely.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  12. #12
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    wooh, stop there! I ain't no priest!

    >> first and last use of fflush
    Well, it's OK on output streams, just not input ones.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  13. #13
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    That is weird Magos...maybe your clock is fux0red by those damned Talibans.

    EDIT - actually this was why:
    http://www.cprogramming.com/cboard/s...threadid=24722
    Last edited by Cshot; 09-11-2002 at 05:06 PM.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  2. Another weird error
    By rwmarsh in forum Game Programming
    Replies: 4
    Last Post: 09-24-2006, 10:00 PM
  3. Alegro closes out on me
    By campsoup1988 in forum C++ Programming
    Replies: 8
    Last Post: 04-03-2006, 10:40 AM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM